What does this mean when a numerical constant in C / C ++ has a prefix with 0?

Okay ... So, I had a stupid idea and I tried to put the value 0123 in an int, just curious to see what happens, I assumed that when I print the value that I get 123, instead I got 83 ... Any ideas why? what happens inside the compiler / memory, what makes this value equal to 83?

I tried this in C ++ and C with the GCC compiler, and also tried using float, which gave the same results.

+8
c ++ c compiler-construction syntax numbers
source share
7 answers

In C / C ++, a numeric literal with the prefix "0" is octal (base 8).

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

+16
source share
+8
source share

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

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

+3
source share

Leading 0 indicates an octal number. Thus, it becomes equal to 1 * 8 ^ 2 + 2 * 8 ^ 1 + 3 * 8 ^ 0 = 83

+3
source share

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

+2
source share

0123 is located in octal .

+1
source share

According to the C ++ standard in [lex.icon], whole literals can be divided into 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 non-zero digit, and 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 represented in the corresponding base should cause a compilation error (for example, 09, which causes error C2041: illegal digit '9' for base '8' and in another prog.cpp:6:15: error: invalid digit "9" in octal constant compiler prog.cpp:6:15: error: invalid digit "9" in octal constant ), because if the integer literal is not representable, the program becomes poorly formed.

+1
source share

All Articles