+ 6

Basic operation on cout

for (int m=0;m<3;++m) { cout << m%2?m:m+2; } why output of this code is 010 ?

20th May 2018, 5:55 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
9 Respostas
+ 11
The reason why you got 010 instead of 214 is because the statement was evaluated as: (cout << m%2)?m:m+2; instead of cout << (m%2?m:m+2); http://en.cppreference.com/w/cpp/language/operator_precedence
20th May 2018, 6:15 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
It seems that c++ just looks at m%2 if you don't put the whole block in parentheses: cout << (m%2?m:m+2)
20th May 2018, 6:12 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 3
Rahul George 214 is correct: m = 0 -> false -> m+2 = 2 m = 1 -> true -> 1 m = 2 -> 2%2=0 -> false -> m+2 = 4
20th May 2018, 6:21 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 1
No paranthesis changes precedence level. Modulus has highest precedence and will do it first.
22nd May 2018, 2:09 AM
Apple Blossom
Apple Blossom - avatar
0
endoo emo
29th May 2018, 8:12 PM
Sea
Sea - avatar
0
thanks to all
20th Jun 2018, 3:18 AM
DK Khan
DK Khan - avatar
0
214
27th Jun 2018, 11:36 AM
Abdul-Elah Sadiq
0
in c++ how can i solve if a problem can make?
22nd Oct 2018, 1:55 PM
Abdikariim siciid
0
то
6th Mar 2019, 4:55 PM
Нурдаулет Октамов
Нурдаулет Октамов - avatar