开发者

What does it mean when a numeric constant in C/C++ is prefixed with a 0?

Ok... So I had a silly idea and tried putting the value 0123 into an int, just curious to see what would happen, I assumed that when I printed the value I'd get 123, but instead I got 83... Any ideas why? what happens inside the compiler/memory that makes this value become 83?

I tried this in C++ and C with GCC compiler and also tried with a float which yielded开发者_如何学运维 the same results.


In C/C++ a numeric literal prefixed with a '0' is octal (base 8).

See http://www.cplusplus.com/doc/tutorial/constants/


Congratulations! You've discovered octal.


This is because any number starting with 0 like this is considered to be in octal (base 8) not decimal.

Same thing if you start with 0x you will get hexadecimal


The leading 0 indicates an "octal" number. So it becomes 1*8^2 + 2*8^1 + 3*8^0 = 83


0123 is an octal constant (base 8). 83 is the decimal equivalent.


0123 is in octal.


According to the C++ standard in [lex.icon] integer literals can be split in 3 types: decimal literals, octal literals and hexadecimal literals, each of which can have a suffix for signess and length type

Decimal literals must start with a nonzero digit, while octal literals start with 0 and hexadecimal literals have 0x and 0X, after the prefix (for octal-literals and hexadecimal-literals) any digit that is not representable in the corresponding base should trigger a compilation error (such as 09 that causes error C2041: illegal digit '9' for base '8' and in other compiler prog.cpp:6:15: error: invalid digit "9" in octal constant), since if the integer literal is not representable the program becomes ill-formed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜