简体   繁体   中英

Parentheses and Typecasting

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM