2

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!

Simon
  • 1,616
  • 2
  • 17
  • 39
user3319015
  • 99
  • 1
  • 5

4 Answers4

5

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.

Tomas
  • 57,621
  • 49
  • 238
  • 373
  • Whether `char` signed or unsigned is implementation defined. So it can hold even 255. – Alex Lop. Nov 14 '19 at 08:14
  • The conversion to a signed char is implementation defined and I know of no implementation which would make it modulo, the wrap around is more complex and will allow negative result. – AProgrammer Nov 14 '19 at 09:04
  • @AProgrammer you are right, in this case it would be little more complicated than just regular modulo. Thanks for comment! – Tomas Nov 14 '19 at 09:58
4

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

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 to UINT_MAX gives ​0​, and subtracting one from ​0​ gives UINT_MAX.

Blaze
  • 16,736
  • 2
  • 25
  • 44
0

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.

Nick
  • 1
  • 3