Question

I'm working on an embedded controller, with a few different non-standard types defined, EG:

uint8 = unsigned char
sint16 = int

If I need to typecast from uint8 to sint16, where should i use my parentheses?

uint8 u8_My_Var = 255;
sint16 s16_New_Var = 0;

s16_New_Var = ((sint16)u8_My_Var + 1); //or
s16_New_Var = ((sint16)(u8_My_Var) + 1); //or
s16_New_Var = ((sint16)(u8_My_Var + 1)); //or
s16_New_Var = (((sint16)(u8_My_Var)) + 1);

I would normally use (((sint16)(u8_My_Var)) + 1), however I started wondering about the 'scope' of the type cast.

No correct solution

OTHER TIPS

Type casts take precedence over addition, so all but the third line (s16_New_Var = ((sint16)(u8_My_Var + 1));) are equivalent. However, if you want to perform the cast after the addition, this is the one you need.

Note that the outermost parentheses are redundant in all cases, since type casts also take precededence over assignments.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top