Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding signed and unsigned int

Tags:

c

int main()
{
  unsigned int a=6;
  int b=-20;

  (a+b)>6?puts(">6"):puts("<=6");
}

It is clear to me how the ternary operator work in this code. I am not able to understand the addition of the signed and unsigned integer here.

Tried Running the code ,output is ">6", why?

like image 431
Nargis Avatar asked Oct 18 '13 10:10

Nargis


2 Answers

I think the OP is not confused about the ternary operator its a different problem.

From the C99 standard, section 6.3.1.8 ("Usual arithmetic conversions"):

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.

unsigned int and int has the same rank, so it's equivalent to:

(a + (unsigned int)b > 6)

To fix it, you need to explicitly cast in the other direction, i.e.:

((int)a + b > 6)

So this is the reason the output will be >6 and NOT <=6

like image 184
Sadique Avatar answered Oct 31 '22 00:10

Sadique


The other two answer accurately describe Ternary operator, but I think this is more relevant to the question

The output is >6 because (a + b) casts b to unsigned int as well.

EDIT:

See Acme's suggestion for fixing this problem. Essentially casting a as an int will fix this

like image 27
sukhvir Avatar answered Oct 31 '22 01:10

sukhvir