Defining value of PI

2019-07-25 15:04发布

问题:

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!

回答1:

#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...



回答2:

How about:

const double PI = 3.1415926535897932384626433832795028841971693993751058209;

This seems to me to be cleaner, easier to read, and more efficient than atan(1.0)*4.



回答3:

You have mis-tagged the question. In C++ the following is well-defined and will compile:

#include <math.h>

const double PI = atan(1.0)*4;

But in C, initializers at file scope are not allowed to.

In C you'll either need to use a non-standard macro (such as M_PI in GCC), create your own appropriate macro or literal (Ned Batchelder has done the hard part for you), or initialize it in your own function at an appropriately early enough time.