Lets assume the int
is the 16-bit type to prevent implicit conversion from short
.
long test_1(short x, short y)
{
return x + y;
}
- What are C rules about promoting numbers in this example?
- How to protect from modulo arithmetic?
Lets assume the int
is the 16-bit type to prevent implicit conversion from short
.
long test_1(short x, short y)
{
return x + y;
}
The rules are relatively straightforward. The binary + will result in the data type of the "largest" int. If you have two operands of the same type, the result will be the same type.
The expression
return x+y
is evaluated in two steps. In the first, the result of x+y is computed. This is a short (as in your first declaration). then it is cast to the type of the function.
If you want to avoid the overflow, you need to cast the operands of plus to the desired type:
return ((long)x) + y
I have oveparenthesized for clarity.