15

Including some math in my code I stumbled over the constant "PI". At least in my Xcode version 4.6 I could use either one. But what is the difference between pi and M_PI? The documentation is little bit tight on that topic.

JFS
  • 2,992
  • 3
  • 37
  • 48
  • 1
    `pi` isn't a standard constant in Cocoa headers I have included, nor is `PI`. `M_PI` is the standard definition from math.h, and should be fine for most purposes. – Ben Zotto Mar 05 '13 at 18:40
  • 5
    @BenZotto: `M_PI` is a posix-ism, not part of the C standard. – Stephen Canon Mar 05 '13 at 18:51
  • @StephenCanon: Right. I meant "standard" as in "the one everyone uses". :) – Ben Zotto Mar 06 '13 at 02:50
  • M_PI is close enough to approximate the circumference of the galaxy (and probably the whole Universe) within a few miles, so I wouldn't lose sleep over it. – Laserbeak Jun 09 '17 at 21:58

1 Answers1

30

pi is defined in the "CarbonCore.framework" headers as

extern const double_t pi  __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_10_0, __MAC_10_8, __IPHONE_NA, __IPHONE_NA);

but marked as "deprecated". I assume that it is a relict from older Carbon frameworks.

M_PI is defined as a macro

#define M_PI   3.14159265358979323846264338327950288

in math.h and part of the POSIX standard.

The values are identical, but you should use M_PI for portability reasons.

(And for Swift, see How to get mathemical PI constant in Swift)

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 1
    Thanks for the answer and WOW! That is good to know to not use `pi` (I always did so far). Can I straight include `M_PI` in my code or do I need to `#import...` a special class as well. – JFS Mar 05 '13 at 19:06
  • 2
    If you already import the Foundation or CoreFoundation headers then you can just use it, because these include ``. Otherwise you have to add `#include ` to your code. – Martin R Mar 05 '13 at 19:13