Reputation: 27
#include<stdio.h>
void main()
{
printf("%d",'AA');
}
I was expecting an error there but the program ran and output was 16705. Can anyone please explain this?
Upvotes: 0
Views: 135
Reputation: 141523
Can anyone please explain this?
The 'AA'
is a multi-character character constant. It has the type int
. It's value is implementation-defined.
"Implementation" here is the compiler and your compiler has rules to which int
value 'AA'
is mapped to. The mapping seems to be easy. Because I don't know your compiler, I am guessing it. Consult your compiler documentation to be sure.
'AA'
maps to a value 'A' << 8 | 'A'
. Bit shifted 'A'
by a byte with another 'A'
. You system most probably uses ASCII to represent characters. The 'A'
maps in ASCII to a value 65
in decimal (0x41
in hex). Calculating 0x41 << 8 | 0x41
gives the value of 16705
in decimal. Because this is an int
value, you can use %d
to print the result. So your code is equivalent to printf("%d\n", 16705)
.
Upvotes: 4
Reputation: 1
this code run because the char data type is a number and you have request ho print the real number of 'AA'
https://en.wikipedia.org/wiki/C_data_types
Upvotes: -1
Reputation: 179991
'AA'
is an exotic beast. It's a character literal, but ASCII does not have a single character 'AA'
. This explains why you get a non-ASCII value instead.
Upvotes: 0