Printf with "% d" numbers starting at 0 (ex "0102"), giving an unexpected response (eg "66")

I used below code in my printf statement.

void main()
{
    int n=0102;
    printf("%d", n);
}

      

In this answer 66. I also changed the value of the variable n to 012. It gives the answer 10. Please help me on how this conversion is done.

0


source to share


3 answers


This is because when the first digit of a number (an integer constant) is 0

(and the second must not be x

or x

), the compiler interprets it as an octal number. Printing it with %d

will give you the decimal value.
To print an octal value you must use %o

specifier

   printf("%o", n);  

      

6.4.4.1 Integer constants:

  • An integer constant starts with a digit but has no period or exponent. It can have a prefix that indicates its base and a suffix that indicates its type.

  • A decimal constant starts with a nonzero digit and consists of a sequence of decimal digits. An octal constant is prefixed with 0, optionally followed by a sequence of digits from 0 to 7 . A hexadecimal constant is prefixed with 0x or 0X in decimal digits and the letters a (or A) through f (or F) with values ​​10-15, respectively.


Integer constants:



1. Decimal constants : must not start with 0

.

 12  125  3546  

      

2. Octal constants : must start with 0

.

 012 0125 03546  

      

3. Hexadecimal constants : always starts with 0x

or 0x

.

 0xf 0xff 0X5fff   

      

+6


source


You tell printf to print the value in decimal format (% d). Use% o to print in octal format.



+4


source


any numeric literal beginning with 0

, followed by only numbers, is taken as an octal number. Hence,

0102 = (1 * 8^2) + (0  * 8^1) + (2 * 8^0)  = 64 + 0 + 2 = 66
012 = (1 * 8^1) + (2 * 8^0) = 8 + 2 = 10

      

0


source







All Articles