Guido Tarsia
Guido Tarsia

Reputation: 2172

Why hasn't my variable changed after applying a bit-shift operator to it?

int main()
{
    int i=3;
    (i << 1);
    cout << i; //Prints 3
}

I expected to get 6 because of shifting left one bit. Why does it not work?

Upvotes: 10

Views: 12732

Answers (7)

foxy
foxy

Reputation: 7672

You need to assign i to the shifted value.

int main()
{
    int i=3;
    i <<= 1;
    cout << i; //Prints 3
}

Alternatively, you can use <<= as an assignment operator:

i <<= 1;

Upvotes: 4

Eric Z
Eric Z

Reputation: 14535

Reason: i << 1 produce an intermediate value which is not saved back to variable i.

// i is initially in memory
int i=3;

// load i into register and perform shift operation,
// but the value in memory is NOT changed
(i << 1);

// 1. load i into register and perform shift operation
// 2. write back to memory so now i has the new value
i = i << 1;

For your intention, you can use:

// equal to i = i << 1
i <<= 1;

Upvotes: 2

Jack
Jack

Reputation: 133639

You should use <<= or the value is just lost.

Upvotes: 10

Assaf Lavie
Assaf Lavie

Reputation: 76113

You're not assigning the value of the expression (i << 1); back to i.

Try:

i = i << 1;

Or (same):

i <<= 1;

Upvotes: 4

Justin Aquadro
Justin Aquadro

Reputation: 2310

Because you didn't assign the answer back to i.

i = i << 1;

Upvotes: 3

Mike Bailey
Mike Bailey

Reputation: 12817

Because the bit shift operators return a value.

You want this:

#include <iostream>

int main()
{
     int i = 3;
     i = i << 1;
     std::cout << i;
}

The shift operators don't shift "in place". You might be thinking of the other version. If they did, like a lot of other C++ binary operators, then we'd have very bad things happen.

i <<= 1; 

int a = 3;
int b = 2;
a + b;    // value thrown away
a << b;   // same as above

Upvotes: 22

jonsca
jonsca

Reputation: 10381

You need to reassign the value back to i with i<<=1 (using "left shift and assign operator")

Upvotes: 2

Related Questions