Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Macros are often used to generalize several segments of code which might be used multiple times in the code. This guideline focuses on macros consisting of single statements, which do not usually have to be enclosed in a do()....-while(). (See also PRE10-C. Wrap multi-statement macros in a do-while loop.)

...

Code Block
bgColor#FFCCCC
#define FOR_LOOP(n)  for(i=0; i<(n); i++);
main()
{
 	int i;
    	FOR_LOOP(3)
    	{
             printfputs("Inside for loop\n");
    	}
}

The user expects to get the following output from the code:

...

Code Block
bgColor#CCCCFF
#define FOR_LOOP(n)  for(i=0; i<(n); i++)
main()
{
 	int i;
    	FOR_LOOP(3)
    	{
        	printfputs("Inside for loop\n");
    	}
}

Noncompliant Code Example

In the this noncompliant code belowexample, the programmer defines a macro which increments the value in the argument 1 by one and modulates it with the max value provided by the user.

Code Block
bgColor#FFCCCC
#define INCREMENT(x, max)    ((x) = ((x) + 1) % (max));
main()
{
     int index = 0;
     int value;
     value = INCREMENT(index, 10) + 2;
    /* ...........
     ...........

}
*/

In this caseIn the above code, the programmer intends to increment index and then use that as a value by adding 2 to it. Unfortunately, the value will always be is equal to the incremented value of index because of the semicolon present at the end of the macro. The '+ 2;' will be is treated as another a separate statement by the compiler. The user will not get any compilation errors. If the user has not enabled warnings while compiling, the effect of the semicolon in the macro cannot be detected at an early stage.

...

Code Block
bgColor#CCCCFF
#define INCREMENT(x, max)    ((x) = ((x) + 1) % (max))
main()
{
     int index = 0;
     int value;
     value = INCREMENT(index, 10) + 2;
     .........
     ..........

}

Mitigation Strategies

The programmer should ensure that there is no semicolon at the end of a macro definition with single statement. The responsibility for having a semicolon where needed during the use of the macro should be given to the person using the macro.

...