Macro Expansion

What is macro?

Let's understand macro using following program:

/*c program for macro expansion*/
#define LENGTH 3
#define WIDTH 2
int main()
 int r,c;
 for(r=1; r<=LENGTH; r++)
  for(c=1; c<=WIDTH; c++)
 return 0;

The output of above program would be:

Output of macro C program
Figure: Screen shot of macro C program

In above program, instead of writing 5 in the for loop we are writing it in the form of text as LENGTH and WIDTH, which have already been defined before main() through the statement.
#define LENGTH 3
#define WIDTH 2
This statement is called 'macro definition' or macro.
LENGTH and WIDTH in the above program are often called 'macro templates' , whereas 5 and 3 are called their corresponding 'macro expansions'.

What is reason of using macro in the program?

Macro makes the program easier to read.
For example: if the phrase "%ls[$2]!@" cause the screen to clear, but which would you find easier to understand in the middle of your program "%ls[$2]!@" or "CLRSCREEN"? 
#define CLRSCREEN "%ls[$2]!@"

Macro makes the easyness if we want to change the vale of constant in program. We can change value values of a constant at all the places in the program by just making a change in the #define directive.
This conversion may not matter for small programs shown above, but with large programs, macro definitions are almost indispensable.

Now you will be thinking, there are any similarity in macro and variable? Can i use variable as macro?
(i recommended, before you read next line, you should think about macro and variable properties.)

After thinking you will be find that we also use variable as macro. Then why not use it?

Why the variable is not using as macro because:
  1. Variable may inadvertently get altered somewhere in the program. so it's no longer a constant that you think it is.
  2. Variable is inefficient, since the compiler can generate faster and more compact code for constant than it can for variables.
  3. Using a variable for what is really a constant encourages sloppy thinking and makes the program more difficult to understand: if something never changes, it is hard to imagine it as a variable.

Related Article:
  1. General rules and example of macro

No comments:

Post a Comment