How to omit certain arguments for which standard values were given in the function prototype parameters?

Asked

Viewed 457 times

1

How to omit specific arguments of the function in C++ for which standard values were given in the function prototype parameters?

E.g. how to omit the second argument (b = 4 by default), passing the first and last?

#include <iostream>
using namespace std;

int SOMA(int a=2, int b=4, int c=5)
{
  int s;
  s=a+b+c;
  return (s);
}

int main ()
{
    //b e c omissos
  cout << SOMA(1) << '\n'; //10
    //b omisso
  cout << SOMA(1,,2) << '\n'; //erro

  return 0;
}
  • I believe this is a feature that only languages that allow calling the function with named parameters have, such as the Python.

2 answers

2


There are even some techniques to allow this but everything so complicated, need so much work and in general has processing cost that is not worth the effort, it is much simpler to use the value.

C++ does not allow you to omit an argument in the middle, after omitting an argument, all of the following must be omitted as well. And obviously after having a parameter with value default can’t have one without a value default.

0

Standard Arguments for Functions

C++ allows a function to associate a default value to a parameter when no corresponding argument is used in the call of function.

void f (int i = 1)
{
.
.
}

On the call to use

f(10) // recebe 10 como parâmetro
f() // recebe 1 que é o valor default.

Another example:

void myfunc (int i=5, double d=1.23);
myfunc (12, 3.45) // usara os valores 12 e 3.45
myfunc (3) // usara como myfunc( 3, 1.23)
myfunc () // usara como myfunc(5, 1.23)

Omitting the first parameter and passing only the second parameter is not allowed. Only can be omitted from right to left. If you have 5 parameters for yourself omit the third, also omit the fourth and the fifth.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.