Accelerated C++ Solution to Exercise 1-1

Exercise 1-1

Are the following definitions valid? Why or why not?

const std::string hello = "Hello";
const std::string message = hello + ", world" + "!";

Solution

Yes. These definitions are valid.

The key in answering this question is to acknowledge the use of the string concatenation operator +.

  • It is left associative.
  • We can use + to concatenate a string and a string literal (and vice versa), or a string and a string, but not a string with a string literal (nor vice versa).

Line 1 defines a string variable hello with length of 5 characters (which is Hello). This line is valid.

Line 2 defines a string variable message with the concatenation operator. The logic looks like this:

message = ( ( hello + ", world" ) + "!") 
        = ( ( a string + a string literal ) + a string literal )
        = ( ( a string ) + a string literal )
        = ( a string + a string literal )
        = ( a string )

i.e. at every single stage, we have not encountered any invalid string literal + string literal scenario. The concatenation is therefore valid.

Let’s test running the following program to prove the validity of the program.

#include <iostream>
#include <string>
int main()
{
    const std::string hello = "Hello";
    const std::string message = hello + ", world" + "!";
    std::cout << message << std::endl;
    return 0;
}

Result

As expected, the program compiled okay and produce the expected output.

Hello, world!

Process returned 0 (0x0)   execution time : 0.214 s
Press any key to continue.

Reference

Koenig, Andrew & Moo, Barbara E., Accelerated C++, Addison-Wesley, 2000

3 thoughts on “Accelerated C++ Solution to Exercise 1-1”

  1. why is the “!” valid?
    Since ! is a character literal, and should always enclosed in signal quotes.

  2. We can use + to concatenate a string and a string literal (and vice versa), …. , but not a string with a string literal (nor vice versa). This seems like a contradiction, could you please clarify?

Comments are closed.