Convert unsigned

if I have :

unsigned int i = 6;
in a = -20;

and I perform i+a....

a will be convert to positive value....what will be the value?
The value remains unsigned and negative numbers are not represented.

6.3.1.3 Signed and unsigned integers
1 When a value with integer type is converted to another integer type other than _Bool, if
the value can be represented by the new type, it is unchanged.
2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or
subtracting one more than the maximum value that can be represented in the new type
until the value is in the range of the new type.49)
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.

From the C99 Standard
I found this question :

void foo(void)
{
unsigned int a=6;
int b=-20;
(a+b >6) ? puts(">6") : puts("<=6");
}


answer :



4. The question tests whether you understand the integer promotions rules in C - an area that I find is very poorly understood by many developers. Anyway, the answer is that this outputs ">6". The reason for this is that expressions involving signed and unsigned types have all operands promoted to unsigned types. Thus -20 becomes a very large positive integer and the expression evaluates to greater than 6.This is a very important point in embedded systems where unsigned data types should be used frequently. If you get this one wrong, you are perilously close to not getting the job.


but what will be "large positive integer " ???
ok sorry I think I got it....


the value is converted by repeatedly adding or
subtracting one more than the maximum value that can be represented in the new type
until the value is in the range of the new type.49)
In principle, yes.

In practice, the machine operations are the same and the value is simply interpreted as an unsigned value. It's no more expensive to do signed or unsigned addition/subtraction.
Topic archived. No new replies allowed.