by flohofwoe · 5y ago · 0 comments
A workaround in C99 (and more limited in C++20) is to use a single struct which bundles all the function parameters, and then use designated initialization, this also makes function paramaters optional, and at least in C99 they can appear in any order:
my_func((my_struct_t){
.a_bool_flag = true,
.another_bool_flag = false,
.a_string = "Hello World"
});
This is mainly useful for functions which take many parameters. One downside in C99 (but not C++) is that there's no way to define default values for struct items (other than zero/false). function f(; a, b)
a+b
end
Default values are optional. This can only be called with named arguments like f(; a=5, b=7). Unfortunately the separation isn't required to be explicit when calling the function, so calling f(a=5, b=7) also works. Generally calling functions is extremely permissive (e.g. a function with two positional and two keyword arguments function g(a, b=5; c, d=8) can be called with keywords and positions interleaved g(1, c = 7, 5)), leading to potential confusion at the call site. Our coding guidelines enforce separation of positional and keyword at call sites, and with that additional restriction I have found Julias behaviour in this regard very pleasant. E.g.: calc_something(a, b; bool_flag=true)
is the best style for this type of thing that I have seen. my_func(/*a_bool_flag*/ true, yadda);Totally agree this is better to be in the language proper so we don't need this extra tooling.
https://pdimov.github.io/blog/2020/09/07/named-parameters-in...
myFunc({
aBoolFlag : true,
anotherBoolFlag : false,
aString : "Hello World"
});
const myFunc = ({ aBoolFlag, anotherBoolFlag, aString }) => { /* do something with them... */ }; interface IFunctionParameters {
userId: string;
name: string;
age: number;
}
const example = ({userId, name, age}: IFunctionParameters) => {...}