I'm learning about function overloading in C++ and came across this:
void display(int a)
{
cout << "int" << endl;
}
void display(unsigned a)
{
cout << "unsigned" << endl;
}
int main()
{
int i = -2147483648;
cout << i << endl; //will display -2147483648
display(-2147483648);
}
From what I understood, any value given in the int
range (in my case int
is 4 byte) will call display(int)
and any value outside this range will be ambiguous (since the compiler cannot decide which function to call). It is valid for the complete range of int
values except its min value i.e. -2147483648
where compilation fails with the error
call of overloaded
display(long int)
is ambiguous
But taking the same value to an int
and printing the value gives 2147483648
. I'm literally confused with this behavior.
Why is this behavior observed only when the most negative number is passed? (The behavior is the same if a short
is used with -32768
- in fact, in any case where the negative number and positive number have the same binary representation)
Compiler used: g++ (GCC) 4.8.5
call of overloaded ‘display(long int)’ is ambiguous
. – Visitanttypeof(-2147483648) != int
. The literal is2147483648
, which is too big for anint
, so it's along
, and it's being negated – Willsonint j{-2147483648};
is a narrowing conversion. Almost worth a question in itself, that. It's probably related to allowing (e.g.)long long
constexpr values such as2147483647LL
to be narrowed in initialization. – Valeda