0
Why is it showing L if I’m assigning it as %c and gives A if assigning %s?
8 Réponses
+ 3
As Julien Quentin said, you passed a memory address of a string, while printf function expected a char, as you had informed it, by specifying the "%c" format specifier. Down casting from memory address (64 bit) into char (8 bit) triggered the problem.
That character wasn't even the letter 'L', it was a character by ASCII code of 192 (it does look a bit like a letter 'L' though). To understand this try:
int x = (int)(char)ch1;
printf("%d\n", x);
It will output a negative value (in Code Playground it is -64), which is invalid for a char type whose value range lies between 0 to 255, it's out of range. To cope with that negative value, <x> will be incremented by 256, until its value lies within valid range (0-255). In this case, <x> (value is -64) is incremented by 256, becomes 192, thus the character of ASCII code 192 be printed.
As a side note, if <x> value was above 255, <x> value will be decremented by 256 until it lies within valid range (0-255).
Hth, cmiiw
+ 3
You are welcome Hemabh Aditya, glad if it helps. For future reference, please choose wisely a proper format specifier, depending on the variable type, for the printf function, though I understand you probably were doing that experiment for some curiosity of the code, nothing's wrong with that : )
Reference:
[printf function]
http://www.cplusplus.com/reference/cstdio/printf/
[Data type ranges]
https://msdn.microsoft.com/en-us/library/s3f49ktz.aspx
+ 2
thanks both of you. your information helped me a lot.
0
in case of %c why it is taking 8bits?
0
i’m not clear about what you want to say. please explain properly.