+ 1
Why this code is not executing my ternary operator statements?
12 odpowiedzi
+ 6
To me this looks like a mistake of "operator precedence":
1 is shoveled into the stream, and only then the ternary is evaluated.
(Is that what's going on, Jayakrishna🇮🇳? My C++ is rusty at best.)
So by putting the ternary in parentheses, it's evaluated first, and only then is the result entering the stream.
+ 6
Jayakrishna🇮🇳 exactly
Though associativity of ternary comparison operator doesn't matter here as "<<" operator have much higher precedence than "?:" operator, hence the expression would be evaluates as
((cout << (1)) ? "c":"3")
= 1?"c":"3" // and 1 would be printed on stdout
+ 5
cout<<(cout<<(1)?"c":"3");
You are not using ternary result..
+ 4
HonFu
For more details clarity,
This hope link clarifies more I guess..
https://stackoverflow.com/questions/68322878/what-does-cout-mean
+ 3
Just put it in brackets, then it works.
cout<<(1?"c":"3")
+ 3
proGAMBLER Your question is "Why it not executing my ternary operator statements? "..
It's executing but you missing the "using of result.. "
Next question: " why not giving error to me for statements after (1)"? because It's syntactically correct.. You know how to use ternary..!!
but it giving warnings of no effect statements..
What actually you are trying? Expected output? Or Expected behavior?
+ 2
I know how to use ternary result..My question why then it is not giving an error to me for statements after (1)
+ 2
HonFu sry, iam not fully understood your reply..
OP question also.. But if iam not wrong..,
ternary operator associativity is Right to left so it's evaluted as
According to syntax:
<Condition> ? <True> : <False> ;
Before? It's like
( cout<<(1)) ? ("c") : ( "3")
So cout<<(1) evaluted and 1 is into stream,...
<< returns outstream pointer (but am not sure am here)
So True block gets evaluated and returns "c".
(Correct me if anything wrong..)
+ 2
Do like this:::
cout<<(1?"c":"3");
+ 1
One question:
In the original line of code, cout << 1 is executed first.
But what is evaluated for the ternary? Still the 1?
Or is it this?
(whatever cout << 1 returns)? 'c': '3';
Ah, so basically this is evaluated, right?
cout? 'c': '3';
Because a cout-operation returns a reference to cout itself?
+ 1
Jayakrishna🇮🇳, thanks!
That confirms what I was thinking - yay! :)
0
Arsenic
Yes. Thanks for adding clarity...
Hope it clarifies OP now...