c-plus-plus
  1. c-plus-plus-sizeof-operator

C++ Pointers sizeof() Operator

Syntax

The sizeof operator in C++ is used to determine the size of a variable or data type.

sizeof(variable or data type)

Example

#include <iostream>
using namespace std;

int main() {
   int myArray[] = {1, 2, 3, 4, 5};
   int sizeOfArray = sizeof(myArray) / sizeof(int);
   cout << "Size of myArray is " << sizeof(myArray) << " bytes." << endl;
   cout << "Size of int is " << sizeof(int) << " bytes." << endl;
   cout << "Number of elements in myArray is " << sizeOfArray << endl;
   return 0;
}

Output

Size of myArray is 20 bytes.
Size of int is 4 bytes.
Number of elements in myArray is 5

Explanation

In the above example, we have an integer array myArray initialized with values {1, 2, 3, 4, 5}. We used the sizeof operator to find the size of myArray in bytes, which is equal to 5 * sizeof(int). We also find the size of int data type using the sizeof operator. We divide the size of myArray by the size of int to get the number of elements in the array.

Use

sizeof operator is used to find the size of a data type or variable. It can also be used to find the size of an array. This operator comes handy in situations where we need to allocate memory dynamically.

Important Points

  • The sizeof operator returns the size of a variable in bytes.
  • The size of a variable in C++ may vary depending on the type of data it holds.
  • sizeof returns the size of the entire array and not just a single element in the array.
  • sizeof can be used to find the size of any data type, including user-defined types.

Summary

The sizeof operator in C++ is a useful operator that allows us to find the size of a variable or data type. It returns the size of a variable in bytes, and it comes in handy in situations where we need to allocate memory dynamically. It is important to note that the size of a variable in C++ may depend on the data it holds.

Published on: