I always thought Amiga's "tag list" concept was really nice. You easily could extend the API w/o breaking the ABI, which was essential for its shared library concept. And it essentially gave you named arguments too.
A somewhat similar extension concept (in the sense of: allow to extend the API without breaking ABI) still exists in some C APIs, for instance in Vulkan each struct starts with an `sType` tag and a `pNext` pointer, this allows to build 'extension struct chains':
Yes indeed. I've often wondered where it came from - did they invent it, or was it inspired by something on another platform?
(For the uninitiated, taglists are freeform lists of TAG / value pairs, which you would typically supply through varargs functions - something like OpenScreenTags(&newscreenstruct,SA_WIDTH,320,SA_HEIGHT,256,SA_DISPLAYID,myscreenmode,TAG_DONE); )
IMHO the main problems with this idea is that it isn't type-safe and it's wasting a lot of stack space for the tags.
> I've often wondered where it came from
Don't know but the other place where I've seen this idea is when initializing OpenGL contexts on some platforms. This involves defining attribute key/value pairs like this:
Yes, that was neat at the time: an array of key/value structs for extensibility. The "keys" were a #define somewhere in the header files. The original Amiga APIs (before OS 2.0) did not have tag lists and it was painful to work with.
I started learning C on an Amiga with OS 1.3, then moved to a 2.0 machine. Fun times.
It's fun watching people rediscover this every so often. If you like this sort of thing, go check out creating generator functions using a switch embedded throughout your function. You can wrap it in macros to end up with a nice yield keyword emulation.
Is this essentially the mechanism behind Duff's Device (switch cases being better thought of as line-oriented jumps instead of structured blocks) but generalised?
#include <stdio.h>
static int generator(int st, float *out) {
switch (st++) {
case 0: *out = 1.0f; return st;
case 1: *out = 7.0f; return st;
case 2: *out = 9.0f; return st;
}
return 0;
}
int main(void) {
float f;
for (int st = 0; (st = generator(st, &f));) {
printf("generator yielded %g\n", (double)f);
}
return 0;
}
but notice you also have the option to make the state static rather than a parameter, which gives you more encapsulation of your state machine at the cost of being way less flexible in terms of threading and reentrance.
That isn't Duff's device. Duff's device has NO return/break, it intentionally falls through to the next case statement. It is an interesting optimization that is only rarely useful (and probably even less useful in these days of optimization compilers) that everybody misunderstands.
C++'s version of this is more verbose but still sometimes worth it: make the caller instantiate the struct and initialise it as separate statements:
FooParams fooParams; // Gives sensible defaults to all members
fooParams.x = 1;
fooParams.y = "xyz";
foo(fooParams);
It doesn't work so well if you want to move construct things because you need to move at least twice: once when moving the value into the member, then you need to move the whole struct to the function argument `foo(std::move(fooParams))`. If you want it to copy something but avoid unnecessary copying then it's even more annoying because you need to move to the function argument still which looks odd when your goal is to copy overall.
As is usual for C++, the committee made arbitrary changes from what C had already laid out that made the feature worse. In particular, C++ requires that the fields appear in order, which means you cannot use it to do what the linked page shows.
This isn't usually a huge deal, because C++ gives you other ways to have overloaded functions and default parameters, but it is sometimes mildly annoying.
This should be handled by the compiler, which shall ignore any overridden initializers and then the structure fields shall be initialized in some specified order, either the order from the definition of the structure or the initializer order.
So this is not a valid excuse for the choice made by the C++ specification.
Sounds like it could lead to subtle bugs if initializers are run in an unexpected order. By not allowing that they prevent such bugs. And if it turns out to be unproblematic and a consensus emerges on which order should be used by such code they can always add it in a later version.
But the programmers must be able to foresee all possible effects of a different initialization order, supposing that it matters, otherwise they cannot write correct code.
Normally classes/structures should be defined in such a way that the order of initializing the members does not matter.
If the order of initialization matters, because there exists a really good reason to make the values of some members dependent on the values of other members (which adds superfluous information to the structure, but which might save some execution time), then I think that any programming language that allows this must enforce a unique order of initialization, i.e. the member order from the structure definition. Otherwise there would be no way to guarantee that when a constructor for a member accesses another member, that member does not contain uninitialized memory, because it has not been constructed yet.
I am not sure whether there exists a reasonable way in modern C++ to access a member of a class/structure from the constructor or destructor of another member, so unless one makes special efforts to circumvent this, e.g. by using some global variable that points to the structure whose constructors or destructors are currently executed, I think that in C++ you cannot easily define a class/structure where the order of executing the member constructors and destructors matters.
If you want for some members to depend on others, that can be easily done only in a constructor of the entire structure, where all members are visible, not in the constructors of the members.
Of course there is, you can do that in initializtion lists, passing fields from one field into the other.
This is a tiny example, with constructor initialization lists, which is possible since C++ARM, and I am not getting creative with what is actually possible.
One problem with this is if one of the initializers throws an exception. The already constructed members must be destroyed. With an arbitrary initialization order the compiler will have to create different code for each order used and make sure it is this code that is called during unwinding.
Like I have said, a possible choice in the language specification in that whenever a set of structure members are initialized, e.g. in a function invocation, the initializations shall be done in the order from the structure definition.
This would solve your problem.
Nonetheless, I do not see why in any correct code the order of member initialization may be relevant, even when different initialization orders can produce different results, because the values of some members depend on the values of other members. If the destructor of some member accesses another member that may have already been destructed, or not, there must be a way to determine this, e.g. destructing a member should replace it with some default value for that type, e.g. a zero or a NaN or a null pointer.
Accessing other members that have already been destructed may happen also in other contexts than during the explicit initialization of the structure, so it must never lead to unpredictable behavior.
That would solve one problem, and create another one: fields get initialised in a different order depending on the caller. You have a valid point but don't pretend that there's no trade off at all.
That doesn't stop the C++ committee from doing the obvious, trivial and correct thing.
Point foo = {
.y = foo(),
.x = bar(),
};
calls foo(), sets x to it, calls bar(), and sets y to it. And
Point foo = {
.x = bar(),
.y = foo(),
};
calls bar(), sets x to it, then calls foo(), and sets y to it.
I'm sure you can give me the reason they didn't do that, and it will be something like "this conflicts with LRR-value warp semantics when invoked from concept inside a consteval coroutine" or something equally stupid, but the problem is I don't care. This is a good piece of syntax sugar (and the only reason I use C++20) and it's being handicapped by insane features that I don't use and don't care about.
> the committee made arbitrary changes from what C had already laid out that made the feature worse. In particular, C++ requires that the fields appear in order
I don’t see how that’s an arbitrary change. C++ initializes members in order of the definition of a class.
I was aware of this but I thought it didn't work if you had any inline default initialisers i.e.
struct FooParams {
int x = getX();
const char* y = getY();
};
It turns out this was an issue all the way back in C++11, which didn't even have designated initialisers, but inline initialisers like this prevented the struct from being an aggregate, which meant you couldn't write FooParams{1, "y"}. That was fixed in C++14 (as I've just discovered).
I proposed something like this ~20 years ago in the context of GSS-API, where there are several functions with lots of arguments but where most arguments have reasonable defaults, so one could use named arguments for all the values that one must give and not mention the others that get default values. But I wasn't serious about it.
I both love & hate this. I would genuinely consider using it in my own projects, and also I would be very pissed off if I encountered it in someone else's project. Brilliant.
Tbh I would skip all the preprocessor magic proposed in the article and just go for plain C99 'option bag struct' arguments, the called function only needs to be aware that "zero means default".
I've been using this style for almost 10 years now in the sokol headers, and it still feels like the right thing to do and actually more ergonomic than most other languages for initializing complex structs, e.g. see here for creating a 3D render pipeline object with dozens of creation options, but most of them keeping their default values:
...this code snippet also makes use of C99 features that are not available in C++20 though (or most other languages), and it's really remarkable how well designed the C99 designated init feature as a whole is (even though it was an afterthought) and how badly its individual subfeatures were understood by most later languages (basically, only Odin got it "mostly right": https://github.com/floooh/sokol-odin/blob/7d47a31cad83a26ba1...)
The idiom I usually use is to define a DEFAULT_FOO_PARAMS like
struct foo { int Z; int A; double E, double v };
#define DEFAULT_FOO_PARAMS .Z = 1, v = 3e8
foo_fn ( &(struct foo){ DEFAULT_FOO_PARAMS, .Z =2, .A = 4, .E = 1 });
But I do sort of wish there was a language-supported way to set defaults for a designated initializer in the struct definition (like C++ default values) to avoid having to write DEFAULT_FOO_PARAMS there.
I always considered this kind of a hack, needing to wrap the actual function call with a function-like macro. Moreover, you’re now using a different calling convention with passing a struct instead of basic types which can be less efficient. I wish C would add actual named arguments like I added in my DrC project: https://github.com/drpriver/DrC/blob/master/EXTENSIONS.md#na...
I do wonder how many times setting the same member twice is a bug rather than a feature. I can imagine quite a bit of copy/paste leading to errors like this.
I also wonder what happens when you forget to give a mandatory parameter which has no default... Yes, that's why this has been possible for a long time but barely anyone uses it : it's a footgun.
The macro is cute, but passing structures by value like that is going to cause real measurable overhead where the functions don't get inlined (the author sort of admits this I guess by calling it "heavyweight").
binaryturtle | 7 hours ago
flohofwoe | 5 hours ago
https://docs.vulkan.org/refpages/latest/refpages/source/VkDe...
robinsonb5 | 5 hours ago
(For the uninitiated, taglists are freeform lists of TAG / value pairs, which you would typically supply through varargs functions - something like OpenScreenTags(&newscreenstruct,SA_WIDTH,320,SA_HEIGHT,256,SA_DISPLAYID,myscreenmode,TAG_DONE); )
flohofwoe | 5 hours ago
> I've often wondered where it came from
Don't know but the other place where I've seen this idea is when initializing OpenGL contexts on some platforms. This involves defining attribute key/value pairs like this:
Of course OpenGL is a bit later than AmigaOS, but not by much :)kevin_thibedeau | 4 hours ago
icedchai | 5 hours ago
I started learning C on an Amiga with OS 1.3, then moved to a 2.0 machine. Fun times.
robmccoll | 7 hours ago
sunrunner | 7 hours ago
mtklein | 7 hours ago
sunrunner | 6 hours ago
lelanthran | 6 hours ago
bluGill | 6 hours ago
cryptonector | 5 hours ago
- the old Icon to-C compiler
- PuTTY's co-routines (and Simon Tatham's essay on C co-routines[0])
[0] https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
quietbritishjim | 7 hours ago
SuperV1234 | 6 hours ago
https://gcc.godbolt.org/z/srz4P6nzM
xKingfisher | 6 hours ago
stephencanon | 6 hours ago
This isn't usually a huge deal, because C++ gives you other ways to have overloaded functions and default parameters, but it is sometimes mildly annoying.
pjmlp | 6 hours ago
adrian_b | 5 hours ago
So this is not a valid excuse for the choice made by the C++ specification.
im3w1l | 5 hours ago
pjmlp | 5 hours ago
The compiler doesn't read binary libraries, nor can foresee all possible side effects for each field constructor, or base classes.
adrian_b | an hour ago
Normally classes/structures should be defined in such a way that the order of initializing the members does not matter.
If the order of initialization matters, because there exists a really good reason to make the values of some members dependent on the values of other members (which adds superfluous information to the structure, but which might save some execution time), then I think that any programming language that allows this must enforce a unique order of initialization, i.e. the member order from the structure definition. Otherwise there would be no way to guarantee that when a constructor for a member accesses another member, that member does not contain uninitialized memory, because it has not been constructed yet.
I am not sure whether there exists a reasonable way in modern C++ to access a member of a class/structure from the constructor or destructor of another member, so unless one makes special efforts to circumvent this, e.g. by using some global variable that points to the structure whose constructors or destructors are currently executed, I think that in C++ you cannot easily define a class/structure where the order of executing the member constructors and destructors matters.
If you want for some members to depend on others, that can be easily done only in a constructor of the entire structure, where all members are visible, not in the constructors of the members.
pjmlp | 13 minutes ago
This is a tiny example, with constructor initialization lists, which is possible since C++ARM, and I am not getting creative with what is actually possible.
https://godbolt.org/z/66TjPK49b
neonz80 | 2 hours ago
adrian_b | 2 hours ago
This would solve your problem.
Nonetheless, I do not see why in any correct code the order of member initialization may be relevant, even when different initialization orders can produce different results, because the values of some members depend on the values of other members. If the destructor of some member accesses another member that may have already been destructed, or not, there must be a way to determine this, e.g. destructing a member should replace it with some default value for that type, e.g. a zero or a NaN or a null pointer.
Accessing other members that have already been destructed may happen also in other contexts than during the explicit initialization of the structure, so it must never lead to unpredictable behavior.
quietbritishjim | 17 minutes ago
sorrywhat | 4 hours ago
I'm sure you can give me the reason they didn't do that, and it will be something like "this conflicts with LRR-value warp semantics when invoked from concept inside a consteval coroutine" or something equally stupid, but the problem is I don't care. This is a good piece of syntax sugar (and the only reason I use C++20) and it's being handicapped by insane features that I don't use and don't care about.
pjmlp | 4 hours ago
radiospiel | 2 hours ago
Someone | 4 hours ago
I don’t see how that’s an arbitrary change. C++ initializes members in order of the definition of a class.
Making reading order follow that IMO is the right thing to do (and yes, they didn’t do that for class initializer lists (https://en.cppreference.com/cpp/language/constructor: “The order of member initializers in the list is irrelevant”), but that’s widely considered a mistake (https://www.intel.com/content/www/us/en/docs/dpcpp-cpp-compi..., https://learn.microsoft.com/en-us/cpp/error-messages/compile...)
cocoto | 6 hours ago
quietbritishjim | 6 hours ago
im3w1l | 5 hours ago
beached_whale | 4 hours ago
cryptonector | 6 hours ago
coldpie | 6 hours ago
flohofwoe | 6 hours ago
I've been using this style for almost 10 years now in the sokol headers, and it still feels like the right thing to do and actually more ergonomic than most other languages for initializing complex structs, e.g. see here for creating a 3D render pipeline object with dozens of creation options, but most of them keeping their default values:
(or see here: https://github.com/floooh/sokol-samples/blob/11bbe1a6865e93c...)...this code snippet also makes use of C99 features that are not available in C++20 though (or most other languages), and it's really remarkable how well designed the C99 designated init feature as a whole is (even though it was an afterthought) and how badly its individual subfeatures were understood by most later languages (basically, only Odin got it "mostly right": https://github.com/floooh/sokol-odin/blob/7d47a31cad83a26ba1...)
cozzyd | 6 hours ago
david2ndaccount | 5 hours ago
nix0n | 5 hours ago
You still get the advantage of not scrambling the order of your same-typed arguments.
It's more verbose and a different calling convention, but it might be worth it.
cesaref | 4 hours ago
astrobe_ | 2 hours ago
jcalvinowens | 4 hours ago
nixpulvis | 4 hours ago
s3graham | 3 hours ago
As I mentioned there, I think it's even cooler when you collapse the "constructor" macro, and tag to be the same name.