on Leave a Comment

Sizeof Operator in C++

C++ has a keyword called sizeof, that determines the size of any data type either predefined data type or user defined data type. The sizeof operator is used to get the size of any data type, for example classes, structure, union or any data type.

When we defining a class, we actually define a new data type and this is same for structure and union. The sizeof operator is a compile time operator.

The sizeof operator determines the size of data type in bytes.

Note: sizeof is a operator, it is not a function.

Syntax of sizeof operator

sizeof(data-type)

Here data type can be any predefined data type or user defined data type.

Example:

int y = sizeof(int);
cout<<y;

Output:

4

Program to understand sizeof operator in C++

Example 1:

#include<iostream>
using namespace std;
class A
{
public:
    int x, y;
};
class B: public A
{
public:
    int a, b;
};
int main()
{
 int y = sizeof(B);
 cout<<y;
 return 0;
}

OUTPUT:

16

Size of class B is 16 because it also contains the variables of class A.

Example 2:

#include<iostream>
using namespace std;
int main()
{
          cout<<"Size of int is "<<sizeof(int);
          cout<<"\nSize of char is "<<sizeof(char);
          cout<<"\nSize of float is "<<sizeof(float);
          cout<<"\nSize of double is "<<sizeof(double);
          cout<<"\nSize of wchar_t is "<<sizeof(wchar_t);
          cout <<"\nSize of short int : "<<sizeof(short int);
          cout <<"\nSize of long int : "<<sizeof(long int);
          return 0;
}

OUTPUT:

Size of int is 4
Size of char is 1
Size of float is 4
Size of double is 8
Size of wchar_t is 2
Size of short int : 2
Size of long int : 4


0 comments:

Post a Comment