Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the output of this code implementation defined?

Consider the following two function overloads:

int foo(int a)
{
  return 20;
}

const char foo(double b)
{
  return -3;
}

int x = foo(6.0);
cout << x;

Why does the result of this example depend on the concrete compiler or platform?

Compilation is by ISO/IEC 14882:1998.

like image 703
Hawklike Avatar asked Dec 11 '22 06:12

Hawklike


1 Answers

The function overloading is a red herring; the overload char foo(double) will be picked on all platforms.

The key difference is in the type char itself: the standard allows it to be either signed or unsigned. Which one is chosen is implementation defined.

On systems with unsigned char, the function would thus return the positive number CHAR_MAX - 2 (as the result of char(-3)).

like image 64
Baum mit Augen Avatar answered Jan 10 '23 06:01

Baum mit Augen