This blog is under construction

Sunday, 3 June 2012

Parametrized macros in C

Macros with arguments are called parametrized macros.  Consider the following example,

#define AREA(r) (3.14 * r * r)

Here, AREA is a macro with parameter 'r'.  Macro AREA(r) would be expanded as 3.14 * r * r during preprocessing.

Parameterized macros example in C

  #include <stdio.h>
  #define AREA(r) (3.14 * r * r)
  #define GREATER(x,y) (x > y? x:y)
  #define ISDIGIT(x) (x >= 48 && x <=57)

  int main() {
        int a, b, ch;
        printf("1. Calculate area of circle\n");
        printf("2. Greatest of two numbers\n");
        printf("3. Given i/p is digit or not\n");
        printf("Enter the operation you wanna perform:");
        scanf("%d", &ch);

        switch(ch) {
                case 1:
                        printf("Enter radius:");
                        scanf("%d", &a);
                        printf("Area of circle:%d\n", (int)AREA(a));
                case 2:
                        printf("Enter two nos:");
                        scanf("%d%d", &a, &b);
                        printf("Greatest: %d\n", GREATER(a, b));
                case 3:
                        printf("Enter a value:");
                        scanf("%d", &a);
                        printf("Digit: %s\n", ISDIGIT(a)?"YES":"NO");
        return 0;

  jp@jp-VirtualBox:~/$ gcc paramacro.c
  jp@jp-VirtualBox:~/$ ./a.out
  1. Calculate area of circle
  2. Greatest of two numbers
  3. Given i/p is digit or not
  Enter the operation you wanna perform:3
  Enter a value:5
  Digit: NO

No comments:

Post a Comment