Result of sizeof operator using C++

C++Server Side ProgrammingProgramming

Sizeof operator is one of the most used operators in C language used to compute the size of any data structure or data type that we pass through it. The sizeof operator returns unsigned integer type, and this operator can be applied to primitive and compound data types. We can use sizeof operator directly to data types and know the memory it is taking up −

Example

#include <bits/stdc++.h>
using namespace std;

int main() {
   cout << sizeof(int) << "\n";
   cout << sizeof(char) << "\n";
   cout << sizeof(float) << "\n";
   cout << sizeof(long) << "\n";
   return 0;
}

Output

4
1
4
8
8

By using this functionality, we can know the space any variable of this data type takes up. The output also depends on the compiler as a 16_bit compiler will give a different value for int than a 32_bit compiler.

We can also apply this operation to an expression −

Example

#include <bits/stdc++.h>
using namespace std;

int main() {
   cout << sizeof(int) << "\n";
   cout << sizeof(char) << "\n";
   cout << sizeof(float) << "\n";
   cout << sizeof(double) << "\n";
   cout << sizeof(long) << "\n";
   return 0;
}

Output

4
4

As you can see, the previous value of x was four, and even after the prefix operation, it happens to remain the same. This is all because of the sizeof the operator because this operator is used during the compile-time, so it doesn’t change the value of the expression we applied.

Necessity of sizeof Operator

There are various uses of the sizeof operator. Still, it is mainly used to determine a compound data type size like an array, structure, union, etc.

Example

#include <bits/stdc++.h>

using namespace std;

int main() {
   int arr[] = {1, 2, 3, 4, 5}; // the given array

   int size = sizeof(arr) / sizeof(int); // calculating the size of array

   cout << size << "\n"; // outputting the size of given array
}

Output

5

Here firstly, we calculate the size of the whole array or calculate the memory it is taking up. Then we divide that number with the sizeof of the data type; in this program, it is int.

The second most important use case for this operator is allocating a dynamic memory, so we use the sizeof operator when allotting the space.

Example

#include <bits/stdc++.h>

using namespace std;

int main() {
   int* ptr = (int*)malloc(10 * sizeof(int)); // here we allot a memory of 40 bytes
   // the sizeof(int) is 4 and we are allocating 10 blocks
   // i.e. 40 bytes
}

Conclusion

In this article, we are discussing the uses of the sizeof operator and how this works. We also coded different types of its use cases to see the output and discuss it. We implemented the use cases of this operator in C++. We can write the same program in other languages such as C, Java, Python, etc. We hope you find this article helpful.

raja
Published on 29-Nov-2021 09:56:03
Advertisements