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

&& operator commutative

Started by Arcamot Oct 16, 2005 at 5:31 AM 4 replies 900+ views
Original Post
Arcamot
Arcamot
Hello have a look at this code: char data[256]; if (!f(data) && (strcmp(data, "") != 0)) { ... } f is a function which modifies the string in some way. We want first the function f to be evaluated and then the chcek whether the string is empty or not. My question is: Can I assume that the evaluation of this is always left to right? Or do I have to write: if (!f(data)) if (strcmp(data, "") != 0) { ... } the first code works, however I dont think that it is 100% right. thanks Sebastian
ToohrVyk
ToohrVyk
&& is not commutative in C++ as it evaluates lazily. This means that, for the code a && b, b will be evaluated if and only if a is false true(and so, a will have to be evaluated first), so you are indeed right in your assumption. The same is also true for ||.
IndyJones
IndyJones
Quote:
Original post by ToohrVyk
b will be evaluated if and only if a is false ...

Isn't b only evaluated if a is true (if a is false the && expression will return false - no matter what b may be).
ToohrVyk
ToohrVyk
Quote:
Original post by BRooksWackerman
Quote:
Original post by ToohrVyk
b will be evaluated if and only if a is false ...

Isn't b only evaluated if a is true (if a is false the && expression will return false - no matter what b may be).


Oops, you are perfectly right. Silly me.

haegarr
haegarr
Yes (at least in C++). In (a && b) the b is evaluated only if a is true, since otherwise the entire expression is already determined: (false && any) is always false. Similarly, in (a || b) b is evaluated only if a is false.

Topic Locked

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

Sign in to reply to this topic.