About changing operator trick in C ++?

When I read the code in the buffers of the Google protocol, I found the confused code as follows.

1 < 2 ? (void)0 : cout << "hi" << endl;

The fact is that the string "hi" will be broadcast via NULL with the left shift operator. As a result, nothing happened. This means that this is the correct grammar code.

And I tried a slightly different code as shown below.

(void)0 << "hi" << endl;

Of course, this did not work.

Finally, I tried this code.

string tmp;
cin >> (1 < 2 ? 0 : tmp);

It was compiled, but crashed at runtime. (It works if the character is reversed, but the input is not saved in tmp.)

Is there anyone who can walk me though what happens in the first case? (from a compiler point of view or low level, if possible)

+3
source share
3 answers

, 1 < 2 ? (void)0 : cout << "hi" << endl; :

if(1 < 2) {
    (void)0; //do nothing
} else {
    cout << "hi" << endl;
}

condition ? true-state : false-state; , <<.

+5

<< , ?:, :

 1 < 2 ? (void)0 : cout << "hi" << endl;

:

(1 < 2) ? (void)0 : (cout << "hi" << endl);

:

 ((1 < 2 ? (void)0 : cout)) << "hi" << endl;

(, , condition ? then_expression : else_expresion else_expression, condition .)

+3
1 < 2 ? (void)0 : cout << "hi" << endl;

, , , :

(1 < 2)
    ? (void)0
    : (cout << "hi" << endl);

.

?: void, void throw.

void :

1 < 2 ? (void)0 : (void)(cout << "hi" << endl);

If you can update your question to show the exact code you are asking for, we can probably explain it better.

It would also be interesting to see the context in which this appears. In itself, he would be more picky as an instruction if.

+1
source

All Articles