Reputation: 15113
Simple question: When the compiler faces a call to, say, pow() with two constants (i.e. values from macros), is it optimized by evaluating it at compile time, or is it still calculated at run-time?
Example:
#define V_BITMEM_GRID 3
#define V_BITMEM_TOTAL pow(V_BITMEM_GRID,2)
Thanks!
EDIT If not, is there a way to calculate the square/cube of a macro as another macro (like I'm attempting above) at compile-time?
Upvotes: 0
Views: 511
Reputation: 3216
You shouldn't depend on it. A macro based approach is:
#define POW1(x) (x)
#define POW2(x) ((x)*(x))
#define POW3(x) (POW2(x)*POW1(x))
...
#define POW(x, y) POW##y(x)
Upvotes: 1
Reputation: 258618
It can be both. It depends on how intrusive the compiler is, whether it has access to the function implementation and can correctly evaluate it. There's no rule that specifies how it's supposed to be, as long as observed behavior is the same.
For example, I got the following:
#define X 1
#define Y 2
int foo(int x, int y)
{
return x + y;
}
int main(int argc, char* argv[])
{
cout << foo(X,Y);
00BE1000 mov ecx,dword ptr [__imp_std::cout (0BE203Ch)]
00BE1006 push 3
00BE1008 call dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (0BE2038h)]
}
The function, as you can see, isn't even called. So it is possible that the call is eliminated for good.
Upvotes: 2