I want to make a function that has parameters like here
void example(int x, int y, int z);
but I dont have to put z
in there like this example(34, 21);
is that possible in C++?
Asked
Active
Viewed 1,048 times
2
-
And when this `z` is not there, what do you expect all the code in the function, that references `z`, to do? – Sam Varshavchik Oct 01 '21 at 12:06
-
write two functions of the same name or provide a default value for z – Abel Oct 01 '21 at 12:07
-
6they are called [default arguments](https://en.cppreference.com/w/cpp/language/default_arguments) – 463035818_is_not_an_ai Oct 01 '21 at 12:09
-
TLDR: `void example(int x, int y, int z=0){}` – OrenIshShalom Oct 01 '21 at 17:07
2 Answers
3
You basically have two options
- Create a overloaded function that takes 2 parameters. So you would have
void example(int x, int y, int z)
and
void example(int x, int y)
- Assign default value to z
void example(int x, int y, int z = 0)

AverageProgrammer
- 167
- 3
- 15
0
The way to use undefined amount of parameters is to use ellipsis. For further read i recomend to look through https://en.cppreference.com/w/cpp/language/variadic_arguments To implement it just google how to use c++ ellipsis and thats it!

korzck
- 198
- 9
-
1
-
-
Only in C API like `printf`. In real C++ API you do not have it. C++20 introduced `std::format` which uses variadic templates to ensure it is type safe and fast. – Marek R Oct 01 '21 at 13:23
-
Anyway if you really think this is a good idea, try to use it with such simple case like this question. You will see how many problems it introduces. – Marek R Oct 01 '21 at 13:27