When I was reading the code in Google Protocol Buffers, I found confused code as follows.
1 < 2 ? (void)0 : cout << "hi" << endl;
The point is that the string "hi' will pipe through NULL by the left shift operator. As a result, nothing happened. That means this is correct code grammatically.
And I tried out little bit different code as below.
(void)0 << "hi" << endl;
Of course, It didn't work.
Lastly, I tried out this code.
string tmp;
cin >> (1 < 2 ? 0 : tmp);
It was compiled but crashed in runtime. (It works if the sign is changed inversely but the input is not stored in tmp.)
Is there someone who can walk me though what to happen in the first case? (in terms of compiler or low level if possible)
You're misreading it, 1 < 2 ? (void)0 : cout << "hi" << endl; translates to :
if(1 < 2) {
(void)0; //do nothing
} else {
cout << "hi" << endl;
}
condition ? true-state : false-state; is called a ternary operator, it absolutely has nothing to do with <<.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With