C++ sizeof Operator
The sizeof operator in C++ returns the size in bytes of a variable, data type, array, or structure. It is evaluated at compile-time for data types and can be used to determine memory requirements.
1. Size of Data Types
You can use sizeof to find the memory size of fundamental data types.
#include <iostream>
using namespace std;
int main() {
cout << "Size of int: " << sizeof(int) << " bytes" << endl;
cout << "Size of float: " << sizeof(float) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes" << endl;
cout << "Size of char: " << sizeof(char) << " bytes" << endl;
cout << "Size of bool: " << sizeof(bool) << " bytes" << endl;
return 0;
}
2. Size of Variables
You can also find the size of variables using sizeof.
#include <iostream>
using namespace std;
int main() {
int a;
double b;
char c;
cout << "Size of a: " << sizeof(a) << " bytes" << endl;
cout << "Size of b: " << sizeof(b) << " bytes" << endl;
cout << "Size of c: " << sizeof(c) << " bytes" << endl;
return 0;
}
3. Size of Arrays
sizeof can be used to find the total size of an array or number of elements.
#include <iostream>
using namespace std;
int main() {
int arr[10];
cout << "Total size of arr: " << sizeof(arr) << " bytes" << endl;
cout << "Number of elements in arr: " << sizeof(arr)/sizeof(arr[0]) << endl;
return 0;
}
4. Size of Structures
sizeof can also find memory size of user-defined structures, including padding bytes.
#include <iostream>
using namespace std;
struct Student {
int id;
char grade;
double marks;
};
int main() {
cout << "Size of Student structure: " << sizeof(Student) << " bytes" << endl;
return 0;
}
5. Combined Program
This program demonstrates sizeof operator for data types, variables, arrays, and structures together.
#include <iostream>
using namespace std;
struct Student {
int id;
char grade;
double marks;
};
int main() {
int a;
double b;
char c;
int arr[5];
cout << "Size of int: " << sizeof(int) << " bytes" << endl;
cout << "Size of double: " << sizeof(double) << " bytes" << endl;
cout << "Size of char: " << sizeof(char) << " bytes" << endl;
cout << "Size of variable a: " << sizeof(a) << " bytes" << endl;
cout << "Size of array arr: " << sizeof(arr) << " bytes" << endl;
cout << "Number of elements in arr: " << sizeof(arr)/sizeof(arr[0]) << endl;
cout << "Size of structure Student: " << sizeof(Student) << " bytes" << endl;
return 0;
}
Conclusion
The sizeof operator in C++ helps determine memory size of data types, variables, arrays, and structures. It is essential for understanding memory usage and array element calculations.
Codecrown