overgrown/src/strcmp.c

44 lines
1.5 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* Copyright (c) 20222024 DTB <trinity@trinity.moe>
* SPDX-License-Identifier: AGPL-3.0-or-later
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://www.gnu.org/licenses/.
*/
#include <stdio.h> /* fprintf(3), stderr */
#include <stdlib.h> /* size_t */
#include <sysexits.h> /* EX_USAGE */
char *program_name = "strcmp";
int main(int argc, char *argv[]){
if (argc < 3) {
fprintf(stderr, "Usage: %s string string...\n",
argv[0] == NULL ? program_name : argv[0]
);
return EX_USAGE;
}
/* This compares the Nth character of arg[2] onward with argv[1]'s Nth
* character, rather than comparing each arg with argv[1] sequentially. */
for (; *argv[1] != '\0'; ++argv[1]) { /* iterate chars in argv[1] */
for (size_t i = 2; i < argc; ++argv[i], ++i) { /* iterate &argv[2] */
/* this never overruns because of nul termination */
if (*argv[i-1] != *argv[i]) { return *argv[i-1] - *argv[i]; }
}
}
return 0;
}