+ 2

Why 'aa' == 24929 ?

cout << 'a'; //output "a" cout << 'aa'; //output "24929" Who can explain why? Where in the C++ standard It's described? I don't understand...

22nd Feb 2017, 3:16 PM
SUPER_S
SUPER_S - avatar
4 Respostas
+ 3
@SUPER_S Sorry for late. This is the reason: The int corresponding to a single 'a' is 97. Its binary 8-bit rappresentation is 01100001 . When printing 'aa' you are concatenating twice the binary rappresentation. So it becomes a 16-bit 0110000101100001. And the corresponding decimal number to that binary is 24929.
22nd Feb 2017, 4:21 PM
Marco Bimbati
Marco Bimbati - avatar
+ 3
@Marco Bimbati Thank you. It's a good explanation!
22nd Feb 2017, 4:25 PM
SUPER_S
SUPER_S - avatar
+ 2
@Marco Bimbati I know about the cast to int. And I know how to make this code to display the "aa". But I don't understand how the compiler gets from 'aa' number 24929 (just single quotes)
22nd Feb 2017, 3:49 PM
SUPER_S
SUPER_S - avatar
0
When using single quotes, the value inside them is implicitly cast to integer, except when you put a single character inside them. That's because single quotes are used to identify a char type variable. If you want to output strings, use double quotes. cout << "aa" //output "aa"
22nd Feb 2017, 3:41 PM
Marco Bimbati
Marco Bimbati - avatar