+ 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; }

31st Mar 2020, 6:19 PM
Solo
Solo - avatar
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
31st Mar 2020, 6:27 PM
Kevin ★
+ 3
if(0){ //0 is false i = 1; }else if(2){ // 2 is true i = 3; }else{ i = 4; } cout << i;
2nd Apr 2020, 7:33 PM
Kevin ★
+ 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?
31st Mar 2020, 9:16 PM
Kevin ★
+ 2
The code prints 3.
2nd Apr 2020, 7:33 AM
Juan Arizpe Vega
Juan Arizpe Vega - avatar
+ 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 ..." "
2nd Apr 2020, 1:56 PM
Solo
Solo - avatar
+ 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
2nd Apr 2020, 3:44 PM
Kevin ★
+ 2
Александр J, я не ставил цель выяснить какой будет вывод, я ставил цель выяснить как этот код работает и насколько он написан корректно, так что это как раз и принципиально в данном случае. P. S: "ошибка не в выражении, даже если вы измените на присвоение, всё равно ваш код ничего не выведет".
2nd Apr 2020, 9:33 PM
Solo
Solo - avatar
+ 1
I tried with "==", all the same, only the first part of the code works correctly. Under no circumstances can you print 4.
31st Mar 2020, 9:38 PM
Solo
Solo - avatar
+ 1
3
2nd Apr 2020, 7:08 PM
Александр J
Александр J - avatar
+ 1
Kevin Star, 👏bravo, finally you and I have reached the truth.
2nd Apr 2020, 8:08 PM
Solo
Solo - avatar
+ 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.
2nd Apr 2020, 8:58 PM
Solo
Solo - avatar
+ 1
Дальше, хуже. Только, предположения :( JavaScript для меня, пока, только, язык учебных моделей, а не реальных проектов, поэтому, из дискуссии самовыпиливаюсь до достижения приемлемого багажа знаний. Впрочем, используя, ваши высказывания, в качестве паттерна, - свою логику, я - тоже, объяснял этажом выше :) Пусть, она, и, строилась на неверных исходных предпосылках.
2nd Apr 2020, 9:28 PM
Александр J
Александр J - avatar
0
Kevin Star, I assumed something similar, but then I don’t understand how it works...
31st Mar 2020, 6:41 PM
Solo
Solo - avatar
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.
31st Mar 2020, 9:07 PM
Solo
Solo - avatar
0
Although with the standard: "if ... else if ... else... " everything works flawlessly.
31st Mar 2020, 9:41 PM
Solo
Solo - avatar
0
Try to search about unary
2nd Apr 2020, 8:41 AM
Fandi Presly Simamora
Fandi Presly Simamora - avatar
0
From the quiz the answer should be 2 I think
2nd Apr 2020, 11:27 AM
david chongo
david chongo - avatar
0
david chongo, do not rush to the conclusion.
2nd Apr 2020, 12:42 PM
Solo
Solo - avatar
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
2nd Apr 2020, 1:12 PM
david chongo
david chongo - avatar
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.
2nd Apr 2020, 1:25 PM
david chongo
david chongo - avatar