C++ sizeof Operator
Table of content
C++ sizeof Operator
sizeof
is a compile-time operator used to calculate the size of data type or variable.sizeof
operator will return the size in integer format.sizeof
is a keyword.sizeof
operator can be nested.
Syntax of sizeof Operator:
sizeof(data type)
Data type include variables, constants, classes, structures, unions, or any other user defined data type.
Examples of sizeof operator:
Size of Data Types
#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:
Size of int : 4 Size of long int : 4 Size of float : 4 Size of double : 8 Size of char : 1
Size of Variables:
#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:
Size of variable i : 4 Size of variable c : 1
Size of Constant:
#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:
Size of integer constant: 4 Size of character constant : 1
Nested sizeof operator:
#include <iostream> using namespace std; int main() { int num1,num2; cout << sizeof(num1*sizeof(num2)); return 0; }
Output:
4