Le lun. 16 nov. 2020 à 16:36, Ranier Vilela <email@example.com> a écrit :
> Em seg., 16 de nov. de 2020 às 11:18, Andrew Gierth <firstname.lastname@example.org> escreveu:
>> strcmp doesn't call strlen (in reasonable implementations) and strncmp
>> isn't necessarily any faster.
> Strncmp always is faster.
> Once strcmp, it will go to the end of the string, always.
Look at strcmp in the GNU C Library (glibc, used in linux systems):
Like I explained to you earlier, strcmp stops on the first difference,
or the first \0 (end of the shorter of the two string), whichever
So in the instance you propose changing, strncmp will *not* reduce the
number of characters compared.
strcmp("a long time ago...", "method") compares a single character, and stops.
strcmp("methodxxxxxxxxxxxx", "method") compares 7 characters, and stops.
strncmp it is not only as fast as strcmp, but it is much more secure.
The basic difference between these two are :
- strcmp compares both the strings till null-character of either string comes whereas strncmp compares at most num characters of both strings. But if num is equal to the length of either string than strncmp behaves similar to strcmp.
- Problem with strcmp function is that if both of the strings
passed in the argument is not terminated by null-character, then
comparison of characters continues till the system crashes. But with strncmp function we can limit the comparison with num parameter."