This blog is under construction

Wednesday, 23 May 2012

Macro Expansion in C

We can use symbolic names to identify constant values or expressions.  At the time of preprocessing these symbolic names will be replaced by the constant values or expressions.  User can see the preprocessed code of any C program using the below command.

%gcc   -E   <C file_name>

Macro expansion example in C:
Consider the following C program,
  #define NAME "Khan"
  #define BIG(num1, num2) ((num1 > num2) ? num1: num2)

  int main() {
        printf("My name is %s\n", NAME);
        printf("%d is bigger\n", BIG(10, 20));
        return 0;
  }

Here, NAME and BIG are two macros.  Let us do preprocessing for the above C program and check the output for the same.

  Output:
  jp@jp-VirtualBox:~/$ gcc -E pgm.c > output.txt
  jp@jp-VirtualBox:~/$ cat output.txt 
  # 1 "pgm.c"
  # 1 "<built-in>"
  # 1 "<command-line>"
  # 1 "pgm.c"

  int main() {
        printf("My name is %s\n", "Khan");
        printf("%d is bigger\n", ((10 > 20) ? 10: 20));
        return 0;
  }


From the above output, we could see that the macros NAME and BIG are replaced by their values or expressions.  This is called macro substitution or macro expansion.



No comments:

Post a Comment