2

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 dont 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?

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
tyler16
  • 73
  • 6

3 Answers3

8

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.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
3

As written, the code doesn't compile, since operator precedence means it's i = ((4 || i) = 5) or something, and you can't assign to a temporary value like (4 || i).

If the operations are supposed to be assignment = rather than comparison == for some reason, and the assignment expressions are supposed to be the operands of ||, then you'd need parentheses

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

As you say, the result of i=4 is 4 (or, more exactly, an lvalue referring to i, which now has the value 4). That's used in a boolean context, so it's converted to bool by comparing it with zero: zero would become false, and any other value becomes true.

Since the first operand of || is true, the second isn't evaluated, and the overall result is true. So i is left with the value 4, then the function returns. The program won't print anything, whatever values you pass to the function.

It would make rather more sense using comparison operations

i == 4 || i == 5

meaning the function would only print something when the argument is neither 4 nor 5; so it would just print once in your example, for f(3).

Note that <iostream.h> hasn't been a standard header for decades. You're being taught an obsolete version of the language, using some extremely dubious code. You should get yourself a good book and stop wasting time on this course.

Community
  • 1
  • 1
Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
1

The compiler shall isuue an error because expression 4 || i is not a lvalue and may not be assigned.

As for the expression itself then the value of it is always equal to true because 4 is not equal to zero.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335