Search code examples
c++compiler-errorspi

Defining value of PI


I am working on a new project and I am trying to write the cleanest, easiest to read and hopefully, most efficient, code I can.

I need to use PI but apparently it isn't defined in math.h. So I read about doing this:

const double PI = atan(1.0)*4

But I get this error:

A function call cannot appear in a constant-expression

Any ideas on why? How can I get PI as a constant?

Also, please, I am trying to learn as much as I can with this project, so it would be great if you could also explain why your answer would work. Thanks!


Solution

  • #include <math.h>
    
    const double PI = M_PI;
    

    You can't call a function for a global const double because the constant needs to be evaluated at compile time. At runtime atan() could be anything. You could arrange for it to be called once at startup, but using an actual PI constant that's already available is better.

    (actually using M_PI directly would also be good)

    EDIT: It took many comment upvotes and re-reading my own answer over a year later to see why people were up in arms about my statement about constants. I was jumping over a step: As everyone is saying you can initialize const double at runtime just as easily as double. However, if you are using a global variable (instead of a constant expression) to store pi you will defeat some optimization opportunities. Some experiments with gcc suggest this isn't even as bad as I thought, which suggests a whole new question...