I stumbled on the following stuff in someone's source code in C:
typedef struct {
u32 reg;
} reg_t;
#define _REG(r) ((const reg_t){.reg=(r)})
#define REG_A _REG(123)
#define REG_B _REG(456)
...
and it makes me wonder: what might be the purpose of such sorcery? Couldn't just a simple numerical constant be defined instead? Why do they define a structure, with just one member, and then use C99's compound literals to initialize it? Is there some obscure benefit that I'm missing here that requires such syntax?
(At first I was puzzled by that syntax as well, until I found out that it's a C99 extension. I knew about the "designated initializers", but I didn't know that they can be used this way, with something that looks like a type cast, but from what I understood, it's just C99's way of doing something akin to C++'s constructors. Still, I don't know why do they use this trick here in particular, and what would happen if they didn't.)
(type){values}
is a compound literal, and.member=value
is the designated initializer. And they are not just C99 extensions; they are integral part of C99 and above.REG_A
orREG_B
are used. But it looks like this is an attempt to increase type safety when dealing with some registers, which are presumably of typereg_t
.reg_t
orconst reg_t
. So there is indeed a possibility that they used this trick to avoid implicit conversions from regular numeric constants and for better type safety and readability. As for corrections: in order to correct, there must be something that needs it. I see no such thing in my post.