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

Kích thước int, long theo chuẩn C++ trên các kiến trúc


Kích thước kiểu dữ liệu phụ thuộc vào kiến trúc và mô hình dữ liệu (data model).

Các mô hình dữ liệu phổ biến

Mô hìnhintlonglong longCon trỏHệ thống điển hình
ILP3232-bit32-bit64-bit32-bit32-bit systems
LP6432-bit64-bit64-bit64-bitLinux/macOS 64-bit
LLP6432-bit32-bit64-bit64-bitWindows 64-bit

Ví dụ kiểm tra tại runtime

#include <iostream>
using namespace std;

int main() {
    cout << "sizeof(char)     = " << sizeof(char)     << " byte (" << sizeof(char)*8     << " bits)\n";
    cout << "sizeof(short)    = " << sizeof(short)    << " byte (" << sizeof(short)*8    << " bits)\n";
    cout << "sizeof(int)      = " << sizeof(int)      << " byte (" << sizeof(int)*8      << " bits)\n";
    cout << "sizeof(long)     = " << sizeof(long)     << " byte (" << sizeof(long)*8     << " bits)\n";
    cout << "sizeof(long long)= " << sizeof(long long)<< " byte (" << sizeof(long long)*8 << " bits)\n";
    cout << "sizeof(void*)    = " << sizeof(void*)    << " byte (" << sizeof(void*)*8    << " bits)\n";
    cout << "sizeof(size_t)   = " << sizeof(size_t)   << " byte (" << sizeof(size_t)*8   << " bits)\n";
    return 0;
}

Đầu ra trên Linux 64-bit (LP64)

sizeof(char)     = 1 byte (8 bits)
sizeof(short)    = 2 byte (16 bits)
sizeof(int)      = 4 byte (32 bits)
sizeof(long)     = 8 byte (64 bits)
sizeof(long long)= 8 byte (64 bits)
sizeof(void*)    = 8 byte (64 bits)
sizeof(size_t)   = 8 byte (64 bits)

Đầu ra trên Windows 64-bit (LLP64)

sizeof(long)     = 4 byte (32 bits)  // Khác Linux!