Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-5825

Macros should not be used as replacement to "typdef" and "using"

    XMLWordPrintable

    Details

    • Default Severity:
      Minor
    • Impact:
      Low
    • Likelihood:
      Low
    • Default Quality Profiles:
      Sonar way, MISRA C++ 2008 recommended
    • Covered Languages:
      C, C++, Objective-C
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      15min
    • Analysis Scope:
      Main Sources, Test Sources
    • CERT:
      PRE03-C, PRE03-C.

      Description

      C provides a way of defining or aliasing a type through typedef. On top of it, C++ 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:

      • 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 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.

      As a result, macros should not be used as a replacement to typedef or using.

      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

      using UINT = unsigned int;
      using INT = int;
      UINT uabs( INT i );
      

      See

      • CERT, PRE03-C. - Prefer typedefs to defines for encoding non-pointer types

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              geoffray.adde Geoffray Adde
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: