C's designated initializers give us named arguments

(quuxplusone.github.io)

76 points | by joshcsimmons 3 days ago ago

48 comments

  • quietbritishjim 2 days ago ago

    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.
    • SuperV1234 2 days ago ago

      You can write `foo({.x = 1, .y = "xyz"});` in C++20.

      https://gcc.godbolt.org/z/srz4P6nzM

      • quietbritishjim 2 days ago ago

        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).
      • stephencanon 2 days ago ago

        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.

        • Someone 2 days ago ago

          > 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.

          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...)

        • pjmlp 2 days ago ago

          C doesn't have constructors, and field initialisation order matters.

          • adrian_b 2 days ago ago

            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.

            • neonz80 a day ago ago

              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.

              • adrian_b a day ago ago

                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.

                • quietbritishjim a day ago ago

                  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.

            • im3w1l 2 days ago ago

              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.

            • pjmlp 2 days ago ago

              Rice theorem enters the room.

              The compiler doesn't read binary libraries, nor can foresee all possible side effects for each field constructor, or base classes.

              • adrian_b a day ago ago

                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.

                • pjmlp a day ago ago

                  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.

                  https://godbolt.org/z/66TjPK49b

          • sorrywhat 2 days ago ago

            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.

            • jbarberu 19 hours ago ago

                  Point foo = {
                     .y = foo(),
                     .x = bar(),
                  };
              
                  calls foo(), sets x to it, calls bar(), and sets y to it. And
              
              I think you meant the other way around...
            • radiospiel a day ago ago

              I am pretty sure that the execution order of the calls to foo() and bar() is not specified, regardless of how you want to order the assignment.

            • pjmlp a day ago ago

              International standards aren't made for a single person, nor single compiler implementation.

              • 19 hours ago ago
                [deleted]
      • cocoto 2 days ago ago

        Sure but now you have to make sure the order of the members is correct.

      • xKingfisher 2 days ago ago

        And this form is much safer if you're using span/string_view members in your struct.

    • beached_whale 2 days ago ago

      Aggregates get RVO into members too, so say .y is a std::string then "xyz" is going to construct in place.

    • im3w1l 2 days ago ago

      I would prefer the java style FooInvocation().x(1).y("xyz").run() over that

  • binaryturtle 2 days ago ago

    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.

    • robinsonb5 2 days ago ago

      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); )

      • flohofwoe 2 days ago ago

        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:

            int attributes[] =
            {
                GLX_RED_SIZE, 8,
                GLX_GREEN_SIZE, 8,
                GLX_BLUE_SIZE, 8,
                GLX_ALPHA_SIZE, 8,
        
                GLX_DEPTH_SIZE, 24,
                GLX_STENCIL_SIZE, 8,
        
                GLX_DOUBLEBUFFER, True,
        
                None
            };
        
        Of course OpenGL is a bit later than AmigaOS, but not by much :)
        • kevin_thibedeau a day ago ago

          XView worked similarly. It had a small handful of variadic functions for its API that you passed lists of arguments into.

    • flohofwoe 2 days ago ago

      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':

      https://docs.vulkan.org/refpages/latest/refpages/source/VkDe...

    • icedchai 2 days ago ago

      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.

  • cryptonector 2 days ago ago

    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.

  • s3graham a day ago ago

    Love it too! https://mstdn.social/@sgraham/112486947826240650

    As I mentioned there, I think it's even cooler when you collapse the "constructor" macro, and tag to be the same name.

  • david2ndaccount 2 days ago ago

    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...

    • nix0n 2 days ago ago

      If you don't need defaults, you don't need the macro.

      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.

  • cozzyd 2 days ago ago

    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.
  • robmccoll 2 days ago ago

    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.

    • cryptonector 2 days ago ago

      And go take a look at:

      - 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

    • sunrunner 2 days ago ago

      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?

      • mtklein 2 days ago ago

        sort of like this,

            #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.
        • bluGill 2 days ago ago

          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.

        • sunrunner 2 days ago ago

          Ah okay, thanks! Surprisingly more readable as there's no loop (in this example...)

          • lelanthran 2 days ago ago

            If you really want readable, search for the protothreads library

  • jcalvinowens a day ago ago

    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").

  • flohofwoe 2 days ago ago

    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:

        state.pip = sg_make_pipeline(&(sg_pipeline_desc){
            .layout = {
                .attrs = {
                    [ATTR_texcube_pos].format = SG_VERTEXFORMAT_FLOAT3,
                    [ATTR_texcube_color0].format = SG_VERTEXFORMAT_UBYTE4N,
                    [ATTR_texcube_texcoord0].format = SG_VERTEXFORMAT_SHORT2N
                }
            },
            .shader = shd,
            .index_type = SG_INDEXTYPE_UINT16,
            .cull_mode = SG_CULLMODE_BACK,
            .depth = {
                .compare = SG_COMPAREFUNC_LESS_EQUAL,
                .write_enabled = true
            },
            .label = "texcube-pipeline"
        });
    
    (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...)

    • aktau 7 hours ago ago

      That is beatiful.

      I had never seen array designated initializer combined with the struct variant. Great foresight of whomever thought to make these features so flexible and composable:

        .attrs = {
          [ATTR_texcube_pos].format = SG_VERTEXFORMAT_FLOAT3,
          [ATTR_texcube_color0].format = SG_VERTEXFORMAT_UBYTE4N,
          [ATTR_texcube_texcoord0].format = SG_VERTEXFORMAT_SHORT2N
        }
  • nixpulvis a day ago ago

    Treating named arguments as structs is my proposal for Rust as well: https://nixpulvis.com/ramblings/2026-10-19-anonymous-struct-...

  • cesaref a day ago ago

    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.

    • astrobe_ a day ago ago

      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.

  • coldpie 2 days ago ago

    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.