C++ gurus and learners, we program ourselves :P all work is CC licensed

Friday, November 8

Macros In C++ By Umair Sajid

Macros In C++ By Umair Sajid

Macros : are pre-processor directives Just As

                                #include<stdio.h>
             #include<graphic

             #include<conio.h>
             #include<malloc.h>
             #include<stdlib.h>
             #include<dos.h>
             #include<iostream> 


but In Above Directive Directs The Compiler to include followings library functions . However We Are Concern with the Macros.

Syntax:               #define ADD x+y

  Actually They Can Be think As Same As Functions But Just Defined Before Main and with A little difference of Syntax and working. In a Nutshell  You can Call Macros as Functions Using As A Variable

Use: Macros In C++ Is Usually Used Where We Required Fast Execution. However The Same Work Can be Done By Using Functions But The Function can pass arguments and require a return_type of the Integers or Result Return.

Lets Come To A Simple Program That prompt the user to enter a number and prints its cube and square using macros.

#include<iostream>
#define SQUARE num*num      // MACROS
#define CUBE num*num*num    // MACROS
using namespace std;
int main()
{
    int num;
    cout<<"\n\t\tEnter A Number : "; // prompt to enter a number
    cin>>num;               // store it in num

    cout<<"\n\t\tThe Square of "<<num<<" is : "<<SQUARE<<"\n";   // Just as function call we have used
    cout<<"\n\t\tThe Cube of "<<num<<" is :"<<CUBE;                     // macros
    cout<<"\n\n";
    cout<<"\n\t\t***THANKYOU PC Umair Sajid ****\n\n";
}

hi my name is umar