Open In App

Output of C++ programs | Set 25 (Macros)

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite – Macros 
 

  • What is the output of following program? 

CPP




#include <iostream>
using namespace std;
  
#define a 10
  
int main()
{
    int a = 5;
    cout << "macro variable value: "<< a;
    return 1;
}


Output: 
Error 

  • Description: Compiler can not resolve the scope and thus it does’nt know which value to print, thus error. 
     
  • What is the output of following program? 

CPP




#include <iostream>
using namespace std;
  
#define area length * width
  
int main()
{
    int length = 10, width = 20;
    cout << "macro expression area: " << area;
    return 1;
}


Output: 

macro expression area: 200
  • Description: Unlike first question, here value in the program need to be replaced in macro. As soon as the control comes to “area” it is replaced with the macro code i.e., 
 cout<< "macro expression area: " << length * width;

an then the values of length and width are substituted and computed. 
 

  • What is the output of following program? 

CPP




#include<iostream>
using namespace std;
  
#define sqrt(x) (x*x)
  
int main()
{
    int a = 3, b;
    b = sqrt(a + 5);
    cout<< "Output of b = " << b;
}


Output: 

Output of b =  23
  • Description: Yes its not sqrt(8) BUT sqrt(a + 5); will be replaced as (a + 5*a + 5); resulting as 23 for it to be perfect the macro command should be replaced as 
     
 #define sqrt(x) ( (x) * (x) )
  • What is the output of following program? 

CPP




#include <iostream>
using namespace std;
  
#define printf(s) cout << s;
  
int main()
{
    printf("GeeksforGeeks");
    cout << "\nBye Bye";
}


Output:

GeeksforGeeks
Bye Bye
  • Description: printf is supported by the c++ compiler so, it will not throw any error. Macro works even for the keywords and any kind of statements like printf. When the control comes to printf it will throw the arguments just like the function calls since, it is already defined. 
     
  • What is the output of following program? 
     

CPP




#include <iostream>
using namespace std;
  
#define SQRT(x) ( x * x)
  
int main()
{
    int a,  b= 3;
    a = SQRT(b++);
    cout << a << endl << b;
    return 0;
}


Output: 

12
5
  • Description: a = SQRT(b++); becomes a = b++ * b++; a = 3 * 4; Here we are using post-increment operator, so the 3 is incremented in the statement for each execution and also after the statement is executed. 
     

Quiz on Macros
This article is contributed by I.HARISH KUMAR.



Last Updated : 14 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads