r/AskComputerScience • • Nov 02 '20

Can anyone trace this c++ program?

Post image
33 Upvotes

12 comments sorted by

34

u/nattack Nov 02 '20

While the question seems to be sort of answered, I have a question for you: is this a question on a college test? and if so, have you considered getting your money back?

1

u/Firestormwannabefat Nov 02 '20

Working on it and trying to learn through Reddit lol. My professor sucks. This not a test btw

14

u/khedoros Nov 02 '20

Sure. Although there are a couple of patterns in the code that suggest it has some typos/bugs, as posted.

3

u/Firestormwannabefat Nov 02 '20

It prints out x= 0 I am not sure how the value of x becomes 0 because I don't understand the expression in the while statement

48

u/khedoros Nov 02 '20

First: x= is an assignment operation, not an equality operation.

Second: (3||'x') evaluates to true, since both 3 and the character 'x' evaluate to true, and you're basically taking the logical-or of true or true. This result is represented by 1 when interpreted as an integer in the comparison 1 > 88, which evaluates to false (represented by 0 when stored in x).

So the whole thing x = (3 || 'x') > 88 is equivalent to x = 0.

In while(x = 0), x is assigned the value 0, which is also what it returns as the conditional value for the while loop. So the loop body never executes.

3

u/flan666 Nov 02 '20

best answer =)

2

u/[deleted] Nov 02 '20

You... are dope!

5

u/jmordicle Nov 02 '20

That's because instead of comparison operation == it's doing a set operator =

So maybe it's changing X's value

30

u/[deleted] Nov 02 '20
int x = 8;

while(x = (3 || 'x') > 88)
  cout << ++x; //this code will never run

cout << "x = " << x;    

it's equivalent as:

int x = 8;
x = (3 || 'x') > 88;
cout << "x = " << x;

then let's find out the second line

(3 || 'x') // x has a value of 120 (ascii)
(3 || 120) // evaluates to 1
1

1 > 88 // evaluates to 0

so now the code looks like this

int x = 8;
x = 0;
cout << "x = " << x;

0

u/kevin16_ Nov 02 '20

What does ‘ ‘ change x into? Because I would imagine it to be x=(3||x). I think it would work either way right because x = 8 and if we just remove the single quotations, it’ll still be x = x which is x= 8. Dang what I’m saying might be a little confusing, but I hope you get what I mean. Putting ‘ ‘ changes it into a char right?

6

u/thehellnokitty Nov 02 '20

‘x’ is a character literal and does not reference the variable x in any way.

‘x’ is evaluated to its ASCII value of 120 in the expression (3 || ‘x’).

So (3 || 120) evaluates to 1.

2

u/kevin16_ Nov 02 '20

I see. Thanks!