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

28th May 2020, 4:30 PM
Mustafa K.
Mustafa K. - avatar
5 Antworten
+ 2
it is call rest and spread property Check out this:- https://www.sololearn.com/learn/JavaScript/2978/
28th May 2020, 4:46 PM
Abhay
Abhay - avatar
+ 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.
29th May 2020, 10:44 AM
Anthony Maina
Anthony Maina - avatar
+ 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)
28th May 2020, 4:58 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
+ 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
28th May 2020, 5:00 PM
Michi
Michi - avatar
0
Abhay , $¢𝐎₹𝔭!𝐨𝓝 , Michi thank you very much all
28th May 2020, 5:02 PM
Mustafa K.
Mustafa K. - avatar