C++ sizeof Keyword
Example
Measure the memory size of different variables and types:
int myInt = 5;
long int myLInt = 5;
float myFloat = 9.99;
char* myString = "Hello World!";
cout << sizeof(myInt) << "\n";
cout << sizeof(myLInt) << "\n";
cout << sizeof(myFloat) << "\n";
cout << sizeof(myString) << "\n";
cout << sizeof(char) << "\n";
cout << sizeof(double) << "\n";
Definition and Usage
The sizeof
keyword is an operator which measures the amount of memory used by a variable or data type.
When a data type is specified it indicates how many bytes are needed to store data of that type.
When a variable is specified it indicates how many bytes of memory the variable occupies.
Syntax
sizeof(data)
More Examples
Example
To count the elements in an array, divide the size of the array by the size of each element in the array:
int myNumbers[5] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof(myNumbers) / sizeof(int);
cout << getArrayLength;
Related Pages
Read more about data types in our C++ Data Types Tutorial.
Read more about array size in our C++ Array Size Tutorial.