Skip to main content
GameDev.net gamedev.net
🔒 Locked

Magical if-statement

Started by ysg Mar 12, 2013 at 6:15 PM 7 replies 4.2k views
Original Post
ysg
ysg


if (foo == foo || bar == bar) {
...
}
else {
...
}

This is an old one. My software lead did this, I showed it to her and she said: Umm... I... yeah... I wasn't thinking :) .

We both laughed and I rewrote it all :) .

C0lumbo
C0lumbo

If it's a floating point number with a NaN value then (foo != foo) and the code could go into the else block.

ysg
ysg

If it's a floating point number with a NaN value then (foo != foo) and the code could go into the else block.

I'm 90% certain that it was an into of some sort. It was pretty funny and

we both were like, yeah, this will not be mentioned in polite company

ever again :) .

21st Century Moose
21st Century Moose

Of course if it's C++ and someone has overloaded operator == then literally anything could happen.

Direct3D has need of instancing, but we do not. We have plenty of glVertexAttrib calls. 
Bacterius
Bacterius

Of course, one could have written #define foo rand() and #define bar time(0) to be particularly treacherous. Then it would make sense. Sort of.

“If I understand the standard right it is legal and safe to do this but the resulting value could be anything.”
Buster2000
Buster2000

Couldn't foo and bar also be declared volotile?

Adaline
Adaline

when x is a floating point number, if (x!=x) permits to check if x is NaN. This is terribly ugly .... but that's it wacko.png

Hodgman
Hodgman

Couldn't foo and bar also be declared volotile?

Yeah, without volatile foo==foo compiles to pseudo-asm like:


int reg0 = read(&foo);
bool reg1 = compare( reg0, reg0 );

But with volatile, it would compile to something like:


int reg0 = read(&foo);
int reg1 = read(&foo);
bool reg2 = compare( reg0, reg1 );

So if the memory at &foo is constantly changing, the comparison could possibly be false.

However, that kind of code should probably never be written. Generally if your code contains volatile, then you have a bug tongue.png

About the only place it's valid to see that keyword used, would be inside the implementation of std::atomic.

ysg
ysg

Couldn't foo and bar also be declared volotile?

I don't think I've ever used volatile in my entire coding career.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.