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

落爺英雄遲暮 提交于 2019-12-17 02:24:34

问题


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.


回答1:


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

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




回答2:


Congratulations! You've discovered octal.




回答3:


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




回答4:


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




回答5:


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




回答6:


0123 is in octal.




回答7:


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.



来源:https://stackoverflow.com/questions/6365565/what-does-it-mean-when-a-numeric-constant-in-c-c-is-prefixed-with-a-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!