Search code examples
c++single-quotes

C++ single quotes syntax


I am learning C++ and just started reading "Programming Principles and Practice" by Bjarne Stroustrup and he uses this code to illustrate a point:

#include "std_lib_facilities.h"

using namespace std;

int main() // C++ programs start by executing the function main
{
char c = 'x';
int i1 = c;
int i2 = 'x';

char c2 = i1;
cout << c << ' << i1 << ' << c2 << '\n';

return 0;
}

I am familiar in general with the difference between double and single quotes in the C++ world, but would someone kindly explain the construction and purpose of the section ' << i1 << '

Thanks


Solution

  • cout << c << ' << i1 << ' << c2 << '\n';
    

    appears to be a typo in the book. I see it in Programming Principles and Practice Using C++ (Second Edition) Second printing. I do not see it listed in the errata.

    According to the book, the intended output is

    x 120 x
    

    But what happens here is ' << i1 << ' attempts to compress the << i1 << to a multi-byte character and prints out an integer (most likely 540818464-> 0x203C3C20 -> ASCII values of ' ', '<', '<', ' ') because cout doesn't know wide characters. You'd need wcout for that. End result is output something like

    x540818464x
    

    and a warning or two from the compiler because while it's valid C++ code, it's almost certainly not what you want to be doing.

    The line should most likely read

        cout << c << ' '  << i1 << ' ' << c2 << '\n';
    

    which will output the expected x 120 x

    In other words, Linker3000, you are not crazy and not misunderstanding the example code.

    Anyone know who I should contact to log errata or get a clarification on the off chance there is some top secret sneakiness going way over my head?