Why allow concatenation of string literals?

前端 未结 10 659
借酒劲吻你
借酒劲吻你 2020-11-30 14:47

I was recently bitten by a subtle bug.

char ** int2str = {
   \"zero\", // 0
   \"one\",  // 1
   \"two\"   // 2
   \"three\",// 3
   nullptr };

assert( int         


        
10条回答
  •  执念已碎
    2020-11-30 15:26

    For rationale, expanding and simplifying Shafik Yaghmour’s answer: string literal concatenation originated in C (hence inherited by C++), as did the term, for two reasons (references are from Rationale for the ANSI C Programming Language):

    • For formatting: to allow long string literals to span multiple lines with proper indentation – in contrast to line continuation, which destroys the indentation scheme (3.1.4 String literals); and
    • For macro magic: to allow the construction of string literals by macros (via stringizing) (3.8.3.2 The # operator).

    It is included in the modern languages Python and D because they copied it from C, though in both of these it has been proposed for deprecation, as it is bug-prone (as you note) and unnecessary (since one can just have a concatenation operator and constant folding for compile-time evaluation; you can’t do this in C because strings are pointers, and so you can’t add them).

    It’s not simple to remove because that breaks compatibility, and you have to be careful about precedence (implicit concatenation happens during lexing, prior to operators, but replacing this with an operator means you need to be careful about precedence), hence why it’s still present.

    Yes, it is in used production code. Google Python Style Guide: Line length specifies:

    When a literal string won't fit on a single line, use parentheses for implicit line joining.

    x = ('This will build a very long long '
         'long long long long long long string')
    

    See “String literal concatenation” at Wikipedia for more details and references.

提交回复
热议问题