Reputation: 1
I would like an explanation on the following code:
#include <stdio.h>
int main()
{
int x = 042;
printf("%d",x);
}
Upvotes: 0
Views: 157
Reputation: 61
adding prefix 0 to any number makes it an octal number. if suppose x equals 096 then the compiler will show an error because 96 is not a valid octal number.
int x=042;
printf("%d", x); /* output : 34
x is in octal representation but %d is used to print for decimal number,
so 042 change to decimal */
printf("%o", x); /* output : 42
%o is used to print in octal representation */
Here, following format specifiers are used:
%d - to print value in integer format
%o - to print value in octal format
%x - to print value in hexadecimal format (letters will print in lowercase)
%X - to print value in hexadecimal format (letters will print in uppercase)
Upvotes: 1
Reputation: 2322
In the C language, a number prefixed with a zero is considered to be Octal.
ISO/IEC 9899:2018 para 6.4.4.1 Integer constants applies
So, 042 is Octal = 34 decimal.
Upvotes: 0
Reputation: 169298
42 in base 8 (octal) is 34 in base 10 (decimal).
Number literals prefixed with zeroes are interpreted as octal in C.
Change 042
to just 42
.
Upvotes: 3