Ono
Ono

Reputation: 1357

Does VS2010 pre-calculate preprocessor defined by #define?

For Visual Studio 2010, if I define

#define PI 4.0f*atan(1.0f)

when PI is used somewhere later in the code, does the value needs to be calculate again or simply 3.1415926... being plugged in? Thanks.

EDIT:

Because I heard someone says the compiler might optimize to replace it with 3.1415926.., depending on the compiler.

Upvotes: 0

Views: 123

Answers (3)

NathanOliver
NathanOliver

Reputation: 180990

the #define will do a direct text replacement. Because of that everywhere you have PI it will get replaced with 4.0f*atan(1.0f). I would suspect the compiler would optimize this away during code generation but the only real way to know is to compile it and check the assembly.

I found this little online tool that will take c++ code and generate the assembly output. If you turn on optimizations you will see that the code generated to display PI is gone and it is now just a constant that gets referenced.

Upvotes: 3

Mooing Duck
Mooing Duck

Reputation: 66961

#define is a "copy-paste" type of thing. If your code says std::cout << PI; then the compiler pretends you typed std::cout << 4.0f*atan(1.0f);.

The values of defines are not calculated until they're used, and they're theoretically recalculated every time they're used. However, most modern compilers will see std::cout << 4.0f*atan(1.0f); and do that calculation at compile time and will emit assembly for std::cout << 3.14159265f;, so the code is just as fast as if it were precalculated.

Unrelated, #include is also a copy-paste kind of thing, which is why we need include guards.

Upvotes: 3

lcs
lcs

Reputation: 4245

When the preprocessor runs it will replace every instance of PI with 4.0*atan(1.0f).

Upvotes: 0

Related Questions