c - I try to switch a specific struct by creating an int of it and can't find a fault -
i defined structure:
struct command_type { uint8_t a,b,command; }; // struct command_type
and constants like:
#define _heartbeat ((struct command_type) {0x10,0x01,0})
i did use in funktions , use how wanted want switch funtion case should use labels. there defined int_of_command_type this:
#define int_of_command_type(a) ((unsigned int) (((int) ((a).a)) << 16) |\ (unsigned int) (((int) ((a).b)) << 8) | \ (unsigned int) (((int) ((a).command))))
when use function print out %u value variable of type struct command_type works perfect.
now did want this:
struct command_type command_type_var=_hearbeat; ....some code .... switch(command_type_var) { case inf_of_command_type(_heartbeat): ..... break; default: };
and following fault message: case label not reduce integer constant. know, how can round problem easy way, because not understand @ wrong when works testprints , not in case label position. i've got lots of defined commands , don't want change of them anyway don't understand how handle it. maybe (const int) or ever needed?
hope know quick fault , if there way round.
the constraint of switch
statement requires according c11 standard integer expression::
6.8.4.2/1 controlling expression of switch statement shall have integer type.
command_type_var
doesn't match constraint, struct (even if struct holds in integer, , if hold integer bit fields).
how solve it:
it's quite simple: convert struct int in switch, using macro:
switch(int_of_command_type(command_type_var)) // here use int { case int_of_command_type(_heartbeat): // fortunately constant break; default: break; };
of course, works if macro defined correctly: parameter can't take name of 1 of struct member, or otherwhise you'll end weird errors due unexpected substitutions (the parameter should renamed x):
#define int_of_command_type(x) ((unsigned int) (((int) ((x).a)) << 16) |\ (unsigned int) (((int) ((x).b)) << 8) | \ (unsigned int) (((int) ((x).command))))
edit: if, despite fact int_of_command_type(_heartbeat)
calculated @ compile time, compiler doesn't recognize constant integer expression, should replace switch if/else sequences. case msvc 2015, seems use stricter rules of 6.6/6 not require implementation provide possibility use .
operator on structure constants.
Comments
Post a Comment