what does cout << “\n”[a==N]; do?

后端 未结 5 1455
予麋鹿
予麋鹿 2020-12-13 23:02

In the following example:

cout<<\"\\n\"[a==N];

I have no clue about what the [] option does in cout, but it

5条回答
  •  半阙折子戏
    2020-12-13 23:55

    It's probably intended as a bizarre way of writing

    if ( a != N ) {
        cout<<"\n";
    }
    

    The [] operator selects an element from an array. The string "\n" is actually an array of two characters: a new line '\n' and a string terminator '\0'. So cout<<"\n"[a==N] will print either a '\n' character or a '\0' character.

    The trouble is that you're not allowed to send a '\0' character to an I/O stream in text mode. The author of that code might have noticed that nothing seemed to happen, so he assumed that cout<<'\0' is a safe way to do nothing.

    In C and C++, that is a very poor assumption because of the notion of undefined behavior. If the program does something that is not covered by the specification of the standard or the particular platform, anything can happen. A fairly likely outcome in this case is that the stream will stop working entirely — no more output to cout will appear at all.

    In summary, the effect is,

    "Print a newline if a is not equal to N. Otherwise, I don't know. Crash or something."

    … and the moral is, don't write things so cryptically.

提交回复
热议问题