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

C question

Started by daniel_i_l Apr 1, 2009 at 6:13 PM 5 replies 700+ views
Original Post
daniel_i_l
daniel_i_l
Let's say I have a pointer i_p and I want to check if it's true, and if it is, evaluate a = f(i_p) and then check that a > and a < 5. Can I do:

int a;
if(i_p && a=f(i_p) && a>0 && a<5){
...
}


I know that I can accomplish this with a nested if but I'm already somewhat nested so I'd rather do this in one line. Is this more efficient that calling f twice? Does this code have well defined behaviour or am I exploiting an undefined feature? Thanks. [Edited by - daniel_i_l on April 1, 2009 6:34:50 PM]
"We've all heard that a million monkeys banging on a million typewriters will eventually reproduce the entire works of Shakespeare. Now, thanks to the internet, we know this is not true." -- Professor Robert Silensky
SiCrane
SiCrane
&& introduces a sequence point, so it's defined behavior. I'd personally still put it on multiple lines.
LessBread
LessBread
There's no telling if a=f(i_p) will be executed first.
"I thought what I'd do was, I'd pretend I was one of those deaf-mutes." - the Laughing Man
Palidine
Palidine
Quote:
Original post by LessBread
There's no telling if a=f(i_p) will be executed first.


What? That can't be true. Order of operations in a boolean comparison sequence is defined left to right ordering. Otherwise early out code would never work:

This, for example, is guaranteed to never have a NULL pointer exception:
if ( pointer && pointer->SomeBooleanFunction() ){    //do some stuff}


-me
SiCrane
SiCrane
Quote:
Original post by LessBread
There's no telling if a=f(i_p) will be executed first.

No, && is a sequence point. Unless && is overloaded, and you can't overload && on primitives like int and bool, then you're guaranteed that all side effects of evaluations will be completed on the left hand side of an && before evaluation begins on the right hand side.
daniel_i_l
daniel_i_l
Quote:
Original post by LessBread
There's no telling if a=f(i_p) will be executed first.

Why is it possible that a < 0 will be evaluated before a=f(i_p) but not before i_p (the first expression)?
[Edit: I see that this has already been talked about above - thanks everyone]
"We've all heard that a million monkeys banging on a million typewriters will eventually reproduce the entire works of Shakespeare. Now, thanks to the internet, we know this is not true." -- Professor Robert Silensky
DevFred
DevFred
If you make a unsigned, you can eliminate one check. Although that's probably implementation defined or something :)
unsigned a;if(i_p && a=f(i_p) && a<5){...}

Oh, and if you don't need a inside the loop, you can simplify further:
if(i_p && f(i_p) < 5U){...}

Oh wait, that doesn't check for zero.

BTW, is the variable name "i_p" an april's fool joke?

Topic Locked

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

Sign in to reply to this topic.