3

With this code snippet:

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

Why is the result

a = 9

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
wonderingdev
  • 1,132
  • 15
  • 28

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
  • 104,019
  • 25
  • 176
  • 264
  • 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
  • 133,132
  • 16
  • 183
  • 261
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,482
  • 35
  • 52
zoska
  • 1,684
  • 11
  • 23