sizeof() operator in C++
The C++ sizeof
operator is used to determine the size in bytes of a data type, an expression, or an object. It’s a compile-time operator, meaning that its result is determined by the compiler during compilation, and it returns an integer value representing the size in bytes. The syntax of the sizeof
operator is as follows:
sizeof (object)
Here are some common use cases for the sizeof
operator:
1. Size of Data Types:
You can use sizeof
to determine the size of fundamental data types, such as int
, float
, char
, etc.
#include <iostream>
int main() {
std::cout << "Size of int: " << sizeof(int) << " bytes" << std::endl;
std::cout << "Size of float: " << sizeof(float) << " bytes" << std::endl;
std::cout << "Size of char: " << sizeof(char) << " bytes" << std::endl;
return 0;
}
2. Size of Objects:
You can use sizeof
to determine the size of objects or instances of user-defined classes or structures.
#include <iostream>
struct MyClass {
int x;
double y;
};
int main() {
MyClass obj;
std::cout << "Size of MyClass: " << sizeof(obj) << " bytes" << std::endl;
return 0;
}
3. Size of Arrays:
sizeof
can be used to calculate the size of arrays, including both their data elements and any padding added by the compiler.
int arr[5];
std::cout << "Size of arr: " << sizeof(arr) << " bytes" << std::endl;
4. Size of Expressions:
You can use sizeof
to calculate the size of expressions, which can be useful in situations like dynamic memory allocation.
int* ptr = new int[10];
std::cout << "Size of dynamically allocated array: " << sizeof(ptr) << " bytes" << std::endl;
delete[] ptr; // Deallocate the dynamically allocated array
5. Size of Types:
You can use sizeof
to calculate the size of types, such as pointers, enums, and user-defined types.
enum Color { RED, GREEN, BLUE };
std::cout << "Size of Color enum: " << sizeof(Color) << " bytes" << std::endl;
Keep in mind that the size returned by sizeof
is platform-dependent and can vary between different compilers and systems. It represents the size in bytes required to store an object of the specified type or the size of the specified expression or object. It’s a valuable tool for memory management and understanding the storage requirements of your C++ code.