Main Content

MISRA C:2023 Rule 8.17

At most one explicit alignment specifier should appear in an object declaration

Since R2024a

Description

Rule Definition

At most one explicit alignment specifier should appear in an object declaration.

Rationale

If you intend to specify an alignment specification in a declaration, using multiple alignment specifiers might obscure your intent and make the code more difficult to parse and review.

When you specify multiple alignment specifier in the same declaration, the strictest requirement is applied to the object. For example, in this code snippet, the variable varWithTwoAlign is declared with two alignment specifiers but is aligned to the boundary required for the strictest alignment, which is a double on most platforms.

_Alignas(float) _Alignas(double) int varWithTwoAlign; //Noncompliant
If you intend to specify different alignments based on a condition, abstract the conditional value of the alignment separately, for instance, in preprocessor directives.

For example, in this code snippet, the alignment of conditionalAlignVar has a value of 4 when environment variable IS_TARGET is defined, and an alignment of 16 otherwise.

#ifdef IS_TARGET  
    #define ALIGN_SPEC 4
#else
    #define ALIGN_SPEC 16 
#endif

#define ALIGNAS_PLATFORM(expr) _Alignas(expr)

void func() {
    ALIGNAS_PLATFORM(ALIGN_SPEC) int conditionalAlignVar;  
    
    //...
}

Polyspace Implementation

The coding rule checker reports a violation of this rule for any declaration that contains multiple alignment specifiers, even if they specify the same alignment.

Troubleshooting

If you expect a rule violation but do not see it, refer to Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <stdint.h>

int16_t varNoAlign;
_Alignas (4) int16_t var_align;
_Alignas (4) _Alignas(0) int16_t var_different_align; //Noncompliant
_Alignas (8) _Alignas(8) int16_t var_same_align; //Noncompliant

In this example, Polyspace reports the declarations of var_different_align and var_same_align as noncompliant with the coding rule because these declarations contain two alignment specifiers each. In the case var_same_align, Polyspace considers that the declaration is not compliant with the rule even if the same alignment is specified twice.

Check Information

Group: Declarations and definitions
Category: Advisory
AGC Category: Advisory

Version History

Introduced in R2024a