Is this the only return value for strcmp() in C?

前端 未结 4 810
小蘑菇
小蘑菇 2021-01-06 17:47

I\'m learning C, and am currently studying String Handling. From where I\'m studying, strcmp() is defined as-

This is a function which c

4条回答
  •  误落风尘
    2021-01-06 18:28

    The C language specification is a document written in English.

    The member of the standardization committee carefully choose their words to permit implementors to make their own implementation choices.

    On some hardware (or implementation), returning any integers (respecting the constraints of the specification) could be faster (or simpler, or smaller code) than returning only -1, 0, 1 (like the function proposed in dvm's answer). FWIW, musl-libc's strcmp.c is shorter, and can return integers outside of -1, 0, 1; but it is conforming to the standard.

    BTW, with GCC & GNU libc (e.g. on most Linux systems) the strcmp function may be handled -notably when optimizing- as a compiler builtin - __builtin_strcmp... It can then be sometimes replaced by some very efficient code.

    Try compiling the following function (in a file abc.c)

    #include 
    int isabc(const char*s) { return strcmp(s, "abc"); }
    

    with optimizations enabled and look at the assembly code. On my Debian/Sid/x86-64 with GCC 4.9.1, compiling with gcc -fverbose-asm -S -O2 abc.c I see no function calls at all in the produced abc.s (but that isabc may return other numbers than -1, 0, 1).

    You should care about portable code, hence you should not expect a particular value (as long as your vendor's strcmp obeys its imprecise and fuzzy specification)

    Read also about undefined behavior, it is a related idea: the language specification is voluntarily imprecise to permit various implementors to do different implementation choices

提交回复
热议问题