Reputation: 2876
int main(){
long a = 1684 * 2097152;
return 0;
}
Above code gives this warning during compilation:
warning: integer overflow in expression of type 'int' results in '-763363328'
I know I can fix this by making one of them unsigned like 1684u
.
I assume 1684
and 2097152
each get promoted to an int
due to the promotion rules in C,
then the compiler complains the multiplication result is too big for a signed int. However my result type is a 64 bit long
which easily can fit the result even if its signed.
So does the promotion rule not care about the result type? and only cares about the intermediate type which is an int
here?
Upvotes: 1
Views: 60
Reputation: 8426
Your interpretation of integer promotion is correct.
long a = 1684L * 2097152;
return 0;
If you explicitly specify the type however, the error goes away because the first operator is now a long
Upvotes: 1
Reputation: 223739
The rules regarding promotion and conversion of integer types occur on a per-operator basis. So the result of the binary *
operator has a type, and the result of the =
operator has a type.
In the case of the *
operator, the integer promotions are first performed on both sides. Since both operands already have type int
there is no change. And since both operands have the same type, i.e. int
, no conversion is performed and the result has type int
.
For the =
operator, the right operand is converted to the type of the left operand, and the resulting expression has the type of the left operand.
Upvotes: 2