Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign value to struct type constants in C

I have following code which I guess is assigning a value to constant struct

in header file:

struct madStruct {
    uint8_t code;
    uint8_t cluster;
};
typedef struct madStruct MadStruct;

and in C file

const MadStruct madStructConst = {
    .code = 0x00,
    .cluster = 0x01,
};

I would like to know what what does this code supposed to do?

This code does not compile in Visual Studio C++ 2010, how can I convert it so I can compile in both MingW and Visual Studio C++ 2010?

like image 397
AaA Avatar asked Dec 10 '25 03:12

AaA


1 Answers

The syntax was introduced in C99 and allows the name of the members to be explicitly specified at initialisation (the .code and .cluster are known as designators). The initialisation assigns the value 0x00 to the code member and value 0x01 to the cluster member.

VC only supports C89, so compiliation fails. As the struct only has two members and both are being initialised you can replace the initialisation with:

const MadStruct madStructConst = { 0x00, 0x01 };

without the designators the members are initialised with the specified values in the order that the members are defined in the struct. In this case code is assigned 0x00 and cluster is assigned 0x01, the same as the initialisation with the designators.

like image 56
hmjd Avatar answered Dec 11 '25 18:12

hmjd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!