Sunday, 19 January 2014

Defined constants (#define) in c++



Defined constants (#define)

You can define your ow.n names for constants that you use very often without having to resort to memory-consuming 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
 
#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;
}
31.4159
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.

No comments:

Post a Comment