Sep 8, 2012

[Macro][NOTE]

Macros
Variadic Macros
Tips on writing C macros

FIX:
Use ntohs(3) instead of ::ntohs(3).

The alternative fix

Add the following line after your includes:

#undef ntohs
Excerpt from "Tips on writing C macros"

RULE 1: Always write your multiline macros using this pattern:
    #define MYMACRO \
    do { \
       macro definition here \
    } while (0)
The only trouble you might get with this, is some smart-a$$ code analyzer screaming about a 'constant expression in do-while condition'. That's usually easy to turn off by adding some comment-directive to your macro definition. Just make sure you only use /*C-style comments*/ in macros ;-) RULE 2: Always surround macro arguments with parentheses inside the macro body.
    #define MYMACRO(a,b,c) \
    do { \
       (a) = (b) + (c); \
       (b) = (c)*2; \
    } while (0)
RULE 3: Keep your macros SHORT. Don't write 50-line macros, because when the time comes to chase down some bug you will soon find out that the only debugger that could step into macro definitions (SoftICE) is out of business. To the best of my knowledge, even WinDBG, the Windows kernel debugger, cannot step into macros. So, keep'em short. RULE 4: Be very careful when trying to use macros for speed optimizations (i.e. save a function call). I have seen even senior programmers get it wrong, because they didn't realize that passing MyArray[x+3] as a macro argument would lexically copy this expression in multiple locations in the macro expansion, causing the generated code to needlessly evaluate MyArray[x+3] again and again and again. Always have someone else, preferably more experienced than yourself, check these 'optimizations' with you.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.