tags:

views:

231

answers:

2

I am trying to replace last 2 digits of a integer with 38. I am doing that like below.

int num = 1297;
num = (num/100)*100 + 38;

What i am assuming is that compiler won't optimize (num/100)*100 to num. If that happens then in my above example, num will become 1335 instead of 1238. So, is it guaranteed in C that the above expression won't be optimized? Or is there any better way of replacing last 2 digits with some number?

+8  A: 
num = num - (num % 100) + 38;
Jason
If you want to shave another six characters off, you could even go with "num -= (num % 100) + 38;"
John Feminella
This post doesn't answer most of the OP's questions and doesn't explain how (or even if) it is better than the example the OP provided.
Artelius
Agree, while the code is technically correct, the answer is horrible from a pedagogical point of view. The current score of 10 is way too much, -1 from me.
hlovdal
+7  A: 

Optimisations are not supposed to affect the outcome of a program at all (apart from its code size and running time of course). When they do, it is usually because you are relying on undefined behaviour.

No sane compiler would replace (num/100)*100 with num. Optimising compilers are far, far, far smarter than that. The compiler might optimise it to num - (num % 100), if that is a sensible decision for the target platform.

I always say "the easier your code is for a compiler to understand, the easier it will be for the compiler to apply the most appropriate optimisation". And you know what? Usually code that is easy for a compiler to understand is also easier for humans to understand.

Artelius