What does "<<" do exactly?

Hello,

So I did the challenge and came up with:

cout << “Welcome to Bulls and Cows, a fun word game.” <<endl;
cout << "Can you guess the “;
cout << WORLD_LENGTH;
cout << " letter isogram I’m thinking of?\n”;

This differs from the proposed solution, which is:

cout << “Welcome to Bulls and Cows, a fun word game.” <<endl;
cout << “Can you guess the " << WORLD_LENGTH;
cout << " letter isogram I’m thinking of?\n”;

My question is; Was my way less efficient? Does it really matter? And what does “<<” do exactly?

Cheers to whoever responds, Kim

The double chevrons tell the compiler that there are multiple elements subject to the command on the same line. In this case the command is “std::cout”. Technically you could have written the whole thing as:

cout << “Welcome to Bulls and Cows, a fun word game.\nCan you guess the " << WORD_LENGTH << " letter isogram I’m thinking of?\n”

(word-wrap prevents it from showing all on one line) and that would have been fine. However, ask yourself this: If you were reading an unfamiliar program, which of these three ways would be easiest to understand?

EDIT (image of the single line)

1 Like

<< is an operator in the iostream library. In this case, when combined with a cout object, it basically says “add this to an output stream”. Like most operators, it can be chained. Like int number = 5+5+5+5+5; or int x,y,z;

2 Likes

Technically, the << is called a bitwise operator which is a build in operator to C++ along with things like +, -, &&, ||…

Ostream, which is part of the library actually overloads it, which basically means customizes what it can do ( i.e. you could overload the + operator to actually subtract two numbers - good example, but in reality no one would actually do this).

1 Like

Privacy & Terms