Search code examples
visual-c++commentsc++17c-strings

Multi-line wide string constant that allows single line comments in C++


This question of how to break up a (wide) string constant along multiple lines in code has been asked and answered multiple times on this platform (here, for example). I have been using the following approach to declare a static wide string in the class definition itself:

#include <Windows.h>    
#include <iostream>

class Test
{
    public:
        static constexpr WCHAR TEST[] = L"The quick brown fox" \
                                        L"jumped over the" \
                                        L"lazy dog!";
    /* ... */
};

int main ()
{
    wprintf(Test::TEST);
    return 1;
}

However, this approach does not work very well if you want to start commenting each line of your multi-line string. The only way you can achieve this is if you stick a multi-line comment in between the string and the backslash (\) like so:

class Test
{
    public:
        static constexpr WCHAR TEST[] = L"The quick brown fox" /* A comment */\
                                        L"jumped over the" /* Another comment*/\
                                        L"lazy dog!";
    /* ... */
};

If you put a comment after the backslash (\), then a compiler error is raised. This means, you cannot use the traditional single line comment (//) with this method. As a matter of fact, if you put a single space after the backslash (\), then a compiler error is generated.

My question is as follows, is there a way to declare a wide string over multiple lines where you can use single line comments (//) to comment each line?

I am idling looking for something like this (similar to Java):

static constexpr ... = L"The quick brown fox" +  // A little comment here...
                       L"jumped over the" +      // A little comment there.
                       L"lazy dog!";

I understand things are incredibly different in Java (i.e. namely everything is an object), but I am just giving this as an example of what I am after.


Solution

  • Simply drop the backslashes:

        static constexpr WCHAR TEST[] = L"The quick brown fox" // a comment
                                        L"jumped over the"     // another comment
                                        L"lazy dog!";          // yet another comment
    

    Comments are replaced by space characters in translation phase 3. Adjacent string literals are concatenated in translation phase 6.