0

I'm trying to write a program that will ask the user to enter "how many numbers they want to add", then add all the numbers in a function. I want to create the adding function with a dynamically allocated number of parameters such that there are X "int num{someNumber}," where X is the number of numbers the user wants to add. My current code (very rough) is:

  int var = 0;
string multiply(int num);
void testing(int num, multiply(var));
int main(){}
void testing(int num, multiply(var)) {
}//end testing

//Function to append int num{num} to string
string multiply(int num) {
    string declaration = "null";
    for (int num = 0; num <= var; num++) {
        declaration.append("int num" + num);
    }//end for 
    return declaration;
}//end multiply

I realize that there is still work to be done, like removing the last comma, for instance, but is it possible to use a string in a function definition to declare X int num parameters?

  • You probably want to read the numbers, put them into a `std::vector`, then have the function add the numbers in the vector. – Jerry Coffin Mar 06 '18 at 22:27

1 Answers1

0

Another similar question already exists, check out its answer: Variable number of arguments in C++?

While it is definitely possible to define functions with a variable number of arguments, you may also want to consider defining your program iteratively or recursively instead.

Functions with a variable number of arguments can be very useful at times, but can also lead to strange edge-cases like scanf("%d") which wants to scan an integer, but is not given an address to place it into. The function call is allowed, and the scanned integer overwrites a (possibly important) location in memory.

  • A variadic function (probably) won't be useful here. A variadic function lets different calls sites pass different numbers of arguments--but each call site passes one number of arguments specified in the call. What he seems to want is a single call site that passes a variable number of arguments. C simply doesn't support that (directly). – Jerry Coffin Mar 07 '18 at 02:08