Preprocessor Directive :

#define

Preprocessor commands are called DIRECTIVES, and begin with a pound / hash symbol(#).

Example :

  1. /* Description: Area of circle use define in C++ language */
  2. #include<iostream>
  3. #define PI 3.14159
  4. using namespace std;
  5. int main()
  6. {
  7. int r=10;
  8. float cir;
  9. cir=PI*(r*r);
  10. cout<< "Area of circle: " <<cir <<endl;
  11. }

Output :

C++ language Area of circle use define

Note : No white space should appear before the #, and a semi colon is NOT required at the end. The #define preprocessor allows us to define symbolic names and constants :

#define PI

This statement will translate every occurrence of PI in the program (Example: #define PI 3.14159 ).

#define MAX

Before compilation, if the C++ preprocessor finds the MAX as one word, in the source code, it replace the number (Example: #define MAX 70 ).

#define NAME

Every time the preprocessor sees NAME it will replace it(Example : #define NAME"Computer Science C++"). This feature is particularly use for defining 'magic' numbers. An advanced use of #define is in the creation of macros.


Structure with #define :

Some time Create a big structure program using #define is helping much so, lets make a simple structure program using #define MAX in C++ language.

Example :

  1. /* Description: simple structure program using define MAX in C++ language */
  2. #include<iostream>
  3. #define MAX 2
  4. using namespace std;
  5. struct data{
  6. char name[20];
  7. }info[4];
  8. int main()
  9. {
  10. int i;
  11. for(i=1;i<=MAX;i++)
  12. {
  13. cout<<"Enter name: ";
  14. cin>>info[i].name;
  15. }
  16. cout<<endl;
  17. for(i=1;i<=MAX;i++)
  18. {
  19. cout<<"Stored name: "<<info[i].name<<endl;
  20. }
  21. }

Output :

C++ language simple structure program using define MAX

Computer Science Engineering

Special Notes

It's a special area where you can find special questions and answers for CSE students or IT professionals. Also, In this section, we try to explain a topic in a very deep way.

CSE Notes