Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to declare multiple function arguments with one type?

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.

  • Can I actually do that and just don't know how to?

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...

like image 823
user2962533 Avatar asked Nov 06 '13 22:11

user2962533


People also ask

Is it possible to pass multiple arguments to a function?

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.

Can we declare a multiple function with same name?

Yes, we can define multiple methods in a class with the same name but with different types of parameters.

How do you add multiple arguments in Python?

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.


2 Answers

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.

like image 65
Artur Avatar answered Sep 30 '22 19:09

Artur


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.

like image 36
remram Avatar answered Sep 30 '22 17:09

remram