0

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;
}
4
  • 4
    016 means octal number. Commented Aug 5, 2017 at 4:32
  • 1
    What was expected? Commented Aug 5, 2017 at 4:32
  • Were you expecting 16 but got 14? Commented Aug 5, 2017 at 4:35
  • You should use %o to print octal numbers — not %d. Octal numbers start with a 0 on input. To get a leading zero on output, you need %#o. See scanf() and printf(). (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 whether x contains an octal or decimal value; it really contains a binary number and the formatted I/O functions control the appearance.) Commented Aug 5, 2017 at 6:11

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for helping out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.