Are logical OR and comma operators equivalent?

711 Views Asked by At

Today I found a syntax thing I had never seen before. Are || and , the same?

bool f() {

    cout << "f";
    return true;
}

bool g() {

    cout << "g";
    return true;
}

int main() {


    if(f(),g())
    {
        cout<<"OK with ,";
    }

    cout<<endl;

    if(f()||g())
    {

        cout<<"OK with ||";
    }

    return 0;
}

From the output of this program, it seems so:

fgOK with ,
fOK with ||

Are they the same exact thing or are there any little differences?

4

There are 4 best solutions below

0
On

f(),g() means evaluate f() then evaluate g() and return g() since your g() returns true it is that what is returned to if

So, no, the operators are totally different.

You can see the difference if you modify your function to return false from g(). The condition f()||g() will still evaluate to true while f(),g() will return false.

0
On

This (comma operator)

if(f(),g())

will evaluate both f() and g() and return the value of the second operand g()

The logical OR operator

if(f()||g())

will not evaluate g() if f() evaluates to true. This is known as short-circuit evaluation - if f() returns true, then the logical OR condition is already satisfied - hence there is no point evaluating g().

So they are NOT the same at all even though under certain conditions you may see the same overall behaviour.

0
On

They are completely different operators that serve completely different purposes.

The main difference is that:

  • The , operator (unless overloaded) will evaluate all of its arguments and return the last one, no matter what.
  • The || operator will evaluate all the arguments until it reaches the first trueish value and will not evaluate the rest.

This is also the reason why the output, you are claiming to receive, is wrong.

0
On
  • || is the logical OR operator and by standard it follows short-circuit evaluation (i.e. it won't evaluate the second operand if the first already suffices to determine the entire logical expression)

  • , is the comma operator that evaluates both but just return the value of the second operand.

By the way you should be seeing something like:

fgOK with ,
fOK with ||

the reason why you're not seeing it might be because you're using a compiler that doesn't strictly follow the standards (I suspect MSVC..)

http://ideone.com/8dSFiY