| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • You already know Dokkio is an AI-powered assistant to organize & manage your digital files & messages. Very soon, Dokkio will support Outlook as well as One Drive. Check it out today!

View
 

MacroTips

Page history last edited by Kenneth Finnegan 16 years ago

Here's a list of things to watch out for when using macros.

 


Don't use increment (++) or decrement (--) operators in macros

#define CUBE(i) (i * i * i)

CUBE(2++) evaluates to (2 * 3 * 4)

Solution:

Instead, use an inline function to protect yourself from misusing the macro:

inline int cube(int i) {

  return i * i * i;

}


Watch out for scope of variables used in macros

#define BUMP (count++)

int count;

 

main() {

     int count = 0;

     BUMP;

}

This increases the count variable in main's scope instead of the global count variable.  You should never use the same variable name in subscopes, they're confusing.

Solution:

Use an inline funtion to protect itself from the scope of the calling function.

inline void BUMP() {

     count++;

}


Use parentheses around macro parameters

You'll never know what people will pass to your macro, so you need to make sure order of operations don't cause unexpected results

#define CUBE(i) (i * i * i)

CUBE(2+1) -> (2 + 1 * 2 + 1 * 2 + 1) = 7

Solution:

#define CUBE(i)   ((i) * (i) * (i))


 

 


Sources:

https://www.securecoding.cert.org/confluence/display/seccode/PRE00-A.+Prefer+inline+functions+to+macros

https://www.securecoding.cert.org/confluence/display/seccode/PRE01-A.+Use+parentheses+within+macros+around+parameter+names

Comments (0)

You don't have permission to comment on this page.