Q : In the following declaration statement:
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?
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 , take less number of bytes than , these data types are automatically promoted to or when an operation is performed on them. This is called integer promotion. For example no arithmetic calculation happens on smaller types like , and . They are first converted to or , and then arithmetic is done on them. If an can represent all values of the original type, the value is converted to an . Otherwise, it is converted to an
char a = 30, b = 40, c = 10;
char d = (a * b) / c;
printf ("%d ", d);
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.