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

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

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

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

    In C++ operator Precedence table, operator [] binds tighter than operator <<, so your code is equivalent to:

    cout << ("\n"[a==N]);  // or cout.operator <<("\n"[a==N]);
    

    Or in other words, operator [] does nothing directly with cout. It is used only for indexing of string literal "\n"

    For example for(int i = 0; i < 3; ++i) std::cout << "abcdef"[i] << std::endl; will print characters a, b and c on consecutive lines on the screen.


    Because string literals in C++ are always terminated with null character('\0', L'\0', char16_t(), etc), a string literal "\n" is a const char[2] holding the characters '\n' and '\0'

    In memory layout this looks like:

    +--------+--------+
    |  '\n'  |  '\0'  |
    +--------+--------+
    0        1          <-- Offset
    false    true       <-- Result of condition (a == n)
    a != n   a == n     <-- Case
    

    So if a == N is true (promoted to 1), expression "\n"[a == N] results in '\0' and '\n' if result is false.

    It is functionally similar (not same) to:

    char anonymous[] = "\n";
    int index;
    if (a == N) index = 1;
    else index = 0;
    cout << anonymous[index];
    

    valueof "\n"[a==N] is '\n' or '\0'

    typeof "\n"[a==N] is const char


    If the intention is to print nothing (Which may be different from printing '\0' depending on platform and purpose), prefer the following line of code:

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

    Even if your intention is to write either '\0' or '\n' on the stream, prefer a readable code for example:

    cout << (a == N ? '\0' : '\n');
    

提交回复
热议问题