0

This is a very detailed question about the logic operators ||, && on C++. Im using them in my code, but I doubt about this code:

bool filluppointer(int*sth);
if (filluppointer(&pointer) || filluppointer2(&pointer))
    return;

filluppointer returns true if something happened, so not always. My question is, if the first function returns true, will the second function in the if block be executed? || is equal to the OR operator, so according to the specification both functions are executed consecutively and then the bools are compared. I just want to create such a structure that the entire if structure returns when encountering the first true function, and it is critical to stop then since I want that specific value in the pointer. Executing another function afterwards will change the value (not in here, but in my real code it does).

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user209347
  • 217
  • 3
  • 11
  • 2
    No, look up [*short circuit evaluation*](http://en.wikipedia.org/wiki/Short-circuit_evaluation). There are plenty of dupes of this question. – juanchopanza Jan 04 '14 at 10:04
  • 2
    A lot of code smell here: int*sth and &pointer –  Jan 04 '14 at 10:07

2 Answers2

7

My question is, if the first function returns true, will the second function in the if block be executed?

No.

C++ uses short-circuit evaluation for && and ||.

Mitch Wheat
  • 295,962
  • 43
  • 465
  • 541
  • To add, C++ only uses short-circuit evaluation for `&&` and `||`, not for other operators. For `&` and `|`, if the operand types are both `bool`, it would be possible the same way. It would even be possible for something like `&` or even `*` on integers if the first operand is known to be zero. But that's not how C++ works. –  Jan 04 '14 at 10:07
  • Just as C does, to be precise – Marco A. Jan 04 '14 at 10:08
  • Yes. I did think about adding that (and C#) but the question is explicitly about C++ – Mitch Wheat Jan 04 '14 at 10:09
3

The C++ standard GUARANTEES that the expression is evaluated left to right, and that as soon as the expression can be known, no further evaluation is done. This is particularly handy for things like:

if (ptr != NULL && ptr->x > 12) ... 

or

if (x != 0 && y / x > 0) ... 

or even this should work:

if (ptr == NULL || ptr->x > 12) 

All of the above would be invalid if the evaluation would be performed "all the way through".

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227