Reputation: 335
How does 'ab' was converted to 24930 when stored in char?
#include<stdio.h>
int main(){
char c = 'ab';
c = toupper(c);
printf("%c", c);
return 0;
}
GCC compiler warning : Overflow in conversion from 'int' to 'char' changes value from '24930' to '98'
Output : B
If possible please explain how char handled the multiple characters here.
Upvotes: 3
Views: 104
Reputation: 2322
A conforming char c
holds a single character... multiple characters require char *string
and you need to iterate through the string, eg something like:
#include <stdio.h>
#include <cype.h> // Needed for toupper()
int main()
{
char *mystring = "ab\0"; // Null terminate
char *mychar = mystring;
while ( *mychar != '\0' )
{
char c = toupper( *mychar );
printf( "%c", c );
mychar++;
}
return 0;
}
As an aside, toupper()
returns an int
, so there is an implicit type conversion there.
Upvotes: 0
Reputation: 311068
From the C Standard (6.4.4.4 Character constants)
10 An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer. The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined.
So this character constant 'ab' is stored as an object of the type int
. Then it is assigned to ab object of the type char
like in this declaration
char c = 'ab';
then the least significant byte of the object of the type int
is used to initialize the object c
. It seems in your case the character 'b'
was stored in this least significant byte and was assigned to the object c
.
Upvotes: 3
Reputation: 11249
Your characters are stored into 4 bytes on the right side. 24930 = 0x6162 equivalent to 0x61 'a' and 0x62 'b' = 'ab'
98 is your 'b', 0x62 in hexa, 98 in decimal, check with man ascii
. Because of the overflow, and the fact that your system works in little endian, your 2 chars are stored on 4 bytes like this:
0x62 0x61 0x00 0x00
Because only one char is supposed to be assigned to c (sizeof char is equal to 1 byte, with a max limit of 256 bits), it truncates and keep only the first byte, your 'b'.
You can test it easily with char c = 'abcd' it will print 'D'.
Upvotes: 0