[英]Assignment and Precedence of operators in c
In the following code : 在下面的代码中:
int main()
{
int x = 2, y = 1;
x *= x + y;
printf("%d\n", x);
return 0;
}
How is the operators precedence work ? 运算符优先级如何工作? , as * has a higher precedence than + so I expect that multiplication operation should be done first however the result shows that it is calculated as x * = (x+y) so the addition is done first !
,因为*的优先级比+高,所以我希望应该先进行乘法运算,但是结果表明它的计算公式为x * =(x + y),所以加法首先完成!
The same confusion here in the following code : 以下代码在这里同样令人困惑:
int main()
{
int x = 2, y = 2;
x /= x / y;
printf("%d\n", x);
return 0;
}
dont know how the operators precedence will work ... Thanks for anyone has an explanation. 不知道运算符优先级将如何工作。谢谢任何人的解释。
The shorthand operators (*=, /= etc.) have lower precedence than single (+, / etc.) operators. 速记运算符(* =,/ =等)的优先级低于单个运算符(+,/等)。
See: http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence 请参阅: http : //en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence
The Precedence of operators is still the same. 运算符的优先级仍然相同。 * has a higher precedence than +.
*优先于+。 However, since you're using *= you are waiting for the operation to be completed first before multiplying.
但是,由于您使用的是* =,因此您在乘法之前先等待操作完成。
It's basically the same thing is (x + y) * x 基本上是(x + y)* x
Given identifiers a
and b
, an operator of the form a op= b
(where op
can be +
, *
, etc.), is entirely equivalent to (a) = (a) op (b)
, with the only difference being that (a)
is only evaluated once. 给定标识符
a
和b
,形式a op= b
(其中op
可以是+
, *
等) a op= b
符完全等效于(a) = (a) op (b)
,唯一的不同是(a)
仅评估一次。
The comma operator has the lowest precedence. 逗号运算符的优先级最低。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.