#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?
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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With