0
[Solved] Is it possible for a function to be able to take any number of arguments?
I mean (in python), print("hello", " world", "!") or print with a string each character seperated by coma, print("h", "e", ... ) all works. What im asking is how this works? Is print() overloaded for it to be able to handle up to a limited number of arguments or what? Are we allowed to do such thing for our own functions in both python and C++ (without arrays and function overloading)?
5 Antworten
+ 2
it is call rest and spread property
Check out this:-
https://www.sololearn.com/learn/JavaScript/2978/
+ 2
In addition to what Michi has said,Cpp also has macros (va_list,va_arg,va_start and va_end) that pretty much do the same thing.However I won't go into the details of how they work since there are many resources on the web that handle the topic.
+ 1
Yes it is possible for python also. Read *arts and **kwargs.
def Print(*args):
for i in args:
print(i, end= " ")
print()
Print(1)
Print(1,2,3,4)
+ 1
In c++ it is possible as well:
How it works:
Typically it is programmed recursively, in each step one (or several) of the arguments are processed. Thereby any number of arguments is possible. For example a sum function could call itself with all but the first arguments (as long as there are two or more arguments) and return the result plus the first argument (case only one argument: return the argument).
Can you do it yourself:
With c++ that is indeed possible. It's called 'variadic templates' and as it is not trivial I won't go into detail.
Hope that helped