if we have
int a = 1;
unsigned int b = -1;
what is the type of expression
a + b;
can i use int to store the result?
In case of your code, the "usual arithmetic conversions" rule will apply for the operands of +
operator, so, in case of
a + b;
as per the integer promotions rule, a
will be promoted to unsigned int
before the addition. The result will also be of type unsigned int
.
To quote C11
standard, chapter ยง6.3.1.8
..[..]... Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
The type of expression
a + b;
will be unsigned int
According to the C Standard )6.3.1.8 Usual arithmetic conversions)
2...Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type
As for the assignment of an object of unsigned type to an object of signed type with the same rank as in your example then ( C Standard, 6.3.1.3 Signed and unsigned integers) id the object of signed integer type can not represent the value of the object of unsigned integer type then
3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised
If the value can be represented by the signed object then it is stored unchanged in the signed object.
There's a set of rules called the usual arithmetic conversions that specify the conversions applied when arithmetic operators are used. (If you search that term on here you will find the full list easily)
In this case, the
int
is promoted tounsigned int
, retaining the value1
, so the result of the addition is well-defined to be(unsigned int)0
.Since this value is not greater than
INT_MAX
, you can store it in anint
.