C and C++ Interview Questions |
5. What is the difference between function and macro?
Ans:
Macro:
e.g. :#define ref-name 99
The code is substituted by the MACRO ref-name. So no overhead.
Execution is faster. Where will it be stotred?(Is it in bss/stack/?)
Function:
There will be a overhead due to function arguments. (Aguments are
stored in the stack) |
Ex - 1:
#define AREA(x)(3.14*x*x)
main()
{float r1=6.25,r2=2.5,a;
a=AREA(r1);
printf("\n Area of the circle is %f", a);
a=AREA(r2);
printf("\n Area of the circle is %f", a);
}
What is the output?
Ans.
Area of the circle is 122.656250
Area of the circle is 19.625000
|
Ex - 2: What is the output?
#define one 0
#ifdef one
printf("one is defined ");
#ifndef one
printf("one is not defined ");
Ans: "one is defined"
|
Ex - 3: What is the output?
# define TRUE 0
some code
while(TRUE)
{
some code
}
Ans. This won't go into the loop as TRUE is defined as 0
|
Ex - 4: What are the output(s) for the following ?
#define MAN(x,y) (x)>(y)?(x):(y)
{int i=10;
j=5;
k=0;
k=MAX(i++,++j);
printf(%d %d %d %d,i,j,k);
}
Ans. 10 5 0
|