C++ 中的 alignof 运算符
运算符是用于向编译器指示执行编程语言中某些操作的符号。
alignof 运算符是返回要应用于给定类型变量的对齐方式的运算符。返回值以字节为单位。
语法
var align = alignof(tpye)
说明
alignof − 运算符用于返回输入数据的对齐方式。
参数类型 − 要返回其对齐方式的数据类型。
返回值 − 以字节为单位的值,用作给定数据类型的对齐方式。
示例
用于返回基本数据类型的对齐方式值的程序。
#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; }
输出
Alignment of char: 1 Alignment of int: 4 Alignment of float: 4 Alignment of double: 8 Alignment of pointer: 8
示例
#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; }
输出
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
C++ 编程语言中的sizeof() 运算符是一元运算符,用于计算操作数的大小。
示例
此程序用于显示 sizeof 运算符和 alignof 运算符之间的差异。
#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; }
输出
Alignment of char: 1 size of char: 1 Alignment of pointer: 8 size of pointer: 8 Alignment of float: 4 size of float: 4
广告