Aka Magdy
Aka Magdy

Reputation: 23

What does int foo = bar << '\n'; mean in c++?

Here is a code that I accidentally write:

int bar = 5;
int foo = bar << '\n';
int cnt = 0;
for (int i = 0; i < foo; i++) {
    cnt++;
}
cout << cnt << '\n';

Why the cnt gives output 5120. I expected that to be a compilation error.

Upvotes: 1

Views: 242

Answers (3)

Karsten
Karsten

Reputation: 2433

<< is a shift operator for integers. It moves the bits to the left. Basically it multiplies by 2^x.

The \n in singlequotes is a character. Characters are like integers and can be used in arithmetic operations.

Upvotes: 1

Temple
Temple

Reputation: 1631

int foo = bar << '\n';

Means move bar value 5 which is in binary 0101 '\n' bits left. '\n' is 10 when interpreted as int.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385224

Well, '\n' is a char which is just another type of number, and << (although we often see it in its overloaded form with streams) is first-and-foremost a "left shift" operator, which works on two numbers.

So, you have the number bar (or 5) and the number '\n' (or, assuming ASCII, 10). Here's how they look in two's complement binary:

0000 0000 00‭00 0101  (5)
       ^^ ^^^^ ^^^^
         ten bits

You shift the 5 left by 10 bits and this gives you...

‭0001 0100 0000 0000‬
       ^^ ^^^^ ^^^^
         ten bits

…or 5120.

By the way, you could have just printed the value of foo, instead of building cnt with a loop.

When you see someStream << '\n' and it does something totally different, it's because someStream is an instance of a class that overloads the operator << giving it a new meaning in that context. Yes, it's a bit confusing.

Upvotes: 5

Related Questions