3

With this code snippet:

int a = 011;
printf("a = %d", a);

Why is the result

a = 9

Yu Hao
  • 115,525
  • 42
  • 225
  • 281
Ivan Gandacov
  • 978
  • 13
  • 26

3 Answers3

12

011 is an octal value and its decimal equivalent is 9. Preceding integer literal with 0 indicates octal value.
Use %o specifier in printf to print the value in octal.

haccks
  • 100,941
  • 24
  • 163
  • 252
  • 1
    I got an integer overflow when I wanted to count the amount of dupes for this question. But on the C tag there are just almost no users, who care about that. (It's like yesterday: http://stackoverflow.com/a/19652607/3933332) – Rizier123 Jun 03 '15 at 09:29
  • 1
    @Rizier123; I would say I am a lazy guy, yes a lazy guy. – haccks Jun 03 '15 at 09:42
10

A leading 0, in an int literal or int constant, represents the octal value. It is called an octal constant.

Related: C11 standard, chapter 6.4.4.1, Integer constants, Paragraph 3,

An octal constant consists of the prefix 0 optionally followed by a sequence of the digits 0 through 7 only.

Sourav Ghosh
  • 130,437
  • 16
  • 177
  • 247
8

With 0 at the beginning of of a numeric literal, you specify the octal system. And 11 in the octal system is 1*8 + 1 = 9.

Samveen
  • 3,472
  • 35
  • 51
zoska
  • 1,593
  • 10
  • 23