0

I am wondering, what is happening when an int is starting with a zero?

int main() {
    int myint = 01001;
    cout << myint;
    return 0;
}

Why is that outputting:

513

I have tried several compilers.

Martol1ni
  • 4,684
  • 2
  • 29
  • 39

1 Answers1

7

Then the integer is treated as an octal number. So,

01001

equals

1 * 8 ^ 0 + 0 * 8 ^ 1 + 0 * 8 ^ 2 + 1 * 8 ^ 3 = 1 + 0 + 0 + 512 = 513

No magic in there.

  • One of the more surprising corners of the language specification, one that's unfortunately shared by Python. – Mark Ransom Aug 28 '12 at 19:34
  • Yup, I just checked Python on Codepad.. – Martol1ni Aug 28 '12 at 19:34
  • 4
    @Martol1ni don't write the leading 0. –  Aug 28 '12 at 19:34
  • @Martol1ni, you could try `int(01001.)`. Floating point constants aren't affected by the leading zero. – Mark Ransom Aug 28 '12 at 19:38
  • 3
    @MarkRansom: You probably already know this, but for others reading: [Python 3 no longer offers octal literals with a leading zero](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#integers). They would be written with a `0o` prefix, eg. `0o1001` in Python 3. – Greg Hewgill Aug 28 '12 at 19:39
  • @GregHewgill, yes I knew that - and I think it's a big mistake that they now treat leading zeros as a syntax error rather than ignoring them. But as this is a question about C++ I'm sorry I brought it up. – Mark Ransom Aug 28 '12 at 19:44
  • You can use cout << oct << myint; That'll display it in octal, but your int still stores the decimal number 513. – derpface Aug 28 '12 at 20:13