tags:

views:

204

answers:

5

Under what circumstances will the "False" part of the following code be executed?

x = 20;
y = -30;
if (x > y) {
    // True part
}
else {
    // False part
}

NB: Language is C, compiler is gcc (although some other compilers may also do the same thing).

+6  A: 

If y is of unsigned integer type it will be initialized to some very large value (because of how negative integer values are represented) and the comparison expression will evaluate to false.

sharptooth
It's not really "because of how negative integer values are represented", it's because that's how conversion of out-of-range values to unsigned types is defined by the language (it's independent of the representation).
caf
+2  A: 
unsigned int x = 20;
unsigned int y = -30;

Sadly, the compiler I'm using doesn't even give a compile-time warning about this.

Chris Schmich
@a_m0d: Prove it.
Greg Hewgill
@Greg: Oops, my bad :( - I keep getting confused between `signed` and `unsigned`
a_m0d
+2  A: 

Only when X and Y are unsigned.

dicaprio
Actually, only one of them needs to be unsigned - the case I saw it in had `x` as unsigned, but `y` as signed, and the problem still existed.
a_m0d
+1  A: 

Sorry, this is C++. It's just fun, anyway, so I won't delete unless someone complains.

Needed a little help from static_cast, but static_cast is safe, right?

enum E { ea = 20, eb = -30 } x;
enum F { fa = 20, fb = -30 } y;

bool operator>( E const &l, F const &r )
    { return static_cast<int>(l) < static_cast<int>(r); }

x = static_cast<E>( 20 );
y = static_cast<F>( -30 );

or a little looser,

enum E { x = 20 };
enum F { y = -30 };

bool operator>( E, F )
    { return false; }
Potatoswatter
very creative! :-)
Nathan Fellman
+2  A: 

Even if x and y are int, you could always have the following...

#define if(p) if(!(p))

...in the body of your method ;)

Chris Schmich