Q : In the following declaration statement:
char c=’A’;
Variable c stores one byte of memory space while character constants ‘A’ stores one byte memory space. How one byte variables can stores two byte character constant? What is automatic type promotion in c?
Solution :
Character constant reserve two byte of memory space to represent
octal or hexadecimal character constant but char variable stores only its one
byte ASCII value.
In C language, char type is used to store a 1 byte integer.
When you assign 'A' to char c, you are not assigning the letter A itself into
memory. Rather, you are assigning the number (integer) representing the A
character. Each letter has a digit that represent it. . Remember that unlike
humans, computers cannot understand letters. That's why we need a way to
translate them into digits. To do this we use differnet coding styles like:
ASCII, UTF-8, etc If your machine use ASCII coding then the value assigned to
char c would be 65 (0x41 hex). As you may notice, 0x41 is one byte and can be
stored in your char variable.
Automatic type promotion
Some data types like char , short int take less number of
bytes than int, these data types
are automatically promoted to int or unsigned int when
an operation is performed on them. This is called integer promotion. For
example no arithmetic calculation happens on smaller types like char, short and enum. They are first
converted to int or unsigned int, and then
arithmetic is done on them. If an int can represent all
values of the original type, the value is converted to an int . Otherwise, it is
converted to an unsigned
int.
int main()
{
char a = 30, b = 40, c = 10;
char d = (a * b) / c;
printf ("%d ", d);
return 0;
}
At first look, the expression (a*b)/c seems to cause
arithmetic overflow because signed characters can have values only from -128 to
127 (in most of the C compilers), and the value of subexpression ‘(a*b)’ is
1200 which is greater than 128. But integer promotion happens here in
arithmetic done on char types and we get the appropriate result without any
overflow.
Consider the following program as another example.
Next Question