2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02: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.
Using a macro to define a type is inferior to the previous ways for two reasons:
2023-10-02 15:54:17 +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.
* macros are handled by the preprocessor and are not understood by 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.
2021-04-28 16:49:39 +02:00
2023-10-02 15:54:17 +02:00
As a result, macros should not be used as a replacement for ``++typedef++`` or ``++using++``.
2021-04-28 16:49:39 +02:00
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,cpp]
2021-04-28 16:49:39 +02:00
----
#define UINT unsigned int // Noncompliant
#define INT int // Noncompliant
UINT uabs( INT i );
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,cpp]
2021-04-28 16:49:39 +02:00
----
typedef unsigned int UINT;
typedef int INT;
UINT uabs( INT i );
----
or
2022-02-04 17:28:24 +01:00
[source,cpp]
2021-04-28 16:49:39 +02:00
----
using UINT = unsigned int;
using INT = int;
UINT uabs( INT i );
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
== Resources
2021-04-28 16:49:39 +02:00
2023-10-02 15:54:17 +02:00
=== Documentation
* {cpp} reference - https://en.cppreference.com/w/cpp/language/typedef[typedef specifier]
* {cpp} reference - https://en.cppreference.com/w/cpp/language/type_alias[Type alias, alias template]
=== Standards
* CERT - https://wiki.sei.cmu.edu/confluence/display/c/PRE03-C.+Prefer+typedefs+to+defines+for+encoding+non-pointer+types[PRE03-C. Prefer typedefs to defines for encoding non-pointer types]
2021-04-28 18:08:03 +02:00