rspec/rules/S5825/rule.adoc

41 lines
1.2 KiB
Plaintext
Raw Normal View History

2021-01-27 13:42:22 +01:00
C provides a way of defining or aliasing a type through ``++typedef++``. On top of it, {cpp} adds ``++using++`` that can do the same and more.
2020-06-30 12:50:28 +02:00
2021-02-02 15:02:10 +01:00
2020-06-30 12:50:28 +02:00
Using a macro to define a type is inferior to the previous ways for two reasons:
2020-06-30 12:50:28 +02:00
* macros cannot be enclosed into scopes. Or at least, doing so is cumbersome and error-prone as in that case, the macro needs to be defined and undefined manually.
2021-01-27 13:42:22 +01:00
* macros are handled by the preprocessor and are not understood from the compiler. They can easily pollute the code in places where types are not expected. ``++typedef++`` and ``++using++`` are known to the compiler to define types and can be more strictly checked.
2020-06-30 12:50:28 +02:00
2021-01-27 13:42:22 +01:00
As a result, macros should not be used as a replacement to ``++typedef++`` or ``++using++``.
2020-06-30 12:50:28 +02:00
== Noncompliant Code Example
----
#define UINT unsigned int // Noncompliant
#define INT int // Noncompliant
UINT uabs( INT i );
----
== Compliant Solution
----
typedef unsigned int UINT;
typedef int INT;
UINT uabs( INT i );
----
or
2020-06-30 12:50:28 +02:00
----
using UINT = unsigned int;
using INT = int;
UINT uabs( INT i );
----
== See
* https://wiki.sei.cmu.edu/confluence/display/c/PRE03-C.+Prefer+typedefs+to+defines+for+encoding+non-pointer+types[CERT, PRE03-C.] - Prefer typedefs to defines for encoding non-pointer types