Main Content

MISRA C:2012 Rule 8.16

The alignment specification of zero should not appear in an object declaration

Since R2024a

Description

Rule Definition

The alignment specification of zero should not appear in an object declaration.

This rule comes from MISRA C™: 2012 Amendment 3.

Rationale

If the operand expr of _Alignas(expr) type var evaluates to zero, the specifier has no effect on the alignment of the object var.

If it is your intent to specify the alignment of an object, specify a non-zero value for the operand of _Alignas. If you intend to disable the alignment specification based on a condition such as platform implementation details, use preprocessor directives to abstract this requirement.

For example, this code snippet illustrates how to specify an alignment on a Linux platform but disable the alignment specification on other platforms.

#ifdef __linux__  
    #define ALIGN_SPEC 16
#else
    #define ALIGN_SPEC 0  
#endif

#define ALIGNAS_PLATFORM(expr) _Alignas(expr)

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

Polyspace Implementation

The coding rule checkers reports a violation on when you use _Alignas(0) in a variable declaration.

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>

struct {
    int32_t varNoAlign;
    _Alignas(16) int32_t varAlign;
    _Alignas(0) int32_t varNoAlignZero; //Noncompliant.
} data;

In this example, the structure data has multiple members with different alignment specifications. Polyspace reports the declaration of varNoAlignZero as noncompliant with the coding rule because of the use of _Alignas (0).

Check Information

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

Version History

Introduced in R2024a