+ 2
What is it? Parsing code from a quiz.
#include <iostream> using namespace std; int main() { int i = 0; cout << (i = 0 ? 1 : 2 ? 3 : 4); return 0; }
32 ответов
+ 3
if ( i = 0 ) // assignment not comparison
returns 0
cout << 1;
else if (2)
cout << 3;
else
cout << 4;
[I was wrong read other comments 4more info]
Answer 3
https://www.sololearn.com/Discuss/42804/?ref=app
+ 3
if(0){ //0 is false
i = 1;
}else if(2){ // 2 is true
i = 3;
}else{
i = 4;
}
cout << i;
+ 2
Why not?
Maybe the author wanted to say i==0 instead of i = 0.
But apart from that I thing everything is fine.
Did you get the code from a quiz?
+ 2
The code prints 3.
+ 2
Finally, I realized this code corresponds to this:
if ((i=0) == true){
i = 1;
}else if ((i=2) != true){
i = 3;
}else{
i = 4;
}
cout << i;
P. S: "the last "else" statement is ": 4", it is only necessary for the compiler to accept the abbreviated syntax for writing "if ... else if ... else ..." "
+ 2
Vasiliy you are right! Assignment operator has lower precedence I missed that.
But i = 2 is true.
david chongo ? : Ternary operator takes an expression and returns something based of the boolean value of that expression:
(exp)?(returnIfTrue):(returnIfFalse)
Read above code like this:
cout<< (i= (0 ? 1 : ( 2 ? 3 : 4 ) )
Both operators are taking 3 operands but the first operator's third operand is just another expression containing a ternary operator.
Abhay S G shankur 0 is false so ans can't be 1
+ 2
Александр J, я не ставил цель выяснить какой будет вывод, я ставил цель выяснить как этот код работает и насколько он написан корректно, так что это как раз и принципиально в данном случае.
P. S: "ошибка не в выражении, даже если вы измените на присвоение, всё равно ваш код ничего не выведет".
+ 1
I tried with "==", all the same, only the first part of the code works correctly.
Under no circumstances can you print 4.
+ 1
3
+ 1
Kevin Star, 👏bravo, finally you and I have reached the truth.
+ 1
Kevin Star, that's just the "else" here is completely useless, enough like this:
if(0){
i = 1;
}else if(2){
i = 3;
}
cout << i;
But with the help of a tennis operator you can’t write it like this:
cout << (i = 0 ? 1 : 2 ? 3);
- will give an error.
+ 1
Дальше, хуже. Только, предположения :(
JavaScript для меня, пока, только, язык учебных моделей, а не реальных проектов, поэтому, из дискуссии самовыпиливаюсь до достижения приемлемого багажа знаний. Впрочем, используя, ваши высказывания, в качестве паттерна, - свою логику, я - тоже, объяснял этажом выше :) Пусть, она, и, строилась на неверных исходных предпосылках.
0
Kevin Star, I assumed something similar, but then I don’t understand how it works...
0
Kevin Star, after a long analysis of this code, I still came to the conclusion that it was not written correctly and did not work as it should.
0
Although with the standard:
"if ... else if ... else... "
everything works flawlessly.
0
Try to search about unary
0
From the quiz the answer should be 2 I think
0
david chongo, do not rush to the conclusion.
0
Vasiliy, I understand. I should have added to say perhaps there is something missing. In my view, since the conditional operator takes 3. If then we don't have those 3 inputs, I am not sure if we can proceed any further. Here now I would want to agree somehow with suggestion by Farnaz.A above
0
The ternary or conditional statement checks a condition and then assigns true or false result. In this question there is use of one '=' which is the assignment operator and not a conditional operator like '=='. So it appears really that what was needed was the conditional operator to test the value of the variable as being equivalents to the declared value of i=0. And depending on the result we can then attribute a true or false to the variable.