Tuesday 29 November 2011

Macros

What is a macro ?
A macro is a piece of code that was labeled with a name. Whenever the preprocessor encounters it, the label is replaced by the associated code. Basically there are two kinds of macros : object-like macros (resemble data objects when used) and function-like macros (resemble function calls).

Example for object-like macros:

#include <stdio.h>
#define HELLO "Hello World Macro!"
int main(){
printf(HELLO);
return 0;
}
In the above example the label is HELLO and the associated data is “Hello World Macro!“ . Before compile-time the preprocessor will replace the label with the associated code. I think the results are pretty obvious.

Example for function-like macros:

#include <stdio.h>

#define MAX(a, b) ((a) > (b)) ? (a) : (b)

int main(){
printf("%dn", MAX(1,3));
return 0;
}
In the case above MAX works exactly as a function that receives two arguments a, b and returns the maximum of the two . Note that the arguments are generic and appear to be typeless, the preprocessor is not performing any validation on types (that’s the compiler job) – this an advantage and also a disadvantage.

No comments:

Post a Comment