Sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t. sizeof can be applied to any data-type, including primitive types such as integer and floating-point types, pointer types, or compound datatypes such as Structure, union etc.
sizeof() operator is used in different way according to the operand type.
1. When operand is a Data Type.
When sizeof() is used with the data types such as int, float, char… etc it simply returns the amount of memory is allocated to that data types.
Let’s see example:
1 4 4 8
Note: sizeof() may give different output according to machine, we have run our program on 32 bit gcc compiler.
2. When operand is an expression.
When sizeof() is used with the expression, it returns size of the expression. Let see example:
As we know from first case size of int and double is 4 and 8 respectively, a is int variable while d is a double variable. The final result will be a double, Hence the output of our program is 8 bytes.
Need of Sizeof
1. To find out number of elements in a array.
Sizeof can be used to calculate number of elements of the array automatically. Let see Example :
Number of elements: 11
2. To allocate a block of memory dynamically.
sizeof is greatly used in dynamic memory allocation. For example, if we want to allocate memory for which is sufficient to hold 10 integers and we don’t know the sizeof(int) in that particular machine. We can allocate with the help of sizeof.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Is sizeof for a struct equal to the sum of sizeof of each member?
- Difference between sizeof(int *) and sizeof(int) in C/C++
- Operands for sizeof operator
- Implement Your Own sizeof
- Do not use sizeof for array parameters
- How to find size of array in C/C++ without using sizeof ?
- sizeof() for Floating Constant in C
- Difference between strlen() and sizeof() for string in C
- Anything written in sizeof() is never executed in C
- Why does sizeof(x++) not increment x in C?
- Result of comma operator as l-value in C and C++
- C/C++ Ternary Operator - Some Interesting Observations
- A comma operator question
- To find sum of two numbers without using any operator
- When should we write our own assignment operator in C++?
- Default Assignment Operator and References
- Operator Precedence and Associativity in C
- Can we use % operator on floating point numbers?
- Scope Resolution Operator Versus this pointer in C++?
- Set a variable without using Arithmetic, Relational or Conditional Operator
Improved By : dominicsavio