I have just been experimenting with the cout object and I have 2 questions.
1. Is there any benefit of of using this
cout << 'm' << endl; instead of this
cout << "m" << endl; or does the compiler treat these lines
differently at all.
2. cout << 'A' << endl; // outputs A
cout << 'AA' << endl; // outputs 16705
cout << 'AB' <<endl; // outputs 16706
can anyone explain this . I know that chars can only hold 1 byte
but i would be interested to know how the above results are
arrived at . Can anyone shed any light?
The only time that you can use the single quote marks ( ' ) is when you are initializing a char variable. When using the iostreams (cout), you must use the double quotes ( " ) for it to display. You will get an error message otherwise.
Although I'm not totally sure, you're probably getting a hex or oct value for the characters that you are typing in.
Basically, there is no benefit because it is not legal. You must use double quotes to output a string in the cout stream. Hope this helps!
As I understand it....
'm' is a char which can fit into a single byte......."m" is represented as a pointer to a NULL terminated string....they will output the same...but there is a slight difference as the "m" has a NULL after it in memory........
'AA' is represented as 2 bytes of an int (which holds 4 on most common platforms).......so 'A' has a value of 65 on the ASCII table....which is 41 in Hexadecimal ......so 'AA' is shown in memory as 00h - 00h - 41h - 41h (00004141 Hex) and that number converted back to decimal is 16705....which is your output
Basically, use single quotes for char, which is a single character (the exception being control characters like /n, which are treated as single characters although to the human eye they're two).
Use double quotes for anything more than one character long.
Thanks guys ,
that is exactly the what i wanted to know!