Alternatives to #define
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++!
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
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
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.
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.
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".
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement