if (memcmp (version, "\x0\x0\x0", 3) == 0 )
I am working on a piece of code that has a statement as below:
if (memcmp (version, "\x0\x0\x0", 3) == 0 )
What is the data that is being compared with version? Is it the same a开发者_开发技巧s comparing with "000"?
No, it is not the same as "000"
. It is comparing three null (0) bytes. Each byte is an actual value of zero in binary. This is different than "000"
, which is a string containing ASCII values for the printable character 0
, which is 48 (or 30 in hex.)
So "000"
would be the same as "\x30\x30\x30"
.
"\x0\x0\x0"
equals { 0x00, 0x00, 0x00, 0x00 }
. The fourth zero is the string null terminator.
So to answer your question - no, it's not the same as comparing with "000"
.
'\x0'
is hexadecimal zero, whereas '0'
is the ASCII code of the character 0
(hexadecimal 30).
No - it's not same as comparing against "000"
. It's comparing against three null characters. An equivalent, and probably more expected, string would be "\0\0\0"
. Or just a 3-character array filled with 0
, for this case, where the code is only checking 3 characters anyway.
\x0
stands for a char
with value 0. 0
is different, it's the ASCII character with code 0x30.
It would be interesting to know the definition of the variable version
. Is it a void *
or a char *
or some other strange casting. This is probably throwing up a warning during compilation.
It would also be prudent to look at how version
is initialised just to make sure there are no errors. It is certainly a strange way to check for (the lack of a) version number in a program.
No. \x0 is the literal for NULL. "000" is a number and have a different representation in memory.
精彩评论