Macros

Macros

You are aware of the term preprocessor directive. A very common preprocessor directive is “#include <stdio.h>”.

There are many types of preprocessor directives. Each begin with the # sign and can be placed anywhere in the program but most often places in the beginning of the program. Macro Expansion is one of the type of preprocessor directive.

Macro Expansion:

Look at the following program

Observe the highlighted line of code. This statement is macro definition.

During preprocessing the preprocessor replaces every occurrence of UPPER in the program with 25.

When we compile the program before the source code is passed to the compiler, it is examined by preprocessor for any macros. If any #define directive is hunted by the preprocessor then it scans the whole code for the macro templates. Wherever it finds any template, it replaces the template with its respective expansion. After this procedure the program is finally passed to the compiler.

  • It is customary in C language to use all capital letter for macros. This make it easy for the programmers to pick out all the macro templates when reading the program.
  • Macro definition never terminated with a semi colon (;)
  • Macro template and expansion have to be separated by a space or tab

Why use macros not variables?

  • To improve readability of the program
  • You would be able to make changes in the constant values easily
  • Using variables for constant values makes the program more difficult to understand.
  • Using variable for the same purpose will not be able to prevent the change in its value anywhere in the program.
  • Space between # and define is optional

You can also use this directive for logical operators like

#include AND &&

# include OR ||

Now, wherever in the program we need to perform AND or OR operation we can write them as;

x>10 OR y<10

x>10 AND y<20

Macros used as conditions:

Macro expansion can also be used to define conditions. Like;

Now imagine the ease that you can get by using macros.

Macros as Statements:

Macros can also be used for C statements. If there is any statement that is frequently used in your code, you can always make a macro for that; following code demonstrates the same concept;

Macros with Arguments:

Macros used so far are the simple ones. Macros can also work with arguments just as functions. Look at the example below;

In this code;

  • The macro “Area” is taking one argument, calculating area of the circle and then returning the calculated area.
  • Here that macro is used two times in the code, you use macros multiple times.