问题
I've done a little bit of reading on endianness and its role in C, but nothing has really managed to clarify this for me. I'm just starting out with C and I saw this example:
#include <stdio.h>
int main(void) {
int x = 017;
int y = 12;
int diff = x - y;
printf("diff is %d\n", diff);
return 0;
}
and it asks what will print. I compiled and ran the example and got that diff is 3, so x is 15. I sort of see why this is, but would really appreciate if somebody really clarified it for me.
[1] I've looked for similar questions but haven't found any that explained the issue thoroughly. If someone could link me to one that would be good also.
回答1:
Prefixing a number with 0
will tell the compiler to mark it as a number in octal (base 8)
Just like prefixing it with 0x
will tell it to use hex (base 16)
For example:
int x = 05; // 5 in octal
int y = 5; // 5 in decimal
int z = 0x5; // 5 in hex
回答2:
017
is an octal constant if we look at the C99 draft standard section 6.4.4.1
Integer constants the grammar for octal constant is as follows:
octal-constant:
0
octal-constant octal-digit
octal-digit: one of
0 1 2 3 4 5 6 7
So any integer constant that starts 0
is in octal(base 8), this includes 0
itself.
来源:https://stackoverflow.com/questions/19485548/why-is-017-15-in-c