[C++] Strange problem stacking multiple OR's

Solved

I'm writing a pretty simple c++ collision algorithm that first checks if the object is within bounds of a mesh grid. However, when I do a stacked OR to see if the values are within bounds, it always triggers as TRUE (even when the object is in bounds)

    if (pos.x <= mesh->X(0, 0)) // None of these evaluate to TRUE
	{
		cout << "<X" << endl;
	}
	if (pos.x >= mesh->X(iw - 1, ih - 1))
	{
		cout << ">X" << endl;
	}
	if (pos.y <= mesh->Y(0, 0))
	{
		cout << "<Y" << endl;
	}
	if (pos.y >= mesh->Y(iw - 1, ih - 1))
	{
		cout << ">Y" << endl;
	}

// But for some reason, this is:
if ( pos.x <= mesh->X(0, 0) || pos.x >= mesh->X(iw-1, ih-1) || pos.y <= mesh->Y(0, 0) || pos.y >= mesh->Y(iw-1, ih-1) );
    	{
    		cout << " Bound Error " << endl;
    		cData.outOfBounds = true;
    		;
    	}    

Is there some nuance of stacking logical OR's that I am missing? If it helps all the values are GLfloat type.

Posted Jun 9, 2014, 3:36 AM UTC

26
zifyoip•
if ( pos.x <= mesh->X(0, 0) || pos.x >= mesh->X(iw-1, ih-1) || pos.y <= mesh->Y(0, 0) || pos.y >= mesh->Y(iw-1, ih-1) );

Look at that line carefully. You have a semicolon at the end.

So the if statement is being applied to the immediately following statement, which is an empty statement. The body of the if statement is empty. The block that follows on the next line is not controlled by the if condition.

===

Make sure you have all warnings turned on in your compiler, and pay attention to what they say. Some compilers will warn you about empty bodies of if statements:

$ cat program.cpp
int main()
{
	int a = 1, b = 2;
	if (a < b);
	{
		++a;
	}
	return 0;
}
$ clang++ -Wall -Wextra -o program program.cpp
program.cpp:4:12: warning: if statement has empty body [-Wempty-body]
		if (a < b);
				  ^
program.cpp:4:12: note: put the semicolon on a separate line to silence this
	  warning
1 warning generated.
5
KeyLordAUOP•

WOW, THANK YOU!

I always thought that would result in a compilation error. I can't believe I made a mistake that stupid... Sometimes it takes two sets of eyes.

1
zifyoip•

I always thought that would result in a compilation error.

No, it's a perfectly valid thing to write. Sometimes you want an empty body of a loop or an if statement. But most of the time you don't, and that's why you should turn on all compiler warnings.

3
KeyLordAUOP•

Yeah... I should turn on all compiler warnings, but there are a LOT of warnings already in this code.

1
zifyoip•

Then you should fix those things.

3