C library - alignof() Operator



The C Library alignof() operator provides the alignment requirement (in bytes) for a given data type. It represents how memory should be allocated for instances of that type. For example, if the alignment requirement is 4, objects of that type should be placed at memory addresses that are multiples of 4. This ensures efficient memory access and proper alignment for data structures.

Syntax

Following is the syntax of the C library align()

alignof(type)

Parameters

This function accepts only a single parameter that is 'type'. A type is denoted as int, char, float, user-defined structure, classes, etc.

Return Type

This operator returns the datatype values into bytes.

Example 1

Following is the basic C library operator alignof() to measure the data types results in bytes.

#include <stdalign.h>
#include <stddef.h>
#include <stdio.h>
 
int main(void)
{
   printf("The alignment of char = %zu\n", alignof(char));
   printf("The alignment of max_align_t = %zu\n", alignof(max_align_t));
   printf("alignof(float[10]) = %zu\n", alignof(float[10]));
   printf("alignof(struct{char c; int n;}) = %zu\n",
            alignof(struct {char c; int n;}));
   return 0;
}

Output

On execution of above code, we get the following result −

The alignment of char = 1
The alignment of max_align_t = 16
alignof(float[10]) = 4
alignof(struct{char c; int n;}) = 4

Example 2

In this example, we measure the bytes value of two different types that are max_align_t and structure classes(struct).

#include <stdio.h>
#include <stddef.h>
#include <stdalign.h>

int main(void) {
    printf("Alignment of max_align_t: %zu\n", alignof(max_align_t));
    printf("Alignment of struct { char c; int n; }: %zu\n", alignof(struct { char c; int n; }));
    return 0;
}

Output

After executing the above code, we get the following result −

Alignment of max_align_t: 16
Alignment of struct { char c; int n; }: 4
c_library_stdalign_h.htm
Advertisements