capypad
0 day streak
cpp / beginner
Snippet

The sizeof Operator for Memory Inspection

The sizeof operator returns the size in bytes of a type or variable at compile time. It is useful for understanding how much memory different data types consume. This is especially important in C++ because the size of fundamental types can vary between platforms. sizeof always evaluates to a constant at compile time, meaning it adds no runtime overhead.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <climits>
 
int main() {
std::cout << "int size: " << sizeof(int) << " bytes" << std::endl;
std::cout << "double size: " << sizeof(double) << " bytes" << std::endl;
std::cout << "char size: " << sizeof(char) << " bytes" << std::endl;
std::cout << "long long size: " << sizeof(long long) << " bytes" << std::endl;
std::cout << "Minimum char value: " << CHAR_MIN << std::endl;
std::cout << "Maximum char value: " << CHAR_MAX << std::endl;
return 0;
}
Breakdown
1
sizeof(int)
Returns byte size of int type (typically 4 bytes)
2
sizeof(double)
Returns byte size of double type (typically 8 bytes)
3
sizeof(char)
Returns byte size of char type (always 1 byte)
4
CHAR_MIN and CHAR_MAX
Constants from <climits> showing char range