3

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.

2

2 Answers 2

10

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
0
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.