Alex Rivera | Logout

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

Asked 2011-06-15T23:17:42.667
9

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.

Edit
Report

2 Answers

19

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

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

answered 2011-06-15T23:19:52.253
1

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.

answered 2011-06-15T23:56:28.497

Your Answer