In this tutorial you will learn about the C++ sizeof and its application with practical example.
C++ sizeof
In C++, the sizeof operator is used to determines the size of a variable or any data type. It is a compile-time operator which returns the size of variable or data type in
in bytes.
Syntax:-
1 |
sizeof(type) |
Here, type include variables, constants, classes, structures, unions, or any other user defined data type.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> using namespace std; int main() { cout << "Size of int : " << sizeof(int) << endl; cout << "Size of long int : " << sizeof(long int) << endl; cout << "Size of float : " << sizeof(float) << endl; cout << "Size of double : " << sizeof(double) << endl; cout << "Size of char : " << sizeof(char) << endl; return 0; } |
Output:-
1 2 3 4 5 |
Size of int : 4 Size of long int : 4 Size of float : 4 Size of double : 8 Size of char : 1 |
Size of Variables
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> using namespace std; int main() { int i; char c; cout << "Size of variable i : " << sizeof(i) << endl; cout << "Size of variable c : " << sizeof(c) << endl; return 0; } |
Output:-
1 2 |
Size of variable i : 4 Size of variable c : 1 |
Size of Constant
Example:-
1 2 3 4 5 6 7 8 9 10 |
#include <iostream> using namespace std; int main() { cout << "Size of integer constant: " << sizeof(10) << endl; cout << "Size of character constant : " << sizeof('a') << endl; return 0; } |
Output:-
1 2 |
Size of integer constant: 4 Size of character constant : 1 |
Nested sizeof operator
Example:-
1 2 3 4 5 6 7 8 9 |
#include <iostream> using namespace std; int main() { int num1,num2; cout << sizeof(num1*sizeof(num2)); return 0; } |
Output:-
1 |
4 |