×

Sizeof() Operators in C++

sizeof() Operators in C++

The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size of the variables or constants in the compile time.

Syntax:    

sizeof()(data_type)

Here, the data_type may be a constant, a variable, or any other structures or union.

Lets us see the coding illustration to visualize how sizeof() operator works.

Example 1:

 #include<bits/stdc++.h>
 using namespace std; 
 int main() 
 {
  cout << "Size of Integer : " <<sizeof(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:

sizeof() Operators in CPP

Explanation:

As already discussed, the sizeof() operator returns the size of any data type, constants, or any variable. In the above program, we have implemented the sizeof() operator to visualize how the sizeof() operator works in close integration with different data types.

Example 2:

 #include<bits/stdc++.h>
 using namespace std; 
 class Main
     { 
     int x; 
     }; 
 int main() 
 { 
     Main y; 
         cout << "Size of Main class is : "<<sizeof(y) <<endl; 
     return 0; 
 }  

Output:

sizeof() Operators in CPP

Explanation:

In the above, we have implemented the use of the sizeof() operator using class. We have defined a class 'Main,' with a data member 'x' of integer type. We have defined another integer variable in the driver code, 'b,' associate with class Main. Since we know that member 'a' is an integer, so in the driver code, it should print as 4 if we use the sizeof() operator. Therefore, 4 is printed on the console as the size of an integer variable in the class 'Main.'

Similarly, we can add more data members be it a char or a float. The sizeof() operator will return the total size of the variables or the data members assigned to some classes.

Lets us look how the sizeof() operator works for arrays.

Example 3:

 #include <bits/stdc++.h>
 using namespace std; 
 int main() 
 { 
   int array[]={101,202,303,404,505,606}; 
   cout << "Size of the given array is : "<< sizeof(array)<<endl; 
   return 0; 
 } 

Output:

sizeof() Operators in CPP

Explanation:

In the above code, we have used the sizeof() operator to calculate the total size of the linear data type i.e., array. The array in the above code is initialized with the 6 different values. As we know that an integer is of 4 bytes, so the sizeof() operator returns the value of the integer on the console as 24.

Example 4:

 #include <bits/stdc++.h>
 using namespace std; 
 int main() 
 { 
     int *pointer1=new int(11); 
         cout << "size of pointer 1 : " <<sizeof(pointer1)<<endl;                                                                                                                                                                                                                                  
         cout << "size of *pointer 1 : " <<sizeof(*pointer1)<<endl; 
    char *pointer2=new char('b'); 
         cout <<"size of pointer 2 : " <<sizeof(pointer2)<<endl; 
         cout <<"size of *pointer 2 : "<<sizeof(*pointer2)<<endl; 
    double *pointer3=new double(13.70); 
         cout <<"size of pointer 3 : " <<sizeof(pointer3)<<endl; 
         cout <<"size of *pointer 3 : "<<sizeof(*pointer3)<<endl; 
     return 0; 
 }  

Output:

sizeof() Operators in CPP

Explanation:

In the above code, we have used the sizeof() operator to illustrate its working with the pointers. Therefore, we have constructed three-pointers, namely 'pointer1', 'pointer2', 'pointer3' associated with three different data types int, char, and double(float). We have assigned values for these data types, respectively. Since we are very familiar with the size of different data types, the program returns their size concerning their original value and their associated pointer. The sizes are then displayed on the console as outputs.

Advantages of using sizeof() operator

The advantages are listed below:

  1. Acts as a savior

Whenever we want to know the number of elements in an array or the type of fashion in which they are arranged, the sizeof() operator acts as a savior as it automatically does that.

2. Helps in Memory allocation

It adds a great advantage in dynamic programming as it allows the programmer to dynamically allocate the size of the block of memory. It helps in memory allocation with enough prior knowledge to allocate enough memory. The memory is allocated in a particular machine which is difficult to do with other operators.

3. Versatile and Flexible

It is a versatile and flexible operator in C++, which helps in streamlining for the allocation of the memory.

Points to Remember:

  1. sizeof() operator is a compile-time unary operator that can be used to get the size of the operand.
  2. The result of the size of the result returned by the sizeof() operator is an unsigned integer value which depends on the nature of the data-type.
  3. Normally, the size of an object is the sum of its constituent data members. It is guaranteed that the sizeof() operator will never be smaller than that provided compiler keeps padding between data members to ensure alignment requirements of the platform.

Related Topics

Star pattern in C++ using For Loops

Star patterns are one of the most extensively utilized patterns in any programming language since they help to increase logical thinking and flow control understanding.In the C++ programming language, you...

3 minutes read.

How to Use Getline in C++

What is getline in C++? Similar to the cin function, which allows the programmer to take input from the user getline() function also takes input from the user. But in this...

4 minutes read.

Pattern programs in C++

In this article, we are going to discuss different pattern programs in C++. Program for Printing * patterns: Right Angle Triangle* pattern #include <iostream> using namespace std; int main() {     int rows;     cout <<...

3 minutes read.

C++ Virtual Function

A virtual function is such function which is declared inside the base class and redefined by the derive class. C++ uses a virtual keyword to make a function as a virtual function. The virtual...

1 minute read.

C++ program to read string using cin.getline()

C++ program to read string using cin.getline() C++ getline() is a standard library feature for reading a string or a line from an input source. A getline() function gets characters from...

3 minutes read.

Call by Pointer in C++

What is Pointer? Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined...

5 minutes read.

Advanced C++ with Boost Library

The goal of the Boost Libraries is to be widely applicable and used in a variety of applications. For instance, they can in handy when working with huge numbers whose...

4 minutes read.

C++ if-else

C++ if else Control Statement if else control statement in C++ is used to control the program flow in a two-way direction. When condition returns a true value, then the program executes if condition block otherwise...

1 minute read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

C++ Continue

In C++, the continue statement is a useful tool for avoiding specific scenarios without breaking the loop. It is employed inside loops to move directly to the following iteration and...

4 minutes read.

C++ Variable

In this article, we will discuss variables in C++ with their types and examples. What are Variables? Variables are specific memory storage spaces that hold a value. During the execution of a...

4 minutes read.

Accumulate() and partial_sum() in C++ STL Numeric header

The C++ STL's numeric library includes the numeric header. This library provides efficient numeric arrays, support for random number generation, and fundamental mathematical operations and types. Several of the numeric...

3 minutes read.

C++ int into String

Data type conversion is a standard editing process. You may need to convert variable from one type of data to another in a variety of situations. There are two ways...

5 minutes read.

Difference between exit() and _Exit() in C++

Before understanding the difference between the exit() and _Exit(), one must know about exit() and _Exit() functions. The exit() function in C/C++ The exit() method in the C language kills the calling...

3 minutes read.

Virtual Function Vs Pure Virtual Function

Virtual activity is a member function defined in the foundation phase that can be redefined by acquired classes. Let's have a look at an example: #include <iostream>   #include <bits/stdc++.h> #include <stdlib> using namespace std;   class Base   {    ...

5 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

5 minutes read.

Char Array to String in C++

Regardless of the programming language you use, data structure is critical to the success of your project. Although each programming language has its own collection of data structures, C++ contains a...

4 minutes read.

4-Dimensional Array in C/C++

A four-dimensional (4D) array is an array of three-dimensional (3D) arrays, or in other words we can say that a 4- dimensional array is an array of arrays of arrays...

3 minutes read.

Add two numbers represented by two arrays in C++

The array stores a number in such a way that each digit of the number is represented by an array element. As an example, The array number 147 is 1,4,7. To add...

3 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.