Sign in to follow this  

[C] Compile time constant conversion

This topic is 2540 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is it legal C89 to convert a constant at compile time as necessary to speed up an algorithm, such as:


float x = 12;



Is the compiler allowed to store 12 as a float, instead of an integer and converting it at runtime?

[Edited by - Ectara on December 29, 2010 3:50:46 PM]

Share this post


Link to post
Share on other sites
Of course. Depending on the level of optimisation you request, the optimiser may also do much, much more.

For instance, if all the values in an arithmetic expression are know at compile time, the compiler can precompute the result, rather than generating the code to compute it at runtime. This even works across small functions: if the function has no side-effects, and the values of all the arguments are known at compile time, the function call may be optimised away entirely.

This type of optimisation is usually disabled in debug mode though, because when debugging you want a fairly close relation between the original source code and the program's operation - otherwise it is very hard to follow what is going on.

There are however certain instances where the compiler is unable to optimise these things away (double -> float rounding is particularly troublesome under some conditions), so you would generally be better off explicitly providing a float constant, such as 12.f.

Share this post


Link to post
Share on other sites

This topic is 2540 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this