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

后端 未结 5 1432
予麋鹿
予麋鹿 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:39

    It is not an option of cout but an array index of "\n"

    The array index [a==N] evaluates to [0] or [1], and indexes the character array represented by "\n" which contains a newline and a nul character.

    However passing nul to the iostream will have undefined results, and it would be better to pass a string:

    cout << &("\n"[a==N]) ;
    

    However, the code in either case is not particularly advisable and serves no particular purpose other than to obfuscate; do not regard it as an example of good practice. The following is preferable in most instances:

    cout << (a != N ? "\n" : "") ;
    

    or just:

    if( a != N ) cout << `\n` ;
    

提交回复
热议问题