Jump to content
  • Advertisement
Sign in to follow this  
Floating

Alternatives to #define

This topic is 4887 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

Hi, Is there a nice alternatice for a define in following case: #define a (12.36f) #define b (14.21f) #define c (a*b) I want to use c, but I don't want the product a*b to be calculated everytime I use c. I'd like c to be calculated during compilation. Thanks EDIT: I forgot to specify that the language is c and not c++!

Share this post


Link to post
Share on other sites
Advertisement
then use:

const float a=12.36f;
const float b=14.21f;
const float c=a*b;

Beside this ... I think that the compiler would optimize this static calculation anyway by precalculating it.

See the base order is this:

PreProcessor insert all macros and defines and that stuff
Paser make it into Tokens the Compiler can use
Generate inter code
Optimize the inter code
Generate the final code

So don't worry about that kind of stuff.
Get it running, and when you find that in the end it's to slow,
1. find the slowest part
2. optimize that
3. if still to slow, go to 1

Share this post


Link to post
Share on other sites
Unfortunatley C doesn't supply templates or inline functions etc so #define's are the way to go to process variables of different types, in some cases, or where efficiency is an issue.

With your example though I'm a little confused as to the context?

Why not just multiply a & b explicitly in the code? c = a*b; As long as c is a float/double you won't lose any precision.

Share this post


Link to post
Share on other sites
Quote:
Original post by Floating
Hi,

Is there a nice alternatice for a define in following case:

#define a (12.36f)
#define b (14.21f)
#define c (a*b)

I want to use c, but I don't want the product a*b to be calculated everytime I use c. I'd like c to be calculated during compilation.

Thanks

EDIT: I forgot to specify that the language is c and not c++!


Even with #defines (although modern C supports const values, you'll be stuck with #defines on older compilers), the calculation will almost certainly be done during compilation anyway, even on aforementioned older compilers (compiling to an older language specification) - because it's a very easy optimization to do (relatively speaking) : [google] "constant folding".

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!