Search code examples
chexscanfformat-specifiersoctal

Scanning an octal and hexadecimal number in %d format specifier with scanf


  1. I was experimenting with the printing octal and hexadecimal number in C. The following is printing as expected

    int a = 012;
    printf("%d",a); //printing as 10. The decimal representation of octal 12.
    

    However, when I am scanning 012 using %d 0 is ignored and it is printing 12. What is the reason?

    int b;
    scanf("%d",&b);
    printf("%d", b); //printing 12.
    
  2. When I am scanning 0x12 using %d the output is giving as 0 as follows

    int b;
    scanf("%d",&b);
    printf("%d", b); //printing 0
    

What is the reason for this? Why they are not giving any runtime errors?

Thanks in advance!!!


Solution

  • Explanation

    int a = 012;    // a is assigned decimal value 10 (012 is octal = 10 in decimal)
    printf("%d",a); // printing a in decimal as 10
    

    In the case of first code snippet, you are assigning a=10 (which is represented as octal 012) and printing it in decimal format.

    int b;
    scanf("%d",&b);  // read an integer in decimal format
    printf("%d", b); //printing 12 because the input was 12 after ignoring the 0.
    

    When you're using scanf with %d, it expects an integer in decimal format. So it ignores the first 0 and assigns b = 12. And when you print it, you see 12.

    int b;
    scanf("%d",&b);
    printf("%d", b); //printing 0
    

    In the above case, you are asking scanf to read an integer in decimal format and when you enter 0x12, it stops scanning at character x after reading 0 since x cannot be a part of a valid integer.

    Solution

    So here is the way to go.

    "%d" - to input decimal value
    "%o" - to input integer value in an octal format
    "%x" - to input integer value in hexadecimal format
    "%i" - to input integer in any format (decimal/octal/hexadecimal)