Look at the difference :
x = x<<1 + x<<3
x = 1<<1 + 1<<3 // execute 1+1 first
x = 1<<2<<3 // execute 1<<2
x = 4<<3
x = 32
and this
x = (x<<1) + (x<<3)
x = (1<<1) + (1<<3)
x = 2 + 8
x = 10
Frage
I want to multiply a number by 10 using bit-shift operators.
To try, I initialized x = 1
. Then I assigned x = x<<1 + x<<3
.This printed x = 32
.
But when I assigned x = (x<<1) + (x<<3)
, it printed x = 10
.
Where does this difference come from?
I am using c++11.
Lösung
Look at the difference :
x = x<<1 + x<<3
x = 1<<1 + 1<<3 // execute 1+1 first
x = 1<<2<<3 // execute 1<<2
x = 4<<3
x = 32
and this
x = (x<<1) + (x<<3)
x = (1<<1) + (1<<3)
x = 2 + 8
x = 10
Andere Tipps
The expressions in the parenthesis are being evaluated first. Without them, the shift operations are being performed before the addition.
First, C++ evaluates (x << 1) which equals 2.
Then it evaluates (x << 3) which equals 8.
Finally, it adds them 2 + 8 = 10.