I am not able to understand why the following C program returns a value 34?
int main(void)
{
char c;
char c1='a', c2='b';
c= c1*c2;
printf("%d", c);
}
Any help is greatly appreciated!
I am not able to understand why the following C program returns a value 34?
int main(void)
{
char c;
char c1='a', c2='b';
c= c1*c2;
printf("%d", c);
}
Any help is greatly appreciated!
Ascii value of "a" is 97, of "b" is 98. Since the char
(which can be signed char
or unsigned char
depending on implementation) can hold maximum value of 127 for signed char
(or 255 for unsigned char
), you get:
97*98 modulo 128 = 34
well, in C notation:
(97*98) % 128 == 34
PS: replacing 128 with 256 gives 34 as well.
Basically char
is just a small integer.
Using ASCII encoding (the most commonly used encoding by far) the values for 'a'
and 'b'
are 97
and 98
(respectively).
When you do multiplication the char
values are promoted to int
values, so it's a simple 97 * 98
multiplication. The result of that is 9506
.
Now 9506
is to large to fit in a char
variable so it's truncated. The result value is easier to see if we use hexadecimal notation: Decimal 9506
is hexadecimal 0x2522
. The value is truncated (through modulo with 128
) to 0x22
which is 34
decimal.
It likely uses ASCII for encoding. In ASCII, 'a'
equals to 97
and 'b'
equals to 98
. Multiply them and you get 9506
. You are assigning it to a char
, which is 8 bits on most systems. 9506
is 37 * 256 + 34, hence why you get 34
after it's truncated. This truncation happens because char
is likely unsigned, an if an unsigned integer type can't represent the value, it's reduced modulo the maximum it can hold +1 (which is 256
, because an unsigned char can hold values up to 255
). This is explained here:
Unsigned integer arithmetic is always performed modulo 2n where n is the number of bits in that particular integer. E.g. for
unsigned int
, adding one toUINT_MAX
gives 0, and subtracting one from 0 givesUINT_MAX
.
As Character range is between -128 to 127 or 0 to 255. In this case integer value for c1 & c2 are 97 & 98 respectively. so c=c1*c2; will result into 97*98 = 9506, While saving value which exceed range it cycle back to the lower limit and continue. just to cross check 9506 % 256 will give you result 34.