0

I want to know how do u declare a function with definite arguments. It's said to be good practice to put the function declaration at the beginning , before the main() function and then its definition, but in this case the compiler gives me an error, becase it's like if it doesn't see the formal arguments.

#include <iostream>
using namespace std;

void function(int i=1, char a='A', float val=45.7);

int main()
{
  function();
  return 0;
}

void function(int i = 1, char a='A', float val=45.7)
{
  cout << "i: " << i << endl;
  cout << "a: " << a << endl;
  cout << "val: " << val << endl;
}

I tried to insert the formal arguments in the declaration, but it doesn't work.

2 Answers2

2

You can put predefined arguments either in the forward declaration or in the function parameter, but not both

If your function has a forward declaration, you really should only have predefined arguments in the forward declaration, not in the function parameter.

Change that to:

void function(int i, char a, float val)
{ 
     // you shouldn't use using namespace std;
     std::cout << "i: " << i << '\n'; // notice the use of newline character instead of std::endl
     std::cout << "a: " << a << '\n';
     std::cout << "val: " << val << '\n';
}
1

here is the way to initialise the function args to default values. You dont need to pass default args in defination. They should be given only in the declaration itself.

#include <iostream>
using namespace std;

void function(int i=1, char a='A', float val=45.7);

int main()
{
  function();
  return 0;
}

void function(int i, char a, float val)
{
  cout << "i: " << i << endl;
  cout << "a: " << a << endl;
  cout << "val: " << val << endl;
}

Now, this code will work like a charm. Link to working example -> http://cpp.sh/4j7lx

GeekyCoder
  • 138
  • 11