c - Cast to larger type in switch case -


during work saw following code snippet , wonder, if there reason casting "case-values" larger datatype. guess, used offer possibility of having more 256 different states later on, then, state variable must larger. here code talking about:

#define state_1 (uint8_t)(0x00) #define state_2 (uint8_t)(0x01) ... #define state_n (uint8_t)(0x..)  void handlestate(uint8_t state) {   switch(state)   {      case (uint16_t)state_1:       // handle state 1       break;      case (uint16_t)state_2:       // handle state 2       break;      ...     case (uint16_t)state_n:       // handle state n       break;      default:       break;   }  } 

is there reason this?

it looks failed attempt rid of implicit integer promotions on 8-bit or 16-bit microcontroller.

first of all, there no way integer promotion can cause harm here, preventing overly pedantic , reduces readability. @ glance looks nonsense.

but.

perhaps coding standard used enforced no implicit conversions allowed? example misra-c does. in case, code makes sense: wished surpress warnings static analysis tool.

using explicit casts way of demonstrating aware of implicit type promotions (something handful of c programmers are, sadly) , handle them in code.

but if so, programmer missed out 1 integer promotion taking place, namely here: switch(state). how switch statements work:

the integer promotions performed on controlling expression. constant expression in each case label converted promoted type of controlling expression.

so if programmer concerned implicit promotions, should have written code switch((uint16_t)state) , kept casts in each case.


if sneered @ code in question, consider following:

  • do know implicit promotions there in switch statement , did consider impact might have on code?
  • do know meaning of integer promotion rules? did know , consider uint8_t promoted (signed) int in code?
  • do use coding standard , static analysis tools @ all, yourself?

Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

android - CollapsingToolbarLayout: position the ExpandedText programmatically -

Listeners to visualise results of load test in JMeter -