Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does addition of two variable types inside sizeof() return the biggest variable size value instead of their sum?

Tags:

c++

sizeof

#include <iostream>

using namespace std;

int main()
{
    int a;
    long b;

    cout<<sizeof(a+b);

    return 0;
}

The output is 8 (size of a long variable). Why doesn't it return their sum?

like image 473
Sandeep Chaurasiya Avatar asked Apr 01 '20 10:04

Sandeep Chaurasiya


2 Answers

the output is 8(size of a long variable)

Because of Integer Promotion.

According to cppreference.com:

the ranks of all signed integer types are different and increase with their precision: rank of signed char < rank of short < rank of int < rank of long int < rank of long long int

Therefore, a + b produces a long because a is int and b is long (rank of long is greater than int).

So, you have sizeof(long) which is 8.

why it doesn't return their addition

You may be looking for sizeof(a) + sizeof(b);

like image 72
Ardent Coder Avatar answered Oct 09 '22 22:10

Ardent Coder


sizeof operator returns the size in bytes of a (type) or expression.

a + b is an expression and a is promoted to long after implicit conversion that's why the result is 8 on your machine i.e. the size of the long.

For calculating the total size of multiple types and/or expressions, calculate them separately and use addition like this:

auto total = sizeof(a) + sizeof(b) + sizeof(c+d);
like image 5
Azeem Avatar answered Oct 09 '22 22:10

Azeem