简体   繁体   English

括号和类型转换

[英]Parentheses and Typecasting

I'm working on an embedded controller, with a few different non-standard types defined, EG: 我正在开发一种嵌入式控制器,其中定义了一些不同的非标准类型,例如EG:

uint8 = unsigned char
sint16 = int

If I need to typecast from uint8 to sint16 , where should i use my parentheses? 如果我需要从uint8转换为sint16 ,我应该在哪里使用括号?

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. 我通常会使用(((sint16)(u8_My_Var)) + 1) ,但是我开始怀疑类型转换的``范围''。

Type casts take precedence over addition, so all but the third line ( s16_New_Var = ((sint16)(u8_My_Var + 1)); ) are equivalent. 类型强制转换优先于加法s16_New_Var = ((sint16)(u8_My_Var + 1)); ,因此除第三行以外的所有内容( s16_New_Var = ((sint16)(u8_My_Var + 1)); )是等效的。 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. 请注意,在所有情况下,最外面的括号都是多余的,因为类型强制转换也优先于赋值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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