0
Default arguments in C ?
Hi every one I am programming a piece of hardware that can only be programmed in C I want to have a function that has default arguments is there a way to do this in C
2 Respostas
+ 2
There isn't a way for defaults. Depending on what you are looking for, you might manage the effect with varying number of arguments.
+ 2
Do you mean _default number of args_ because C doesn't support overloading.
...Or do you mean _default values_ which C doesn't support either? In both cases not, but there's a hacky way.
This behaviour can be emulated to a point. If your function uses global array instead of parameters, you can have the function check the number of non-blank items to determine the function's "signature" and use it for any default values. Also, you can always "reset" the array just before exiting the function to the default values.
It's a hack in both cases, but a relatively clean and manageable solution to overloading and default values. Globals are not evil if not abused, they can make code simpler and even faster.
May I just add this method is less cumbersome than variadic functions like printf and portable (doesn't require C11 special features or compiler-specific features).