r/AskComputerScience • • Nov 02 '20

Can anyone trace this c++ program?

Post image
33 Upvotes

12 comments sorted by

View all comments

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!