codescracker


c++

C++ #define



« Previous Tutorial Next Tutorial »


Preprocessor commands are called DIRECTIVES, and begin with a pound or hash symbol (#). No white space should appear before the #, and semi colon is NOT required at the end.

Many things that can be done during preprocessing phase include :

Through some preprocessor directives you can also conditionally compile or execute some preprocessor directives.

Note - The preprocessing phase of a C++ program occurs before a program is compiled. The C++ preprocessor is a program that is executed before the source code is compiled.

You have already learnt to work with #include preprocessor directive that lets you include desired header files in your program. This discussion or ours is dedicated to #define preprocessor directive.

The #define preprocessor allows us to define symbolic names and constants. For example,

#define PI 3.14159

This statement will translate every occurrence of PI in the program to 3.14159.

C++ #define Example

Now consider the complete example wherein every occurrence of PI will replace with the value 3.14159, the value defined with #define directive.

/* C++ #define - Example Program of #define */

#include<iostream.h>
#include<conio.h>

#define PI 3.14159

void main()
{
	clrscr();

	int r = 10;
	float cir;
	cir = PI * (r * r);
	cout<<"Area of Circle: "<<cir<<endl;

	getch();
}

Here is the sample output of the above C++ program:

c++ #define

#define allows you to make text substitutions before compiling the program. Here's an example :

#define MAX 70

Before compilation, if the C++ preprocessor finds MAX as one word (so words like MAXIMUM will not be affected), in the source code, it replaces it with the number 70. If MAX was part of a string (for example, between quote marks of cout), the preprocessor will leave it alone.

You can call the MACRO DEFINITION anything you want, as long as it doesn't contain special characters or spaces and it cannot start with a number. I tend to use upper-case and underscore characters. You can define strings as well:

#define NAME "Computer Science C++"

Every time the preprocessor sees NAME it will replace it with "Computer Science C++"

This feature is particularly useful for defining 'magic' numbers. An advanced use of #define is in the creation of macros. To learn more about preprocessor, refer C++ Preprocessors.


« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test