Define with a formula

If I use this construct

#define RAD2DEG (180/PI)

The preprocessor:

  1. replaces at the compiling time the value 180/PI
  2. replaces at the compiling time the value calculated (57.295779513...)

In the first hypothesis I need to calculate every time the value, in the second not. I'm very interested hearing the facts.

The preprocessor simply does the text replacement.
The compiler may optimise to the single constant

I don't even know why the two constants aren't factored in the first place. That is, why not:

#define RAD2DEG 57.295779513 // 180.0 / PI

Even the first c compiler did compile time constant calculations. Heck, I even included it when I wrote an image-processing expression parser based on the C parser using lex and yacc. So, the compiler will substitute the text into the expression and then calculate any constant expressions available at compile-time. Heck, it might even throw in the constant 2 that is also probably in the expression.

When in doubt, you can check the assembly code.

econjack:
I don't even know why the two constants aren't factored in the first place. That is, why not:

#define RAD2DEG 57.295779513 // 180.0 / PI

But what if the value of π changes?

econjack:
I don't even know why the two constants aren't factored in the first place. That is, why not:

#define RAD2DEG 57.295779513 // 180.0 / PI

And what is the advantage of that? You have simply done the calculation the compiler would otherwise have done for you. The generated code will be EXACTLY the same in either case.

Regards,
Ray L.

The 180/pi is also clearer to the maintainer. I kind of agree with Kernigham and Plauger in "The Elements of Programming Style": "We refuse to count characters" This was discussing why they used quoted FORTRAN strings instead of Hollerith Strings, but the sentiment is the same. That is also why C will count the initializers in an array and set the size for you, computers are much better at counting than you are.

Why use a #define anyway? Why not just use a const?

KeithRB:
I kind of agree with Kernigham and Plauger in "The Elements of Programming Style": "We refuse to count characters" This was discussing why they used quoted FORTRAN strings instead of Hollerith Strings, but the sentiment is the same.

Hollerith strings have the huge advantage that you need not worry about control characters. (Think SQL injection and the like.) Unfortunately, though, there is also the huge disadvantage that humans can't be arsed to count. (Oh, I'm sure that we would learn to count, and count very well, if we were forced to; however, no one is forcing us to.)