1
#include<stdio.h>

int main(){
    unsigned int a = 6;    
    int b = -20;
    ( a+b > 6 ) ? puts( "a") : puts( "b");// if a+b > 6 then a else b
}

I presumed that the output should be "b" but it wasn't.

output: a

rose
  • 162
  • 1
  • 1
  • 13
Rajesh
  • 19
  • 1
  • there are already a lot of duplicates about mixed signed-unsigned arithmetics and comparison here but I can't find right now – phuclv Sep 15 '15 at 12:18
  • 1
    [Duplicate](http://stackoverflow.com/questions/17312545/type-conversion-unsigned-to-signed-int-char). Also, I believe that the 2nd and 3rd operands of `?:` must be an arithmetic or pointer type. – Lundin Sep 15 '15 at 12:34
  • 1
    @Lundin: sure – but `puts` indeed [returns a value](http://en.cppreference.com/w/c/io/puts). – Jongware Sep 15 '15 at 12:59

2 Answers2

4

C99 standard, section 6.3.1.8

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.

So here b(value= -20) is converted to unsigned type (a large value), it will be equivalent to -

    ( a+(unsigned int)b > 6 )    

Therefore , output is a not b

ameyCU
  • 16,489
  • 2
  • 26
  • 41
1

The type of the expression a + b is unsigned int, which is the result of arithmetic conversions that are applied whenever the arithmetic operators are used on operands of different types. Each operand is first converted to this common type, and the result of converting -20 to an unsigned int is a very large value.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084