Basic data type declaration
I respective basic types of PC data sizes are as follows:
Code:
#include <iostream>
using namespace std;
int main() {
cout << "char: " << sizeof(char) << endl; // 1
cout << "bool: " << sizeof(bool) << endl; // 1
cout << "int: " << sizeof(int) << endl; // 4
cout << "long: " << sizeof(long) << endl; // 4
cout << "long long: " << sizeof(long long ) << endl; // 8
cout << "float: " << sizeof(float) << endl; // 4
cout << "double: " << sizeof(double) << endl; // 8
return 0;
}
Out:
char: 1
bool: 1
int: 4
long: 4
long long: 8
float: 4
double: 8
Structure
Code:
#include <iostream>
using namespace std;
struct A {
bool one;
};
struct B {
int one; // 4
bool two; // 1
};
struct C {
bool one; // 1
int two; // 4
double three; // 8
};
struct D {
char one[10]; // 12
double two; // 8
double three; // 8
};
int main()
{
cout << "A: " << sizeof(A) << endl;
cout << "B: " << sizeof(B) << endl;
cout << "C: " << sizeof(C) << endl;
cout << "D: " << sizeof(D) << endl;
}
Out:
A: 1
B: 8
C: 16
D: 32
Add compiler directives head:
#pragma pack(4)
Out:
A: 1
B: 8
C: 16
D: 28
Memory Alignment: In order to facilitate the reading of the CPU, the data structure of the compiler will be a fixed integer multiple of alignment, and this number is usually fixed with 4 bytes and 8 bytes. Generally determines the word length factor is a CPU, i.e. 32bit word length, for the CPU will read 4 bytes, to be more quickly and easily than the 1-byte read. And replaced 64bit word length of the CPU, wanted to 8-byte read will be more quickly and easily.
In the compiler-specific platforms, generally have a default "Align coefficient" (also called modulus aligned), i.e., does not correspond to the current CPU alignment word length coefficients. This factor can be changed by a pre-compiled command #pragma pack (n), where n is and you have to specify the "alignment factor."
Thus, I use the compiler MinGW-W64 gcc version 8.1.0
aligned coefficients default is 8 bytes, i.e. corresponding to the 64bit CPU.