0
C++ Which is always true?
Given the following code fragment, which of the following expressions is always true? int x; cin >> x; 1. if( x < 3) 2. if( x==1) 3. if( x = 1) 4. if( (x / 3) >1 ) Please explain your answer.
2 ответов
+ 8
if(x = 1)
the assignment of a value returns the value that was assigned
https://stackoverflow.com/questions/14697643/low-level-details-of-c-c-assignment-operator-implementation-what-does-it-retu
and as the assigned value is 1 (which translated as a true value) the if will always be true
all other if statements are dependant on user input as a comparison is being made (instead of assignment that in this case is true)
if you were to try if(x = 0) you would have gotten a false statement as 0 would have been returned and evaluated as false
+ 1
Only line 3 is always true.
This is actually a quite nice thing you found out. At first it was confusing, but I think I've got an explaination.
In c++ to check equality you use ==. At line 3 you used only =. So instead of checking x against 1, you are making the value of x equal to 1. Also because you are missing the actual condition ==, c++ automatically checks if x is equal to true. Which it is because in c++ every number except from zero is equal to true. What you are doing translates to this
if(1 == 1)