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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP