...
This noncompliant code example creates a macro definition for a for
loop in the program. for
loops should require braces, even if it contains only a single body statement. (See recommendation EXP19-C. Use braces for the body of an if, for, or while statement.) This macro takes an integer argument, which is the number of times the loop should run. The programmer has provided a semicolon at the end of the macro definition by mistake.
Code Block | ||||
---|---|---|---|---|
| ||||
#define FOR_LOOP(n) for(i=0; i<(n); i++); int i; FOR_LOOP(3) { puts("Inside for loop\n"); } |
...
The compliant solution is to write the macro definition without the semicolon at the end, leaving the decision to have a semicolon or not up to the person who is using the macro.
Code Block | ||||
---|---|---|---|---|
| ||||
#define FOR_LOOP(n) for(i=0; i<(n); i++) int i; FOR_LOOP(3) { puts("Inside for loop\n"); } |
...
In this noncompliant code example, the programmer defines a macro which increments the value of the first argument x
by one and modulates it with the value of the 2nd argument max
.
Code Block | ||||
---|---|---|---|---|
| ||||
#define INCREMENT(x, max) ((x) = ((x) + 1) % (max)); int index = 0; int value; value = INCREMENT(index, 10) + 2; /* ...*/ |
...
The compliant solution is to write the macro definition without the semicolon at the end, leaving the decision to have a semicolon or not up to the person who is using the macro.
Code Block | ||||
---|---|---|---|---|
| ||||
#define INCREMENT(x, max) ((x) = ((x) + 1) % (max)) |
...