0

I have the following piece of code:

int ret() {
    int x = 010;
    int y = 4;
    int z = x | y;
    return z;
}

When x = 010, this function returns 12. However, on changing x to 10, 14 is returned. Why is this so?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
dntk
  • 41
  • 5
  • 1
    Binary integer literals was introduced with C++14 and uses the prefix `0b`. As in `0b10` for the integer value 2. – Some programmer dude Aug 02 '17 at 09:30
  • 2
    It's a pity `0o` wasn't adopted for octal literals in C++14 with an eye to deprecating the leading `0` without the `o` in a future standard. – Bathsheba Aug 02 '17 at 09:31
  • It's a pity octal literals aren't deprecated outright. I could perhaps live with `10_octal`. – MSalters Aug 02 '17 at 09:42
  • Another possible dupe target: https://stackoverflow.com/q/26568200/1896169 . There are a lot of these questions on stackoverflow – Justin Aug 02 '17 at 19:59

1 Answers1

5

The OR operator is a red-herring: the issue is elsewhere.

010 is an octal literal due to the leading 0. In decimal, this is 8.

So x has the value 8 in decimal. And 8 | 4 is 12.

10 is a decimal literal. And 10 | 4 is 14.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483