Re:Learning that you can use unions in C for grouping things...
by saagarjha on Sunday August 01, 2021 @07:29PM
(#28031246)
I suspect that to many C++ programmers, most initializations of structs have unpredictable side effects because of how complex they are ;)
Re:Learning that you can use unions in C for grouping things...
by wott on Sunday August 01, 2021 @09:04PM
(#28031844)
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 :-/
Re:Learning that you can use unions in C for grouping things...
by gumby on Monday August 02, 2021 @02:49AM
(#28033610)
> The only explanation I saw was that C++ standards guys were horrified by the idea of unpredictable side effects as a result of initialization of a struct.
I don't understand. How would struct or class initialization be any different from simply doing, say, `for (auto& a : { x, y, z }) frob (a);` which is perfectly legal?
Re:Learning that you can use unions in C for grouping things...
by Gibbon1 on Tuesday August 03, 2021 @03:40PM
(#28053218)
I didn't mention. I think the thought was with designated initializers the order of initialization is what? The order of the elements of the struct? Or the order where it's initialized. In C probably matters little as side effects are usually blatant. C++ I think cryptic side effects are common.
I think C++ though is adding them.
What I'd like in c is designated function parameters.