#define: simple and parameterized macros

Chapter 8:Preprocessor And Complex Declarations

    #define: simple and parameterized macros

  • Simple macros

              It is a type of abbreviation. They are mostly used for defining manifest constants. Like giving names to numeric, character, and string values. Before use a macro, it must be defined explicitly with the #define directive.Syntax of a simple macro is as follows:

    #define identifier replacement-list


    #define STR_LEN 50
    #define TRUE 1
    #define FALSE 0
    #define PI 3.14159
    #define MEM_ERR “Error: not sufficient memory”

             Macro definitions take care at the position that it is written because the preprocessor reads the program in order.  So, if we give input to the C preprocessor as follows:

         foo = z;
         #define z 5
         bar = z;

    Generates output:

         foo = z;
         bar = 5;

    Advantages of a Simple macro:

              It makes programs easier to read, to modify.

              It helps to skip inconsistencies and typographical errors and provide control to conditional compilation.

              Accomplishing slight alterations to the syntax of C and renaming types is possible - #define float int

    Parameterized macros

              Parameterized macros can be used to create templates for frequently used parts of code. Frequently, they serve as simple functions. #define helps to define a macro and the #undefine helps to remove a macro definition. Syntax of a parameterized macro is as follows:

              #define identifier(parameterlist) replacement-list

              There should be no spaces between the identifier and the parameter list. There should be no spaces in the parameter list.


    #define getchar() getc(stdin)
    #define IS_EVEN(m) ((m)%2 == 0)
    #define max(a,b) (((a)>(b))?(a):(b))
    #define toupper(x) (('a'<=(x)&&(x) z="" x="" -="" a="" :="" br=""> #define print(y) printf("%d\n",y) print(c/d) /* becomes printf("%d\n",c/d); */

    Advantages of a parameterized macro:

              The compiled code will execute more quickly because the macro is substituted in line. No function calling overhead is wanted.

              The parameters of functions are typed but in macros they are not typed. So, they are generic. The max() macro given example will perform for floats and also for ints.

    Disadvantages of a parameterized macro:

              The compiled code will often be larger, mostly when macros are nested (e.g., max(a,max(b,max(c,d))) ) because each instance of the macro is expanded in line.

              A macro may calculate its arguments more than once, producing subtle faults and it is not achievable to have a pointer to a macro.

© 2015 by Learncertification All Rights Reserved. The certification names are the trademarks of their respective owners. Terms & Privacy Policy