-->





Translate

sizeof operator c++ tutorial with examples

Leave a Comment
Sizeof of operator is a unary operator which is used to calculate the size of a data type in bytes during a program compilation process. Pass a data type name and it will return the size in bytes.


List of Basic Data types their sizes and value ranges

Data TypeBytesMin ValueMax Value
char    1   -128127
short    2-3276832767
int    2-3276832767
long    4-21474836482147483647
double    8  10^-30810^308
float    410^-3810^38
unsigned short    2        065535
unsigned    int    2        065535
unsigned    long    4        04294967295
  bool    1True/FalseTrue/False


To understand more deeply let discuss a scenario
we have array of type integer of size 10
int array[10];
we want to calculate its size in two ways.
  1. sizeof operator in main function
  2. sizeof operator in another function in which array will be passed

Let see if the both methods returns same result or different. If different then why?
Cpp code example

#include<iostream>
using namespace std;

void calculate_size(int *);
int main()
{
    int array[10];

    cout<<"Size of array in bytes->
          main function "<<sizeof(array);
    cout<<"\n\n\n";

    calculate_size(array);

    return 0;

}

void calculate_size(int *iPtr)
{
   cout<<"Size of array in bytes-> 
     another function: "<<sizeof(iPtr)<<endl;
}


Example input/ouput of c++ program



As we can see both results are different buy why?

Lets explain it:
We know Integer takes 4 bytes in memory
we have array[10]->  10X4= 40 bytes in memory
so in main function body compiler knows that array is declared and it's size is -> sizeof(array)= 40 correct

In second result we have function with integer pointer argument. Array name is a constant pointer it will take 4 bytes that is why the result is different because we passed the array name(constant pointer) in function and within the scope of this function we have a single pointer of type integer.
address of array stored in iPtr->  iPtr=&array;

For pointers read here: Learn pointers in C++ Tutorial 
Sizeof Operator Example:
calculate number of elements in array using sizeof operator operations
We can also calculate number of elements in an array simple using two sizeof operators.
Lets discuss a Cpp code 


#include<iostream>
using namespace std;

int main()
{
    double array[10];
    int elements=sizeof(array)/sizeof(array[0]);

    cout<<"Total Elements "<<elements;
    cout<<"\n\n\n";

    return 0;

}


we have double array[10];
sizeof(array)=40
sizeof(array[0])=4
No.of Elements =sizeof(array)/sizeof(array[0])= 10


Note:
Size of data type varies from system to system specifications for 32-bit and 64 bit sizes may differ it is recommend to use sizeof operator for portability purpose.

Read more: Cpp Programming Tutorials

0 comments:

Post a Comment