-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Macros and Enums
Names of macros
defining constants and labels in enums
are capitalized.
#define CONSTANT 0x12345
and
enum sample
{
FIRST = 1,
SECOND,
THIRD
};
Enums are preferred when defining several related constants.
CAPITALIZED macro names are appreciated but macros resembling functions may be named in lower case.
Generally, inline functions
are preferable to macros resembling functions.
Macros with multiple statements should be enclosed in a do - while
block:
#define macrofun(a, b, c) \
do \
{ \
if (a == 5) \
do_this(b, c); \
} while (condition)
#define FOO(x) \
do \
{ \
if (bar(x) < 0) \
return (-1); \
} while (condition)
This is a very bad idea.
It looks like a function call but exits the calling
function; don't break the internal parsers of those who will read the code.
#define FOO(val) bar(index, val)
might look like a good thing, but it's confusing as hell when one reads the code and it's prone to breakage from seemingly innocent changes.
3) Forgetting about precedence: macros defining constants using expressions must enclose the expression in parentheses. Beware of similar issues with macros using parameters.
#define CONSTANT 0x4000
#define CONSTEXP (CONSTANT | 3)
#define FOO(x) \
({ \
typeof(x) ret; \
ret = calc_ret(x); \
(ret); \
})
ret
is a common name for a local variable. __foo_ret
is less likely to collide with an existing variable.
0.1 - Betty-style usage
0.2 - Betty-doc usage
0.3 - References
1.1 - Indentation
1.2 - Breaking long lines and strings
1.3 - Placing Braces
1.4 - Placing Spaces
1.5 - Naming
1.6 - Functions
1.7 - Commenting
1.8 - Macros and Enums
1.9 - Header files
2.1 - Functions
2.2 - Data structures
3.1 - Emacs
3.2 - Vim
3.3 - Atom