![The C Standard Library Reference](/c_standard_library/images/c-mini-logo.jpg)
- The C Standard Library
- C Library - Home
- C Library - <assert.h>
- C Library - <complex.h>
- C Library - <ctype.h>
- C Library - <errno.h>
- C Library - <fenv.h>
- C Library - <float.h>
- C Library - <inttypes.h>
- C Library - <iso646.h>
- C Library - <limits.h>
- C Library - <locale.h>
- C Library - <math.h>
- C Library - <setjmp.h>
- C Library - <signal.h>
- C Library - <stdalign.h>
- C Library - <stdarg.h>
- C Library - <stdbool.h>
- C Library - <stddef.h>
- C Library - <stdio.h>
- C Library - <stdlib.h>
- C Library - <string.h>
- C Library - <tgmath.h>
- C Library - <time.h>
- C Library - <wctype.h>
- C Standard Library Resources
- C Library - Quick Guide
- C Library - Useful Resources
- C Library - Discussion
- C Programming Resources
- C Programming - Tutorial
- C - Useful Resources
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