rspec/rules/S960/cfamily/rule.adoc

47 lines
1.6 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
It is tempting to treat function-like macros as functions, but the two things work differently. For instance, the use of functions offers parameter type-checking, while the use of macros does not. Additionally, with macros, there is the potential for a macro to be evaluated multiple times. In general, functions offer a safer, more robust mechanism than function-like macros, and that safety usually outweighs the speed advantages offered by macros. Therefore functions should be used instead when possible.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
#define CUBE (X) ((X) * (X) * (X)) // Noncompliant
void func(void) {
int i = 2;
int a = CUBE(++i); // Noncompliant. Expands to: int a = ((++i) * (++i) * (++i))
// ...
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
inline int cube(int i) {
return i * i * i;
}
void func(void) {
int i = 2;
int a = cube(++i); // yields 27
// ...
}
----
2021-04-28 16:49:39 +02:00
== See
* MISRA C:2004, 19.7 - A function should be used in preference to a function-like macro.
* MISRA {cpp}:2008, 16-0-4 - Function-like macros shall not be defined.
* MISRA C:2012, Dir. 4.9 - A function should be used in preference to a function-like macro where they are interchangeable
* https://wiki.sei.cmu.edu/confluence/x/INcxBQ[CERT, PRE00-C.] - Prefer inline or static functions to function-like macros
* https://github.com/isocpp/CppCoreGuidelines/blob/036324/CppCoreGuidelines.md#es31-dont-use-macros-for-constants-or-functions[{cpp} Core Guidelines ES.31] - Don't use macros for constants or "functions"
ifdef::rspecator-view[]
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::rspecator-view[]