4 ms·
How would you have those work with function pointers?
by JonChesterfield 4y ago
How would you have those work with function pointers?
- habibur 4y agoGood point.
- kangalioo 4y agoI see the point. Out of curiosity, I thought up some approaches: - disallow making function pointers of functions with default params - require explicitly passing all params when used as a function pointer - generate a trampoline function that generates the default params and use that as the function pointer - somehow include the default param values as part of the function pointer type
- unwind 4y agoWouldn't that be just as hard as for any other function? The name of a function (a bit like the name of an array) evaluates to basically a function pointer value, there is little difference between the two calls here: int foo(int a, int b) { return a + b; } int main(void) { printf("Direct: %d\n", foo(1, 2)); int (*ptr)(int, int) = foo; printf("Indirect: %d\n", ptr(1, 2)); return 0; } of course default arguments, if added, would have to be part of the function pointer type as well, making the above: int foo(int a = 1, int b = 2) // NOT REAL CODE, FANTASY SYNTAX { return a + b; } int main(void) { printf("Direct default: %d\n", foo()); int (*ptr)(int a = 1, int b = 2) = foo; // NOT REAL CODE, FANTASY SYNTAX printf("Indirect default: %d\n", ptr()); return 0; } Unnamed function arguments would look silly (`int (ptr)(int = 1, int = 2)`?), but I would be radical then and only support default argument values for named arguments, probably. Edit: fixed a typo in the code, changed in-code comment.
- JonChesterfield 4y agoEncoding the defaults in the type seems valid. Interesting alternative to name mangling + cast to select the variant.