-1

In C, using GCC, when a if statement is writen like:

if(function() || A==B)

Can we consider that if A equals B, the function() is not executed? Is it the case when the statement is written like:

if(A==B || function())

I know that is more clear to call the function before the statement if we want it to be executed each time, but the code I read is like that.

  • 2
    Does [this](https://stackoverflow.com/questions/45848858/short-circuit-evaluation-on-c) answer your question? Note that the order matters so `if (a() || b())` will call only `a` if it returns `true`, while `if (b() || a())` will call both `b` and `a` (in this order) if `b` returns false. – icebp Mar 04 '21 at 09:05

1 Answers1

4

The C language requires that the short-circuiting operators || and && process their operands from left to right. So it will always evaluate the left operand, but the right operand will be evaluated conditionally. For || it evaluates the right operand if the left operand is false. For && it oevaluates the right operand if the left operand is true.

So order definitely matters. function() || A == B calls the function. If it returns false, it will then test A == B. But A == B || function() first tests A == B, and only calls the function if they're not equal.

This is not specific to GCC, it's part of the language specification (and it's similar in many other languages). It's also not related to if, since you can use logical operators anywhere that an expression is allowed, e.g.

int foo = function() || A==B;
Barmar
  • 741,623
  • 53
  • 500
  • 612