I want to typedef
a struct in some way if the machine I am on is Little endian and in some other way if it is Big endian.I tried:
unsigned int i = 1;
char *c = (char*)&i;
if (*c)
{
/*Little endian"*/
typedef struct
{
unsigned long A : A_BIT_SIZE;
unsigned long R : R_BIT_SIZE;
unsigned long E : E_BIT_SIZE;
unsigned long funct : FUNCT_BIT_SIZE;
unsigned long opsource : OPSOURCE_BIT_SIZE;
unsigned long sourcetype : SOURCETYPE_BIT_SIZE;
unsigned long opdest : OPDEST_BIT_SIZE;
unsigned long desttype : DESTTYPE_BIT_SIZE;
unsigned long opcode : OPCODE_BIT_SIZE;
}command_byte;
}
else
{
/*Big endian"*/
typedef struct
{
unsigned long opcode : OPCODE_BIT_SIZE;
unsigned long desttype : DESTTYPE_BIT_SIZE;
unsigned long opdest : OPDEST_BIT_SIZE;
unsigned long sourcetype : SOURCETYPE_BIT_SIZE;
unsigned long opsource : OPSOURCE_BIT_SIZE;
unsigned long funct : FUNCT_BIT_SIZE;
unsigned long E : E_BIT_SIZE;
unsigned long R : R_BIT_SIZE;
unsigned long A : A_BIT_SIZE;
}command_byte;
}
It compiles, but I am not sure whether this is the valid way to define structs inside an if statement. I am also not sure weather it will work when I actually use the struct. Will at work on header files too? what is the correct way to define a struct if condition is met?
Yes, you can use an if
like that. But the typedef command_type
can only be used within the innermost containing block that it was defined in.
Therefore there is no advantage over defining typedef ... command_type_big_endian
and typedef ... command_type_little_endian
, you cannot share the code either way.
You could use preprocessor macros to aid in avoiding repetition; then you could write the bulk of a serialization and deserialization macro only once and instantiate that for each command_type
variation.