Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About shift operator trick in C++?

Tags:

c++

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)

like image 606
z3moon Avatar asked Dec 09 '25 22:12

z3moon


1 Answers

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 <<.

like image 126
OneOfOne Avatar answered Dec 11 '25 10:12

OneOfOne