Alignof operator in C++


Operator is a symbol which is used to indicate the compiler to perform some operation in programming language.

alignof operator is the operator that returns the alignment that is to be applied to the given type of variable. The returned value is in bytes.

Syntax

var align = alignof(tpye)

Explanation

  • alignof − the operator is used to return the alignment of the inputted data.

  • parameter type − the data type whose alignment is to be returned.

  • return value − The value in bytes that is be used as alignment for the given data type.

Example

The program to return the values for align of basic data types.

 Live Demo

#include <iostream>
using namespace std;
int main(){
   cout<<"Alignment of char: "<<alignof(char)<< endl;
   cout<<"Alignment of int: "<<alignof(int)<<endl;
   cout<<"Alignment of float: "<<alignof(float)<< endl;
   cout<<"Alignment of double: "<<alignof(double)<< endl;
   cout<<"Alignment of pointer: "<<alignof(int*)<< endl;
   return 0;
}

Output

Alignment of char: 1
Alignment of int: 4
Alignment of float: 4
Alignment of double: 8
Alignment of pointer: 8

Example

 Live Demo

#include <iostream>
using namespace std;
struct basic {
   int i;
   float f;
   char s;
};
struct Empty {
};
int main(){
   cout<<"Alignment of character array of 10 elements: "<<alignof(char[10])<<endl;
   cout<<"Alignment of integer array of 10 elements: "<<alignof(int[10])<<endl;
   cout<<"Alignment of float array of 10 elements: "<<alignof(float[10])<<endl;
   cout<<"Alignment of class basic: "<<alignof(basic)<<endl;
   cout<<"Alignment of Empty class: "<<alignof(Empty)<<endl;
   return 0;
}

Output

Alignment of character array of 10 elements: 1
Alignment of integer array of 10 elements: 4
Alignment of float array of 10 elements: 4
Alignment of class basic: 4
Alignment of Empty class: 1

sizeof() operator in C++ programming language is the unary operator that is used to compute the size of operand.

Example

This program is to show the difference between sizeof operator and the alignof operator.

 Live Demo

#include <iostream>
using namespace std;
int main(){
   cout<<"Alignment of char: "<<alignof(char)<<endl;
   cout<<"size of char: "<<sizeof(char)<<endl;
   cout<<"Alignment of pointer: "<<alignof(int*)<<endl;
   cout<<"size of pointer: "<<sizeof(int*)<<endl;
   cout<<"Alignment of float: "<<alignof(float)<<endl;
   cout<<"size of float: "<<sizeof(float)<<endl;
   return 0;
}

Output

Alignment of char: 1
size of char: 1
Alignment of pointer: 8
size of pointer: 8
Alignment of float: 4
size of float: 4

Updated on: 16-Oct-2019

495 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements