Recently, I found myself kind of annoyed by the fact that I couldn’t use the same “initialization” syntax to directly set the values of an existing structure. Extremely trivial, but it bugs me. Is there really a good reason for this limitation?

	typedef struct
	{
	    int x;
	    int y;

	} Doh;

    Doh doh = { 1, 2 };

    // You can't directly re-assign in one step, bummer.
    // doh = { 3, 4 };

    // You need a second struct to use the same syntax.  Yuck.
    Doh d2 = { 3, 4 };   
    doh = d2;

    // Or just do it longhand.  Also yuck.
    doh.x = 5;
    doh.y = 6;

So I dug around to see if there was anything I was missing, and I found designated initializers, the new initialization method available in C99. It doesn’t allow me to directly assign values to an existing structure, but it is interesting:

	Doh doh_set = { 
	    .x = 4,
	    .y = 3
	};
	Doh doh_set2 = { 
	    .y = 3, 
	    .x = 4 
	};
	Doh doh_set3 = { 
	    .y = 3
	};
    Doh set4[]=
    {
        {
            .y  = 1039      
        },
        {
            .y  = 1040,
            .x  = 23
        }
    };

Still not rocket science, but the truly interesting part is that designated initializers are not yet available in C++. At least not today. I tested it with gcc 4.1.2 and Visual Studio 2008 C++ compilers and they do not support it. It may appear in C++0x, but for now, C is definitely no longer a pure subset of C++. For more possible gotchas (and some C99 features that make it more compatible with C++), here’s a quick C99 rundown.

Considering designated initializers are being used in places like the linux kernel, this issue no longer seems trivial. Oh well, code and learn. Hopefully I can go another 10 years(!) before my next snag. For now, back to classes… :>

Leave a Reply