Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Toán tử alignof trong C++

Toán tử alignof trả về yêu cầu căn chỉnh (alignment) của một kiểu dữ liệu, đơn vị byte.

Cú pháp

size_t alignment = alignof(type);

Ví dụ: Alignment các kiểu cơ bản

#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;
}

Kết quả

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

Ví dụ: Struct và mảng

struct Basic { int i; float f; char s; };
struct Empty {};

int main() {
    cout << "char[10]: " << alignof(char[10]) << endl;
    cout << "int[10]: " << alignof(int[10]) << endl;
    cout << "float[10]: " << alignof(float[10]) << endl;
    cout << "struct Basic: " << alignof(Basic) << endl;
    cout << "struct Empty: " << alignof(Empty) << endl;
    return 0;
}

Kết quả

char[10]: 1
int[10]: 4
float[10]: 4
struct Basic: 4
struct Empty: 1

So sánh alignof và sizeof

int main() {
    cout << "alignof(char): " << alignof(char) << ", sizeof(char): " << sizeof(char) << endl;
    cout << "alignof(int*): " << alignof(int*) << ", sizeof(int*): " << sizeof(int*) << endl;
    cout << "alignof(float): " << alignof(float) << ", sizeof(float): " << sizeof(float) << endl;
    return 0;
}

Kết quả

alignof(char): 1, sizeof(char): 1
alignof(int*): 8, sizeof(int*): 8
alignof(float): 4, sizeof(float): 4