1

I'm trying to see default argument promotion in functions. Specifically I want to test section 6.5.2.2 Function calls (described here).

I want to have a prototype-less function call to see default argument promotion to integer but I get "Function does not take 1 arguments" error. This is what I'm trying to do:

#include<iostream>
using namespace std;

//void Func(char val);
//void Func(int val);
void Func();  // No prototype

int main(int argc, char** argv)
{
    char charVal = 'a';
    cout << "Func(charVal) - "; Func(charVal);

    return 0;
}

void Func(char val)
{
    cout << "Char arg. Result: " << val << endl;
}

void Func(int val)
{
    cout << "Int arg. Result: " << val << endl;
}

I expected to see Func(int) being called due to argument promotion. Is this removed from the standard already?

Cheers.

P.S- I just saw that this kind of prototype-less declarations are part of C standard, NOT C++. Any particular reason why C++ doesn't support it?

Community
  • 1
  • 1
madu
  • 5,232
  • 14
  • 56
  • 96
  • 4
    Only the `Func()` overload is in scope - the one that takes zero arguments. Promotion has nothing to do with it. If the other overloads were in scope the `Func(char)` overload would be chosen. – David G Mar 02 '15 at 15:08

2 Answers2

4

All functions (and named entities in general) need to be declared before use. You've only declared the overload with no parameters (which is what an empty parameter list means in C++) when you try to call it with an argument in main.

You have the correct declarations at the start of the file, but for some reason the one you need is commented out. Uncomment them and it's fine.

I just saw that this kind of prototype-less declarations are part of C standard, NOT C++. Any particular reason why C++ doesn't support it?

Because C++ supports overloading. Overload resolution happens at compile time, where the function is called, and candidates can only be considered if the compiler knows they exist - that is, if they've been fully declared so that the compiler can match their signatures against the argument types of the function call.

In C, the compiler knows which function you mean, whether or not it knows the parameter types, since it's the only one with that name. Such declarations are merely dangerous, removing type-checking from the argument types and opening the door to all manner of bugs.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

C++ has never supported prototype-less function declarations. The empty argument list in C++ means no arguments, not a lack of prototype.

The reason is that C++ has type-safe linking, and that just doesn't work if you don't have a prototype. And C++ has type-safe linking because that's just a good idea and reduces bugs. (You can read Design&Evolution of C++ for more details.)

Argument promotions in C++ exist only in calls to true variadic functions, i.e. those declared with a ... in the argument list.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157