Wednesday, 1 May 2013

Defined constants

Defined constants (#define)
You can define your own names for constants that you use very often without having to resort to memoryconsuming
variables, simply by using the #define preprocessor directive. Its format is:
#define identifier value
For example:
#define PI 3.14159
#define NEWLINE '\n'
This defines two new constants: PI and NEWLINE. Once they are defined, you can use them in the rest of the code
as if they were any other regular constant, for example:
// defined constants: calculate circumference            31.4159
#include <iostream>
using namespace std;
#define PI 3.14159
#define NEWLINE '\n'
int main ()
{
double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0;
}

In fact the only thing that the compiler preprocessor does when it encounters #define directives is to literally
replace any occurrence of their identifier (in the previous example, these were PI and NEWLINE) by the code to
which they have been defined (3.14159 and '\n' respectively).
The #define directive is not a C++ statement but a directive for the preprocessor; therefore it assumes the entire
line as the directive and does not require a semicolon (;) at its end. If you append a semicolon character (;) at the
end, it will also be appended in all occurrences within the body of the program that the preprocessor replaces.
Declared constants (const)
With the const prefix you can declare constants with a specific type in the same way as you would do with a
variable:
const int pathwidth = 100;
const char tabulator = '\t';
Here, pathwidth and tabulator are two typed constants. They are treated just like regular variables except that
their values cannot be modified after their definition.

No comments:

Post a Comment