How to create optional parameters in C++?

Asked

Viewed 41 times

-2

In Python it is possible to have optional parameters in a function. It would look something like this:

def soma(n1, n2 = 5):
    return n1 + n2

print(soma(5, 7))

If a second parameter is not passed n2 would receive number 5 and there would be no errors.

I was wondering if it would also be possible to have optional parameters in C++, I even tried to do this (it got awful) using function overload and it worked. Stayed like this:

#include <iostream>
using namespace std;

int soma(int n1, int n2);
int soma(int n1);


int main() {
    cout << soma(5, 7) << endl;
    
    return 0;
}

//Funções
int soma(int n1, int n2) {
     return n1 + n2;
}

int soma(int n1) {
    return n1 + 5;
}

Will have the same result as in the above code done in Python.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

0

C++ has standard arguments (the correct term, see more).

And you can write more succinctly if you want, only it can’t be smaller because C++ is not a language of script by default, so it makes no sense to be saving, although it has C++ implementation that allows you to use as if it were script and some things aren’t mandatory, but it doesn’t make much sense to use it. It has to be very bad in C++ to write a code 10x larger than Python.

#include <iostream>

int soma(int n1, int n2 = 5) { return n1 + n2; }

int main() { std::cout << soma(5) << std::endl; }

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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