Sizeof operator is one of the most commonly used operators in C language and is used to calculate the size of any data structure or data type that we pass. The sizeof operator returns an unsigned integer type and can be applied to primitive and composite data types. We can directly use sizeof operator on the data type and know the memory occupied by it -
#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; }
4 1 4 8 8
By using this function we can know the data type The space occupied by any variables. The output is also compiler dependent, as a 16-bit compiler will give a different value for int than a 32-bit compiler.
We can also apply this operation to expressions -
#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; }
4 4
As you can see, The previous value of x was 4, which happens to remain the same even after the prefix operation. This is all because of the sizeof operator, because this operator is used at compile time, it does not change the value of the expression we apply.
#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 }
5
Here first we calculate the size of the entire array or calculate the memory it occupies. We then divide that number by the sizeof data type; in this program, it's int.
The second most important use case of this operator is to allocate dynamic memory, so we use the sizeof operator when allocating space.
#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 }
In this article, we will discuss the usage of sizeof operator and how it works. We also wrote different types of use cases to see the output and discuss it. We implemented the use case of this operator in C. We can write the same program in other languages like C, Java, Python etc. We hope this article was helpful to you.
The above is the detailed content of Result of using sizeof operator in C++. For more information, please follow other related articles on the PHP Chinese website!