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.
-
8Every language has precedence rules... en.cppreference.com/w/cpp/language/operator_precedence– chrisCommented Nov 4, 2013 at 7:12
-
Oh, I see, but then, if addition is performed before, how does it give 32?– ShubhamCommented Nov 4, 2013 at 7:17
Add a comment
|
2 Answers
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
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.