Short-circuit evaluation in if?

I could not find it in the documentation (https://cmake.org/cmake/help/latest/command/if.html), but it would seem that conditions do not short-circuit.
Is that correct?

if(DEFINED MY_VAR AND ${MY_VAR} STREQUAL "true")
The command above returns:

CMake Error at CMakeLists.txt:23 (if):
  if given arguments:

    "DEFINED" "MY_VAR" "AND" "STREQUAL" "true"

  Unknown arguments specified

which leads to think the second part is evaluated, and returns nothing (and not an empty string), when the variable is not defined.

I think it first perform all the required substitutions and then parses the command. This gives you the possibility to define entire condition in a variable. Then are the arguments checked and it blows up.

You can simply write (i.e. do not expand the variable):

if (MY_VAR STREQUAL "true")

In this case, a non-existing variable will evaluate to FALSE (boolean value as defined by CMake).

And, in the case of expected value is a true value as defined by CMake:

if (MY_VAR)
1 Like

To expand on the accepted answer, It’s not short circuit behavior.

Refer to https://cmake.org/cmake/help/v3.18/command/if.html and Variable Expansion.

The if command was written very early in CMake’s history, predating the ${} variable evaluation syntax, and for convenience evaluates variables named by its arguments as shown in the above signatures. Note that normal variable evaluation with ${} applies before the if command even receives the arguments.