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

If-Then question

Started by thejoshinator Feb 21, 2005 at 11:10 AM 9 replies 800+ views
Original Post
thejoshinator
thejoshinator
Say I have something like
if (!Thisfunc() || !Thatfunc())
                // insert code here
If Thisfunc() returns 0, will the expression still evaluate Thatfunc() or will it skip to the next line?
Scythen
Scythen
Its an 'OR' operation so in order to figure out if one 'OR' the other is true they both may need to be evaluated.

If !Thisfunc() is true, !Thatfunc() will not be evaluated because its already known that one of the arguments to the 'OR' is true.

If !Thisfunc() is false, !Thatfunc() will be evalueated.
Agony
Agony
You could write a program to test it, you know. Wouldn't be too hard.
int Func1(){  printf("Func1\n");  return 0;}int Func2(){  printf("Func2\n");  return 1;}int main(){  if (!Func1() || Func2())    printf("if body\n");  system("pause");  return 0;}
"We should have a great fewer disputes in the world if words were taken for what they are, the signs of our ideas nly, and not for things themselves." - John Locke o
Wan
Wan
Only one of them has to be true.
"!0" is true, so it's skips after the first statement.
Trap
Trap
Not all programming languages do short-cut-evaluation by default. C/C++/Java do it. Eiffel does not.
Wan
Wan
Quote:
Original post by Trap
Not all programming languages do short-cut-evaluation by default. C/C++/Java do it. Eiffel does not.

And VB doesn't either.

Anyway:

int a = 1;int b = 1;int c = 0;// this won't give a "division by zero" error (first statement is true)if ((a / 1) == 1 || (b / c) == 1){    // do stuff}// this however fails (first statement is false, continues to to the second statement)if ((a / 1) == 2 || (b / c) == 1){    // do stuff}
okonomiyaki
okonomiyaki
This is generally considered a bad thing to do also. I'm talking about using function return values in short circuited operations, not just taking advantage of the short circuit operation. Not horrible, but makes it a little harder to read.
Zipster
Zipster
You could always do a little something like this:
if(!ThisFunc() | !Thatfunc()){   // Something}

4.7.4 of the standard states that true is converted to 1 while false is converted to 0 (here for the function return values), and 4.12.1 states that non-zero values are converted to true and zero values are converted to false (here for the conditional), so this type of bitwise logic and opposed to the boolean logic should avoid the short-circuit evaluation and should work according to the standard. However you should probably stick a comment in there somewhere, just so your peers don't rip your heart out Aztec style for using bitwise logic in a conditional, hehe [smile]

Topic Locked

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

Sign in to reply to this topic.