Question:
c++, user defined functions variable input and other options?
Peter-MedEng
2015-08-06 07:07:11 UTC
1.
How can I make a function with variable input? I seen non-user defined functions where it works with 1, 2 or more inputs
for example function1(input1, input2, input3), function1(input1). If i don't type in all input in user defined functions I get an error :/ but sometimes I don't need all inputs.

2.
How can i make a user defined function with the input being automatically detected as a string or int. For example I don't want
function1(int input1, string input2) but function1(input1 OR input2).

thanks for help in advance ^^
Four answers:
?
2015-08-06 09:12:27 UTC
Functions which take a variable number of arguments are called Variadic functions. Here is the Wikipedia page, with a C example: https://en.wikipedia.org/wiki/Variadic_function



For a discussion of how C and C++ differ, try looking at this stackoverflow.org discussion: http://stackoverflow.com/questions/1579719/variable-number-of-parameters-in-function-in-c
DrZoo
2015-08-06 07:26:12 UTC
For your first question, you can use parameter default values for your function. function1(input1, input2 = 0, input3 = 0). You then do not have to pass in a value, but 0 will be used as the values of the other variables. The way you have your question worded, they may be other alternatives to passing your values to a function, like an array.



For question two, you can use function templates:

template

void f(T s)

{

std::cout << s << '\n';

}
SAINT IKER
2015-08-06 09:45:52 UTC
Just to add to rogers answer you could also look into templates for problem #2



Overloaded functions:



void doThis(int a)

{

//do something...

}

void doThis(string a)

{

//do something...

}



OR



Templates



Template (typename T)

void doSomething(T a)

{

//do something....

}



Remember for problem #1



void doThis(int a, int b = 10) //allowed

{

//do something...

}

void doThis(int a = 10, int b) // not allowed

{

//do something...

}

void doThis(int a, int b = 10, int c = 10) //allowed

{

//do something...

}



Needs to from the rightmost parameter
?
2015-08-06 08:35:31 UTC
"but sometimes I don't need all inputs."

look into default parameters



int function1(int a, int b=1,int c=2){...}

http://en.cppreference.com/w/cpp/language/default_arguments



for the second question you can use overloaded functions

int funct2( int a){...}

int funct2( string b){...}



http://www.tutorialspoint.com/cplusplus/cpp_overloading.htm


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...