6.7 Constants in C


6.7 Constants in C++

The following C++ program contains an empty main function, and therefore when the program is executed it ends almost as soon as it begins.

      int main()      {        return 0;      } 

Since it does very little, except terminate, it therefore requires very little memory. It is now time to fill this function with some code so something happens.

Here, our sample program will be instructed to create several constants. That is, when the program is executed it will create some constants in system memory. To create constants, a programmer must declare them using the const keyword. This declaration must tell the compiler the data type of the constant to be created (int, float, char, etc.) and provide a unique name so the constant can be identified if referenced in the program later. The name can be anything the programmer chooses except for a reserved word. Ideally, the name will be indicative of the data it represents, such as Age, Name, and Date, etc. In the following example, two constants will be of an integer data type, while others will be of the float, Boolean, and char types. Constants can be created in C++ as follows:

      const int Age = 27;      const int Friend_Age = Age;      const bool Is_Human = true;      const float Pi = 3.14;      const char Letter = 'a'; 
Note 

Notice how the value of constants can be assigned to other constants: const int Friend_Age = Age. Here, Friend_Age has the same value as Age, which is defined on the line above.




Introduction to Game Programming with C++
Introduction to Game Programming with C++ (Wordware Game Developers Library)
ISBN: 1598220322
EAN: 2147483647
Year: 2007
Pages: 225
Authors: Alan Thorn

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net