I'm pretty new to programming and can't really understand why I can't just declare argument types the same way I do with normal variables and have to declare the type again and again.
I mean, why must I:
Func(int a, int b, float c)
instead of
Func(int a, b, float c)
?
As long as they're the same type, of course.
If it is possible, please tell me how.
Thanks in advance.
@0x499602D2: If parameter declarations were more closely analagous to object declarations, then void f(int a, float c, d) would presumably be equivalent to void f(int a, float c, float d). The language could have made this work correctly and consistently. It just didn't. – Keith Thompson
This answered my question best. but it's a comment...
Some functions are designed to return values, while others are designed for other purposes. We pass arguments in a function, we can pass no arguments at all, single arguments or multiple arguments to a function and can call the function multiple times.
Yes, we can define multiple methods in a class with the same name but with different types of parameters.
In Python, by adding * and ** (one or two asterisks) to the head of parameter names in the function definition, you can specify an arbitrary number of arguments (variable-length arguments) when calling the function.
This is why:
Everything has some rules or works on contracts. In theory you could write a C compiler that will instead of:
func(int a, int b)
take this:
func(int a, b)
that would be perfectly fine.
but
Creators of C decided that every single formal argument has to have its type attached to it hence we have it today. It's just a convention which you must follow.
And you must follow it as C/C++ parser is expecting you to do it this way otherwise it will not understand you.
Similarly your question:
Is there a way to declare multiple function arguments with one type?
may theoretically be written this way:
there multiple a way Is to declare function arguments with one type?
If you agree with someone to construct questions this way you must follow this contract - period.
That's how the syntax is. I don't know of there is a "reason", but in (old) C arguments without an explicit types would default to int (and there was even a syntax to provide types after the closing parenthesis), so I'm not sure this could be relaxed safely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With