Macros in C
Macros is a preprocessor in C. It is used for simple textual replacements in C. The following is the simplest macros example in C.
Now, in the program all the MAX will be replaced by the value 50 during compilation. This is only the most basic usage of macros. More complex usages are also there for macros. All of them does the same purpose of textual replacement.
The macros in certain cases work like a function. But actually it is quite different from functions. In certain cases it is more useful than functions.
This macro definition will replace any occurrence of, for example, SQR(4) by 4*4. There is a simple problem present in this situation, If we use 4 + 1 instead of 4 we get the answer 9 because * have higher precedence than +. Therefore we must use braces.
How it is useful than functions? In functions there is overhead due to call and return. During a function call the state and variables are needed to be pushed to the stack. This takes time. Macros is a single textual replacements and hence the SQR function will be done in a single line execution.
Another big difference is macros parameters are not predefined. C language is a statically typed language. All types are to be predefined. macros is the only variation. This make the code little more flexible. In the function declaration the type is to be listed. This makes the functions less flexible.
x and y can be integers or strings etc. We can pass the type as a parameter. Thus if we use the type as integer x and y becomes integers. This flexibility is not available in function.
But along with this benefits there comes many problems. The coding must be done with excessive care, otherwise unexpected could arise. In the above examples two problems could rise:
1) There may be a local ‘t’ or
2) If swap is called after execution of some statements, the replacement could give rise to an error. This is because there is a declaration inside the macro, type t. In C, every declarations must be done first.
The solution of this problem is the usage of another feature of C, block structure. We can make the macro a new block using the curly braces.
The replacement during compilation will introduce a needless ‘;’ at the end of braces. It will not create problem until it comes after an if statement.
To avoid this problem, there is a simple solution, just avoid the ‘;’ after the function. But it is not a good engineering practice. It will affect the consistency we are following. For very large programs we will get confused when to use semicolons and when not.
To handle this situation we use the least used ‘do while’ loop.
The ‘;’ now become the part of ‘do while’ syntax.
We are not breaking consistency of our mental model. There is no effect in using the ‘do while’ loop. The condition checked is false. Since it a ‘do while’ loop, the loop body will be executed atleast once. This is what we want.