4 ms·
It seems it's not so much booleans than using unnamed parameters for option parameters. I find myself using this style in C, it does not prevent a mix-up if som
by cassepipe 2y ago
It seems it's not so much booleans than using unnamed parameters for option parameters.
I find myself using this style in C, it does not prevent a mix-up if someone refuses to use named field designators but it works ok :
typedef struct options_s {
bool toggle_case;
bool strip_whitespace;
} options_s;
char *modify_string(char *str, options_s options)
{
if (options.toggle_case) { /**/ }
if (options.strip_whitespace) { /**/ }
return str;
}
int main(void) {
char str[] = "Hacker News";
modify_string(str, (options_s){ .toggle_case = true, .strip_whitespace = false });
}
Now that I think of it it's probably trivial to forbid the use of struct literals without designated fields in code in a linter
Maybe we get anonymous struct function parameter declaration with C32 ? :D
EDIT:
I have been asking around to people fluent in standardese and if you leave out fields in a struct literal you are guaranteed they will be zeroed-out
- Gibbon1 2y agoIf a giant meteor took out WG14 we might get named arguments in C modify_string(.str=str, .options = { .toggle_case = true, .strip_whitespace = false });
- CoastalCoder 2y agoI've wanted a similar thing for C++. Anyone know what the reasons have been for the language not adopting this?
- wavemode 2y agoIt would cause argument names to become part of the function signature, which would be a significant change to the language, and its ABI.
- wk_end 2y agoWouldn’t you be able to treat this as syntactic sugar - effectively you rearrange the arguments as needed and strip the labels. Doing that wouldn’t necessitate any kind of change to the ABI, I think.
- Gibbon1 2y agoYes it's basically designated initializers for function arguments. Interestingly designated initializers got added to C99 and then WG21 sat on their finger for 20 years before adding it to C++. It can't be anything but the most trivial thing to implement.
- grumbelbart2 2y ago> It seems it's not so much booleans than using unnamed parameters for option parameters It's actually using unnamed parameters at all. While this issue is more frequent for boolean parameters, it can happen for integers or floating point numbers as well. We do a lot of numerics in C, and calls such as optimize_foo (&state, 0.3f, 1e-5f, 1.f); have the same issues as mentioned in the post: Error prone, more difficult to review, more risky to refactor.