1

I recently came across the following when I was testing my code for various value of x.

I will try to illustrate only the issue.

#include <iostream>

int main()
{
     int x = 01234;

     std:: cout << x ;

     return 0;
}

Output:

when x = 1234 , 1234

 x = 01234 , 668

 x = 001234 , 668

 x = 240 , 240

 x = 0240 , 160

 x = 00240 , 160

For mostly any number starting with 0 I get a different value. eg: x = 0562 gives 370 and so on.

I tried using various online C++ compilers but all give same output. I tried to google the issue but couldn't find an appropriate answer.

2 Answers2

3

Looks like you've been hit with an octal literal! Any number literal beginning with just 0 is interpreted in base 8.

01234 = 1 × 8^3 + 2 × 8^2 + 3 × 8^1 + 4 × 8^0  
      = 1 × 512 + 2 × 64 + 3 × 8 + 4 × 1  
      = 512 + 128 + 24 + 4  
      = 668

0240 = 2 × 8^2 + 4 × 8^1 + 0 × 8^0
     = 2 × 64 + 4 × 8 + 0 × 1
     = 128 + 32
     = 160
2

The number 01234 is in octal (base 8) when you prepend a 0 you define the number as an octal. When you then print it in decimal you get it's decimal equivalent

twain249
  • 5,666
  • 1
  • 21
  • 26