C_Preprocessor
C_Preprocessor
return 0; 0
} 1
2
3
4
Macro with Arguments
// C Program to illustrate function like macros
#include <stdio.h>
int main()
{ Area of rectangle is: 50
int l1 = 10, l2 = 5, area;
return 0;
}
Nesting of Macros
#include<stdio.h>
void main()
{
int A = 8, B= 6, C = 4;
printf("The area of square= %d\n", Area(A));
printf("Cost of paint= %d\n", Costpaint(A,B,C));
}
Problem with Macros (1)
#include <stdio.h>
#define MULTIPLY(a, b) a* b
int main()
{
// The macro is expanded as 2 + 3 * 3 + 5, not as 5*8
printf("%d", MULTIPLY(2 + 3, 3 + 5));
return 0; #include <stdio.h>
}
// Output: 16 // here, instead of writing a*a we write (a)*(b)
#define MULTIPLY(a, b) (a) * (b)
int main()
{
// The macro is expanded as (2 + 3) * (3 + 5), as
5*8
printf("%d", MULTIPLY(2 + 3, 3 + 5));
return 0;
}
Problem with Macros (2)
#include <stdio.h>
#define square(x) x* x
int main()
{ #include <stdio.h>
// Expanded as 36/6*6
int x = 36 / square(6); #define square(x) (x * x)
printf("%d", x);
return 0; int main()
} {
// Expanded as 36/(6*6)
int x = 36 / square(6);
printf("%d", x);
return 0;
}
Macro Vs. Function
Conditional Compilation (1)
• #ifdef macro_name
• // Code to be executed if macro_name is defined
• #ifndef macro_name
• // Code to be executed if macro_name is not defined
• #if constant_expr
• // Code to be executed if constant_expression is true
• #elif another_constant_expr
• // Code to be excuted if another_constant_expression is true
• #else
• // Code to be excuted if none of the above conditions are true
• #endif
Conditional Compilation (2)
PI is defined
Square is not defined
#undef Directive