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

  • Work with all your cloud files (Drive, Dropbox, and Slack and Gmail attachments) and documents (Google Docs, Sheets, and Notion) in one place. Try Dokkio (from the makers of PBworks) for free. Now available on the web, Mac, Windows, and as a Chrome extension!

View
 

MacroTips

Page history last edited by Kenneth Finnegan 13 years, 8 months 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.