Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using M_PI with C89 standard

Tags:

c

math

c89

I'm using C and trying to get access to the constant M_PI (3.14159...). I have imported the math.h header file, but the M_PI constant was still undefined. Through some searching on StackOverflow I have found that I need to add #define _USE_MATH_DEFINES to my code (see example code below). This works fine when compiling normally, but I need to be able to compile with the std=c89 flag for the work that I'm doing.

How should I access M_PI from some C89 code?

like image 536
robintw Avatar asked Feb 15 '11 18:02

robintw


People also ask

What does M_PI mean in C++?

M_PI. Pi, the ratio of a circle's circumference to its diameter. M_PI_2.

Is Pi included in Cmath?

The PI constant is present in the cmath header file. The name of the constant is M_PI.

Can you use PI in C++?

Standard C++ doesn't have a constant for PI. Many C++ compilers define M_PI in cmath (or in math. h for C) as a non-standard extension. You may have to #define _USE_MATH_DEFINES before you can see it.


1 Answers

A conforming standard library file math.h is not only not required to, but actually must not define M_PI by default. In this context 'by default' means that M_PI must only get defined through compiler-specific tricks, most often undefined behavior through the use of reserved identifiers.

Just define the constant yourself (you can use the name M_PI freely, but should you want to be able to compile the code with a non-conforming compiler, you must first check that M_PI is not already defined). For convention's sake, do not define M_PI as anything other than (the approximation of) pi.

like image 131
eq- Avatar answered Sep 20 '22 16:09

eq-