Question

So I just took a CS101 C++ quiz and this was one of the problems:

int x=5;
if(x=2)
  cout <<"this is true"<<endl;
else
  cout <<"this is false"<<endl;
  cout <<"this is all folks"<<endl;

following choices are given for what can be the possible output

a. this is true
b. this is false
c. this is true
   this is false
d. this is true
   this is all folks
e. None of the above

Now I noticed that the if statement was testing an assignment so I circled e.) because I figured the output should be a syntax error. I don't think an assignment cant be evaluated true or false. The instructor marked me wrong. Reason being that an argument that is greater than 0 is true. I told the professor that this is not possible unless x=2 is surrounded by parentheses. That x=2 by itself is not true or false. The instructor then stated that we shouldn't expect code on test or quiz to be runnable that logic was being tested not syntax. But logically x=2 is neither true or false, right???

I wasn't arguing for the points; it was only 1 of two that I got wrong. But the instructor was adamant that the quiz problem was written correctly and ended the dialog. I don't think the instructor appreciated me questioning her on this...she brushed me off rather rudely. Anyways I ran the code using vim/g++ and it gave me syntax error, recommended that I put parentheses around the assignment. Could it be that some compilers are more picky??

Was it helpful?

Solution

Yes: int to bool conversion:

if(x=2) //2 is non 0 converts to true

Therefore it will print this is true. A and D are the only remaining choices. And because of

else
  cout <<"this is false"<<endl;
  cout <<"this is all folks"<<endl; //not included in `else`, will print no matter what

this is all folks will also print.

The correct answer is D.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top