2

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++?

wovano
  • 4,543
  • 5
  • 22
  • 49
xfajk X
  • 151
  • 1
  • 1
  • 7

2 Answers2

3

You basically have two options

  1. 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)
  1. Assign default value to z
void example(int x, int y, int z = 0)
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
    this is C feature considered harmful. – Marek R Oct 01 '21 at 13:16
  • @MarekR anyway it is used in many STD C/C++ functions – korzck Oct 01 '21 at 13:21
  • 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