What are the differences between
int size = (int)((length * 200L) / 100L); // (1)
and
int size = length << 1; // (2)
(length is int in both cases)
I assume both code snippets want to double the length parameter.
I’d be tempted to use (2) … so are there any advantages for using (1)? I looked at the edge cases when overflow occurs, and both versions seem to have the same behavior.
Please tell me what am I missing.
And here is the 3rd option:
And this must be the best option. As it is readable and easy to understand what you want to do.
As for performance, compilers are generating pretty optimized code, so no need to worry for such a simple operation.
If you have any concerns concerning overflow you can use
checkedblock.EDIT As mentioned by many others just use any meaningful variable instead of
2here.