Can anyone explain why the output is not as expected ? I was expecting 16 but got 14.
#include<stdio.h>
int main()
{
int x=016;
printf("%d",x);
return 0;
}
Numeric literals beginning with 0 are interpreted as octal numbers.
6.4.4.1 Integer constants
3 ... An octal constant consists of the prefix 0 optionally followed by a sequence of the digits 0 through 7 only. ...
E.g 016(8 base) ==> 0 x 8^2 + 1 x 8^1 + 6 x 8^0 ==> 0 + 8 + 6 ==> 14(10 base)
%d of printf outputs the value of int in 10 bases, so the result is 14.
If you output int as an octal number using %o, 16 is obtained.
E.g
int x = 016;
printf("%#o", x);//016
If you want results with three digits include leading 0 using %d,
printf("%03d", 16);//016
Please refer to the reference of printf for details of format string.
016means octal number.%oto print octal numbers — not%d. Octal numbers start with a0on input. To get a leading zero on output, you need%#o. Seescanf()andprintf(). (And yes, this is a very tongue-in-cheek comment — it is accurate up to a point, but it is also very misleading. There's no way to decide whetherxcontains an octal or decimal value; it really contains a binary number and the formatted I/O functions control the appearance.)