C++ Tutorial C++ Advanced C++ References

C++ - sizeof() Operator



The C++ sizeof() operator returns the size of data type, constants, variable. It is a compile-time operator as it returns the size of any variable or a constant at the compilation time. It can also be used to get the size of classes, structures, unions and any other user-defined data type.

Syntax

//returns the size in bytes of the 
//object representation of type.
sizeof(type)

//returns the size in bytes of the object 
//representation of the type of expression, 
//if the expression is evaluated.
sizeof expression

Return Value

Returns the size in bytes of the object representation of type or type of expression.

Example:

The example below shows the usage of sizeof() operator.

#include <iostream>
using namespace std;

int main (){
  int x = 10;
  int A[10];
  int * ptr;
  ptr = A;

  //displaying size in bytes of 
  //various object representation 
  cout<<"Size of int : "<<sizeof(int)<<"\n";
  cout<<"Size of float : "<<sizeof(float)<<"\n";
  cout<<"Size of double : "<<sizeof(double)<<"\n";
  cout<<"Size of long double : "<<sizeof(long double)<<"\n";  
  cout<<"Size of variable x : "<<sizeof(x)<<"\n";
  cout<<"Size of array A : "<<sizeof A<<"\n";
  cout<<"Size of pointer ptr : "<<sizeof &ptr<<"\n";

  return 0;
}

The output of the above code will be:

Size of int : 4
Size of float : 4
Size of double : 8
Size of long double : 16
Size of variable x : 4
Size of array A : 40
Size of pointer ptr : 8

❮ C++ - Operators