Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for number of arguments for subroutines in C

I've recently started working on developing APIs written in C. I see some subroutines which expect 8(Eight) parameters and to me it looks ugly and cumbersome passing 8 parameters while calling that particular subroutine. I was wondering if something more acceptable and cleaner way could be implemented .

like image 461
Amit Avatar asked Jul 02 '10 13:07

Amit


People also ask

How many arguments should a function have C?

Neither the C nor C++ standard places an absolute requirement on the number of arguments/parameters you must be able to pass when calling a function, but the C standard suggests that an implementation should support at least 127 parameters/arguments (§5.2.

What is the ideal number of arguments for a function?

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification - and then shouldn't be used anyway.

How many arguments is too many in a function?

Functions with three arguments (triadic function) should be avoided if possible. More than three arguments (polyadic function) are only for very specific cases and then shouldn't be used anyway.

How many parameters are in a subroutine?

A subroutine can have one, more than one, or no parameters.


1 Answers

If a number of arguments can be logically grouped together you may consider creating a structure containing them and simply pass that structure as an argument. For example instead of passing two coordinate values x and y you could pass a POINT structure instead.

But if such a grouping isn't applicable, then any number of arguments should be fine if you really need them, although it might be a sign that your function does a little too much and that you could spread work over more, but smaller functions.

like image 194
Joey Avatar answered Oct 04 '22 05:10

Joey