One of my friends asked me the output of this code and I just got shocked after running this code. The output of this code is 70. Please explain why?
#include <stdio.h>
int main()
{
int var = 0101;
var = var+5;
printf("%d",var);
return 0;
}
The C Standard dictates that a numeric constant beginning with 0 is an octal constant (i.e. base-8) in § 6.4.4.1 (Integer constants).
The value 101 in base 8 is 65 in base 10, so adding 5 to it (obviously) produces 70 in base 10.
Try changing your format specifier in printf to "%o" to observe the octal representation of var.
It is because of Integer Literals. A number with leading 0 denoted that the number is an octal number. You can also use 0b for denoting binary number, for hexadecimal number it is 0x or 0X. You don't need to write any thing for decimal. See the code bellow.
#include<stdio.h>
int main()
{
int binary = 0b10;
int octal=010;
int decimal = 10;
int hexa = 0x10;
printf("%d %d %d %d\n", octal, decimal, hexa, binary);
}
For more information visit tutorialspoint.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With