Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator precedence for "=" and "||"

I have a sample midterm question that I am not too sure about. Here it is:

#include <iostream.h>

void f(int i)
{
    if(i = 4 || i = 5)
        return;
    cout << "Hello, World!\n";
}

int main()
{
    f(3);
    f(4);
    f(5);
    return 0;
}

So I understand that the logical OR operator has a higher precedence and that it is read left to right. I also understand that what's being used is an assignment operator instead of the relational operator.

I just don’t get how to make sense of it all. The first thing the compiler would check would be 4 || i? How is that evaluated and what happens after that?

like image 899
tyler16 Avatar asked Jan 29 '26 16:01

tyler16


1 Answers

Let's add all the implied parentheses (remembering that || has higher precedence than = and that = is right-associative):

i = ((4 || i) = 5)

So, it first evaluates 4 || i, which evaluates to true (actually, it even ignores i, since 4 is true and || short-circuits). It then tries to assign 5 to this, which errors out.

like image 94
Angew is no longer proud of SO Avatar answered Jan 31 '26 07:01

Angew is no longer proud of SO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!