sizeof operator

"It's not the size of the dog in the fight; it's the size of the fight in the dog" Mark Twain

In the data-type section we mentioned that via data-type of a variable, compilers can figure out how much memory space should be set aside for a variable.

We also named a few basic-data types and gave the least memory-space that a compiler will allocated for variable of those types.

For example a variable of type int has at least 4 bytes.

But the memory space of a data-type is system-dependent. This mean if we have a variable of type int, in one system this variable might take 4 bytes but in another one it might end up taking 8 bytes!

For this reason, the C language brought an operator named sizeof which also can be used in C++ as well.

This operator takes one argument and that is the name of the data-type or the variable of the target data-type.

The return value of this operator is the number of bytes that the target data-type will take in the memory space.

Example:

#include <iostream>
using namespace std;
int main()
{
double vDouble = 1.2;
float vFloat = 33.33;
cout<<"The size of a double variable is: "<<sizeof(vDouble)<< "nAnd the size of a float variable is: "<< sizeof vFloat<<endl;
cout<<"The size of an int data-type is: "<<sizeof (int)<<endl;
return 0;
}

Output:

The size of a double variable is: 8

And the size of a float variable is: 4

The size of an int data-type is: 4

As you can see, on the system that this program ran, the memory space of a double-variable was 8 bytes, the size of float-variable was 4 bytes and the size of an integer-variable was 4 bytes as well.

But if you run this program, you might end up having different memory space for each of these data-types.