8

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.

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
CurtisJC
  • 680
  • 3
  • 9
  • 23

7 Answers7

18

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

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

Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
8

Congratulations! You've discovered octal.

Peter K.
  • 8,028
  • 4
  • 48
  • 73
  • 1
    Amusement is better than bemusement. :-) – Peter K. Jun 15 '11 at 23:28
  • `To write numbers in octal, precede the value with a 0. ... To write numbers in octal, precede the value with a 0x or 0X. ` doh! – mrk Jun 15 '11 at 23:28
  • [D'oh!](http://www.cs.umd.edu/class/spring2003/cmsc311/Notes/BitOp/hexoctal.html) is right! Changed it for a better one... Thanks! – Peter K. Jun 15 '11 at 23:31
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

Locksfree
  • 2,682
  • 23
  • 19
3

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

Bill Forster
  • 6,137
  • 3
  • 27
  • 27
2

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

ribram
  • 2,392
  • 1
  • 18
  • 20
1

0123 is in octal.

Bertrand Marron
  • 21,501
  • 8
  • 58
  • 94
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.

lccarrasco
  • 2,031
  • 1
  • 17
  • 20