Tuesday, 31 December 2013

Difference between SIZEOF AND SIZEOF() IN C or C++

 

1. Size of is an unary operator. unary operator is a operator that acts upon the single operand at a time Eg: postincrement, logical not and so on

2. size of can be used as following formats
sizeof(int), sizeof int, sizeof i,sizeof(arr),

3. It is used to calculate the size of the data type.

4. Size is returned in the bytes which is of the form “size_t”. size_t is an unsigned type which is always positive.

5. Sizeof as return type
You can also return the sizeof array using the size_t as datatype.
size_t  my_function()
{
  size_t mysize=sizeof(int);
  return mysize;
}

6. size of can be applied to any datatypes such as basic, derived, Enumerated and void

7. Need for sizeof
Even though the size of the datatypes are predefined by the c standard already Not every implementation of the compiler follows the correct standard. So size of is useful at a time of allocating the dynamic memory. so whenever we need to allocate the memory dynamically we should use the sizeof function to find the size of the datatype.

8. We cannot use the size of operator in preprocessor expressions. Because the preprocessor does not know about the sizeof

9. Difference between sizeof and sizeof()
we can use sizeof as both keyword “sizeof int”and function type sizeof(int). Although we use the sizeof as function type it doesnot mean that it is an function. Because according to the C standard function should only take arguments as value not as datatype.

10. When sizeof is applied to the static array or structure, it will  return the size of  the entire array and entire structure.

11. Using Sizeof to find the number of elements in a array:
sizeof(arr)/sizeof(arr[0]);
You can also write a macro to that defines the size of 
#define arraysize(array) sizeof(array)/sizeof(*array)
In one of the above statement I have mentioned that c preprocessor does not know about  the sizeof. But here #define just expands the macro at runtime. Here the sizeof will work.

12. Cannot apply sizeof to structure without members:
Applying sizeof is invalid in the following cases.
struct x;
int arr[];
Although the above declaration is leagal in C, Applying sizeof is illegal here. Because without knowing the member of the array and structure it cannot find the size.

13.  C++ 11 standard allows to find the sizeof to the structure member too.
For eg: 

struct s
{
  int a;
  int b;
}
int main()
{
  cout<<sizeof(s::a);
}