3

Given a C++ function foo:

bool foo();

and the following lines of code

bool some_bool = false;
some_bool = some_bool and foo();

I observed that foo() is not called although it might have side-effects. What is the name of this behavior and is it compiler-dependent?

Cristik
  • 30,989
  • 25
  • 91
  • 127
Elrond1337
  • 424
  • 1
  • 5
  • 16

2 Answers2

5

This is called short-circuit evaluation.

In your example, some_bool is false and so the statement some_bool && foo() is always going to be false. So there is never any need to evaluate foo().

Note that this is standard C/C++ and is not compiler dependent as it can lead to unperformed code as you've discovered.

A better way of writing the code is:

bool some_bool = false;
bool foo_result = foo();
some_bool = some_bool && foo_result;
CadentOrange
  • 3,263
  • 1
  • 34
  • 52
  • Calling this "better" is naive. The two are different programs, as you pointed out. Your version does not do the same thing as the OP's. So is it automatically "better" if it in fact does not achieve the OP's requirements? (Or vice versa) – Lightness Races in Orbit May 15 '15 at 10:14
  • I do not get what you are driving at. The original code does is broken and does not work. The version here does. It is "better" unless the OP's intention is to write broken code. – CadentOrange May 15 '15 at 12:19
  • Nothing in the question says the code is "broken" or "does not work". This is a question about whether short-circuiting is reliable. Whether you actually want it or not will depend on the circumstances: you cannot say, in general, that one is "better" than the other. – Lightness Races in Orbit May 15 '15 at 13:36
2

If some_bool is already false, then foo() will not be called (optimization), since whatever foo() returns, the end result is always false.

rcs
  • 6,713
  • 12
  • 53
  • 75
  • @juanchopanza Thanks for the information. Glad I learn something new. – rcs May 15 '15 at 09:36
  • Calling it "optimization" makes it sound like an optional compiler behaviour. It's not "optimization". It's a reliable fact of the language semantics that has hard consequences. "Optimization" tends to describe the compiler taking shortcuts _without changing semantics_. – Lightness Races in Orbit May 15 '15 at 10:15
  • 1
    This is important, since it happens independently of whether you use optimization in your compiler or not. – Elrond1337 May 15 '15 at 10:25