lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

Em seg., 16 de nov. de 2020 às 12:52, Julien Cugnière <> escreveu:
Le lun. 16 nov. 2020 à 16:36, Ranier Vilela <> a écrit :
> Em seg., 16 de nov. de 2020 às 11:18, Andrew Gierth <> escreveu:
>> strcmp doesn't call strlen (in reasonable implementations) and strncmp
>> isn't necessarily any faster.
> False.
> 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
comes first.

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.

"Prerequisites : strncmp, strcmp

The basic difference between these two are :

  1. 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.
  2. 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."

see at:

Ranier Vilela