How to set a default value to function parameters in C++

2 Answers

0 votes
#include <iostream>

void f(int a = -1) {
    std::cout << a << std::endl;
}

int main() {
    f();
    f(30);
}


/*
run:

-1
30

*/

 



answered Jan 28, 2025 by avibootz
0 votes
#include <iostream>
#include <string>

void f(std::string country = "No Country") {
    std::cout << country << std::endl;
}

int main() {
    f();
    f("USA");
    f("Canada");
}


/*
run:

No Country
USA
Canada

*/

 



answered Jan 28, 2025 by avibootz

Related questions

1 answer 89 views
1 answer 115 views
1 answer 116 views
1 answer 100 views
1 answer 117 views
2 answers 117 views
2 answers 126 views
...