Hacker News new | ask | show | jobs
by wott 1781 days ago
You can somewhat fake it by replacing your functions parameters list with a single struct parameter.

    struct bar_arguments {
       int a, b;
    };
    int bar(struct bar_arguments args) { return 2*args.a + args.b;}

    #define bar(...) bar((struct bar_arguments) {__VA_ARGS__})

    // usage (will print 32 three times)
    printf("%d\n", bar(10, 12));
    printf("%d\n", bar(.a = 10, .b = 12));
    printf("%d\n", bar(.b = 12, .a = 10));

The main drawback is that all parameters are now optional: it will not complain if you forget to assign all parameters, it will silently set them to 0 :-/

    printf("%d\n", bar(10));
    printf("%d\n", bar(.a = 10));
    printf("%d\n", bar(.b = 12));
will print 20, 20 and 12.

You can change those "default values", but then calling the function with regular positional parameters is impaired :-/