int y = 17*x;
int y = x + 16*x;
int y = x + (x<<4)
All are numerically equal to 17x , but is there is any difference between them in terms of execution or anything else ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The difference is this: 1) is readable, 2) is obscure and 3) is even more obscure.
Manual optimizations, replacing multiplication with bitwise-instructions, should not be needed on a modern compiler. It will most likely translate all 3 alternatives to the same machine code.
In case the compiler is bad and it does not translate them to the same machine code, then we can’t know which is the fastest, since it relies on how fast the underlying assembler instructions are for the specific CPU architecture. Traditionally, logical shift instructions are faster than multiplication instructions, but you can’t assume that this is true for all CPUs.