Reputation: 79
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;
}
Upvotes: 0
Views: 127
Reputation: 40145
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.
Upvotes: 4