1

I have this code here where i multiply char type and int type variables and store them in different int variables

int m,n;
int num = 1000;
char c = 50;
m = num*c*c;
n = c*c*num;

printf("%d\n", m);
printf("%d\n", n);

and it outputs

2500000
2500000

I expected the output values to overflow, but it outputed the correct result.Why didn't it overflow?

ichigo14
  • 63
  • 5
  • the values are implicitly converted to int. `c * c` is internally executed with all ints as `(int)c * (int)c` – pmg Apr 08 '20 at 18:33
  • There is a quite lot written here about [Implicit type promotion rules](https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules). There a several similar questions to be [found](https://www.google.co.uk/search?q=c+stackoverflow+integer+promotion+site:stackoverflow.com) too. – Weather Vane Apr 08 '20 at 18:37

2 Answers2

2

How do you know it doesn't overload? You just assume subject to the output.

If your int is 2 bytes, it overflows. Otherwise, in the case of higher bytes, not.

However, we don't know what architecture you are working on.

For example, if the code runs by clang x86-64 compiler, it yields as follows.

    // byte 8 bits, int(dword) 32 bits
    mov     eax, dword ptr [rbp - 12]
    movsx   ecx, byte ptr [rbp - 13]
    imul    eax, ecx
    movsx   ecx, byte ptr [rbp - 13]
    imul    eax, ecx
    mov     dword ptr [rbp - 4], eax

As can be seen, the result is preserved in a field whose type is dword.

1

Your question contains two separate questions:

  • What about multiplying integer and char types?
  • What about the maximum value of integer types?

The first question is answered in the comments from @pmg and @Weather Vane.

The second question can be answered by your own compiler, you just verify the value of INT_MAX, this is the maximum value an integer might have according to your compiler.

Dominique
  • 16,450
  • 15
  • 56
  • 112
  • Yes, @EricPostpischil, you're right of course. Clearly I needed to have consumed more coffee before writing what I did. But the point is still that the maximum representable value for an `int` in most modern implementations is more than sufficient for the values the OP is asking about. – John Bollinger Apr 08 '20 at 22:58