When will this condition evaluate to False?
Under what circumstances will the "False" par开发者_如何学Got 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).
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
.
unsigned int x = 20;
unsigned int y = -30;
Sadly, the compiler I'm using doesn't even give a compile-time warning about this.
Only when X and Y are unsigned.
Even if x
and y
are int
, you could always have the following...
#define if(p) if(!(p))
...in the body of your method ;)
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; }
精彩评论