Why allow concatenation of string literals?

前端 未结 10 581
借酒劲吻你
借酒劲吻你 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:40

    From the python lexical analysis reference, section 2.4.2:

    This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings

    http://docs.python.org/reference/lexical_analysis.html

    0 讨论(0)
  • 2020-11-30 15:43

    Sure, it's the easy way to make your code look good:

    char *someGlobalString = "very long "
                             "so broken "
                             "onto multiple "
                             "lines";
    

    The best reason, though, is for weird printf formats, like type forcing:

    uint64_t num = 5;
    printf("Here is a number:  %"PRIX64", what do you think of that?", num);
    

    There are a bunch of those defined, and they can come in handy if you have type size requirements. Check them all out at this link. A few examples:

    PRIo8 PRIoLEAST16 PRIoFAST32 PRIoMAX PRIoPTR
    
    0 讨论(0)
  • 2020-11-30 15:45

    I certainly have in both C and C++. Offhand, I don't see much relationship between its utility and how "modern" the language is.

    0 讨论(0)
  • 2020-11-30 15:47

    I'm not sure about other programming languages, but for example C# doesn't allow you to do this (and I think this is a good thing). As far as I can tell, most of the examples that show why this is useful in C++ would still work if you could use some special operator for string concatenation:

    string someGlobalString = "very long " +
                              "so broken " +
                              "onto multiple " +
                              "lines"; 
    

    This may not be as comfortable, but it is certainly safer. In your motivating example, the code would be invalid unless you added either , to separate elements or + to concatenate strings...

    0 讨论(0)
提交回复
热议问题