Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace last digits of an integer

Tags:

c

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?

like image 639
chappar Avatar asked Mar 09 '26 15:03

chappar


2 Answers

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.

like image 87
Artelius Avatar answered Mar 12 '26 05:03

Artelius


num = num - (num % 100) + 38;
like image 22
jason Avatar answered Mar 12 '26 05:03

jason



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!