Programming Tutorials

Multi-Line Literals in C++

By: Stanley B. in C++ Tutorials on 2011-02-19  

There is a more primitive (and less useful) way to handle long strings that depends on an infrequently used program formatting feature: Putting a backslash as the last character on a line causes that line and the next to be treated as a single line.

C++ programs are largely free-format. In particular, there are only a few places that we may not insert whitespace. One of these is in the middle of a word. In particular, we may not break a line in the middle of a word. We can circumvent this rule by using a backslash:

      // ok: A \ before a newline ignores the line break
      t << "Hi" << st\

is equivalent to

      std::cout << "Hi" << std::endl;

We could use this feature to write a long string literal:

           // multiline string literal
           std::cout << "a multi-line \
      string literal \
      using a backslash"
                    << std::endl;
          return 0;

Note that the backslash must be the last thing on the lineno comments or trailing blanks are allowed. Also, any leading spaces or tabs on the subsequent lines are part of the literal. For this reason, the continuation lines of the long literal do not have the normal indentation.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)