5

Inspiring from a obfuscated piece of code, I have a small question regarding to assign value to an integer:

#include <iostream>
#include <cstdio>

int main() {
    int i = 0101;
    std::cout << i << "\n";
}

And the output was 65, and I have no idea where 65 came from? Any idea?

Lundin
  • 195,001
  • 40
  • 254
  • 396
roxrook
  • 13,511
  • 40
  • 107
  • 156
  • The linked duplicate is closed and generally of low quality. This question and answer however, are plain and straight-forward. I'm re-opening this with the intention to use as canonical dupe for octal literal FAQs. – Lundin Jan 11 '19 at 07:30

2 Answers2

12

It specifies an octal (base-8) number: 0101 == 1 * (8 * 8) + 1 == 65.

user541686
  • 205,094
  • 128
  • 528
  • 886
  • @:Lambert: Thanks a lot ;)! It was really interesting. – roxrook Jan 18 '11 at 06:05
  • @Chan: You're welcome. :) I actually learned it myself a few hours ago, when learning about the grammar of the D language! – user541686 Jan 18 '11 at 06:06
  • @Chan: The full expansion of 0101, if the extra detail helps you understand: 101 in base 8 is (each digit from left to right) `1 * (8 ** 2) + 0 * (8 ** 1) + 1 * (8 ** 0)`; this reduces to the expression in the answer. – Fred Nurk Jan 18 '11 at 06:37
0

Lambert already explained that. So let me tell you what else you can do.

You can write hexadecimal integer:

int main() {
    int i = 0x101; //0x specifies this (i.e 101) is hexadecimal integer
    std::cout << i << "\n"; //prints 257 (1 * 16 * 16 + 1)
}

Output:

257
Nawaz
  • 353,942
  • 115
  • 666
  • 851