Computer >> Máy Tính >  >> Lập trình >> C ++

Toán tử căn chỉnh trong C ++

Người điều hành là một ký hiệu được sử dụng để chỉ ra trình biên dịch thực hiện một số hoạt động trong ngôn ngữ lập trình.

alignof toán tử là toán tử trả về sự liên kết sẽ được áp dụng cho loại biến đã cho. Giá trị trả về tính bằng byte.

Cú pháp

var align = alignof(tpye)

Giải thích

  • alignof - toán tử được sử dụng để trả về sự căn chỉnh của dữ liệu đã nhập.

  • loại thông số - kiểu dữ liệu có sự liên kết sẽ được trả về.

  • giá trị trả về - Giá trị tính bằng byte được sử dụng làm căn chỉnh cho kiểu dữ liệu đã cho.

Ví dụ

Chương trình trả về các giá trị để căn chỉnh các kiểu dữ liệ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;
}

Đầu ra

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

Ví dụ

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

Đầu ra

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 () toán tử trong ngôn ngữ lập trình C ++ là toán tử một ngôi được sử dụng để tính toán kích thước of toán hạng.

Ví dụ

Chương trình này là để hiển thị sự khác biệt giữa toán tử sizeof và toán tử 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;
}

Đầu ra

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