capypad
0 day streak
cpp / beginner
Snippet

The sizeof Operator: How Much Memory?

The sizeof operator tells you how many bytes a type or variable uses in memory. An int typically uses 4 bytes, a double uses 8 bytes, a char uses 1 byte, and a bool uses 1 byte. Knowing sizes helps you write memory-efficient programs.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;
 
int main() {
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 bool: " << sizeof(bool) << " bytes" << endl;
int numbers[10];
cout << "Size of int array[10]: " << sizeof(numbers) << " bytes" << endl;
long bigNumber = 1000000;
cout << "Size of long: " << sizeof(long) << " bytes" << endl;
return 0;
}
Breakdown
1
sizeof(int)
Returns the memory size of an int in bytes
2
sizeof(numbers)
Returns total size of the entire array, not just one element
3
sizeof(long)
Returns memory size of long type, usually 8 bytes on 64-bit systems
4
" bytes"
Appends unit label to make output clear