简体   繁体   中英

When will this condition evaluate to False?

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).

如果y是无符号整数类型,它将被初始化为一个非常大的值(由于如何表示负整数值),并且比较表达式的值将为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.

仅当X和Y为无符号时。

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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM