Given a variable x of type int(which may contain a negative value) which are correct ways of doubling the value of x,barring any overflow? (a) x << 1; (b) x <<= 1; The answer is (b). Can anybody please explain why?? i thought both are correct. Thanks
geetha nagarajan
Ranch Hand
Joined: Jul 13, 2001
Posts: 94
posted
0
a.)x << 1:The value is not assigned back to x,after shifting. b.)x <<=1 :It's actually : x=x<<1. So,after shifting,the value is assigned back to x. Am i right?
Chitra Jay
Ranch Hand
Joined: May 02, 2002
Posts: 76
posted
0
Can anybody please explain this with an example?
Corey McGlone
Ranch Hand
Joined: Dec 20, 2001
Posts: 3271
posted
0
Originally posted by Chitra Jay: Can anybody please explain this with an example?
Just write a program, compile it, and execute it. That will tell you what happens. Try this:
What's the result? If you don't understand why you get the results that you get, please ask. Corey
Don't know what else you're looking for. Would this help?
Junilu
Chitra Jay
Ranch Hand
Joined: May 02, 2002
Posts: 76
posted
0
Oops!! Forgot the concept that the value of the left-hand operand is NOT affected by the shift operator ,whereas in the second case,x gets the new value due to extended assignment..Yeah I got it!! Thanks a lot for your examples..