r/AskComputerScience • u/Firestormwannabefat • Nov 02 '20
Can anyone trace this c++ program?
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 totrue, since both 3 and the character 'x' evaluate totrue, and you're basically taking the logical-or oftrue or true. This result is represented by1when interpreted as an integer in the comparison1 > 88, which evaluates tofalse(represented by0when stored inx).So the whole thing
x = (3 || 'x') > 88is equivalent tox = 0.In
while(x = 0),xis 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
2
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
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 0so 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
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?