Compilation of string literals

后端 未结 5 1227
臣服心动
臣服心动 2021-01-13 16:32

Why can two string literals separated by a space, tab or \"\\n\" be compiled without an error?

int main()
{
   char * a = \"aaaa\"  \"bbbb\";
} 
5条回答
  •  爱一瞬间的悲伤
    2021-01-13 17:20

    In C and C++ compiles adjacent string literals as a single string literal. For example this:

    "Some text..." "and more text"
    

    is equivalent to:

    "Some text...and more text"
    

    That for historical reasons:

    The original C language was designed in 1969-1972 when computing was still dominated by the 80 column punched card. Its designers used 80 column devices such as the ASR-33 Teletype. These devices did not automatically wrap text, so there was a real incentive to keep source code within 80 columns. Fortran and Cobol had explicit continuation mechanisms to do so, before they finally moved to free format.

    It was a stroke of brilliance for Dennis Ritchie (I assume) to realise that there was no ambiguity in the grammar and that long ASCII strings could be made to fit into 80 columns by the simple expedient of getting the compiler to concatenate adjacent literal strings. Countless C programmers were grateful for that small feature.

    Once the feature is in, why would it ever be removed? It causes no grief and is frequently handy. I for one wish more languages had it. The modern trend is to have extended strings with triple quotes or other symbols, but the simplicity of this feature in C has never been outdone.

    Similar question here.

提交回复
热议问题