Why is memcmp(a, b, 4) only sometimes optimized to a uint32 comparison?

后端 未结 4 924
暗喜
暗喜 2021-02-03 16:36

Given this code:

#include 

int equal4(const char* a, const char* b)
{
    return memcmp(a, b, 4) == 0;
}

int less4(const char* a, const char* b         


        
4条回答
  •  执念已碎
    2021-02-03 17:13

    Endianness is the problem here. Consider this input:

    a = 01 00 00 03
    b = 02 00 00 02
    

    If you compare these two arrays by treating them as 32-bit integers, then you'll find that a is larger (because 0x03000001 > 0x02000002). On a big-endian machine, this test would probably work as expected.

提交回复
热议问题