22
Constants

We have spent a lot of time discussing variables, which as the name indicates, change their values as the program runs. There are, however, pieces of information that do not change value. For example, the mathematical constant π never changes. We call these things constants, and there are two common ways that Objective-C programmers define constants: #define and global variables.

In Xcode, create a new Foundation Command Line Tool called Constants.

In the standard C libraries, constants are defined using the #define preprocessor directive. The math part of the standard C library is declared in the file math.h. One of the constants defined there is M_PI. Use it in main.m:

#​i​m​p​o​r​t​ ​<​F​o​u​n​d​a​t​i​o​n​/​F​o​u​n​d​a​t​i​o​n​.​h​>​

i​n​t​ ​m​a​i​n​ ​(​i​n​t​ ​a​r​g​c​,​ ​c​o​n​s​t​ ​c​h​a​r​ ​*​ ​a​r​g​v​[​]​)​
{​
 ​ ​ ​ ​@​a​u​t​o​r​e​l​e​a​s​e​p​o​o​l​ ​{​

 ​ ​ ​ ​ ​ ​ ​ ​/​/​ ​I​n​ ​l​i​t​e​r​a​l​ ​N​S​S​t​r​i​n​g​,​ ​u​s​e​ ​​u​ ​f​o​r​ ​a​r​b​i​t​r​a​r​y​ ​u​n​i​c​o​d​e​ ​c​h​a​r​s​
 ​ ​ ​ ​ ​ ​ ​ ​N​S​L​o​g​(​@​"​​u​0​3​c​0​ ​i​s​ ​%​f​"​,​ ​M​_​P​I​)​;​

 ​ ​ ​ ​}​
 ​ ​ ​ ​r​e​t​u​r​n​ ​0​;​
}​

When you build and run it, you should see:

π​ ​i​s​ ​3​.​1​4​1​5​9​3​

To see the definition, Command-click on M_PI in the editor. It will take you to the following line in math.h:

#​d​e​f​i​n​e​ ​M​_​P​I​ ​ ​ ​ ​ ​ ​ ​ ​3​.​1​4​1​5​9​2​6​5​3​5​8​9​7​9​3​2​3​8​4​6​2​6​4​3​3​8​3​2​7​9​5​0​2​8​8​

Preprocessor directives

Compiling a file of C, C++, or Objective-C code is done in two passes. First, the preprocessor runs through the file. The output from the preprocessor then goes into the real compiler. Preprocessor directives start with #, and the three most popular are #include, #import, and #define.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset