Evaluation of C expression

2019-01-20 09:36发布

int main() {
  int i = -3, j = 2,  k = 0, m;
  m = ++i || ++j && ++k;
  printf("%d %d %d %d\n", i, j, k, m);
  return 0;
}

i thought that && has more precedence that || as per this logic ++j should execute, but it never does and the program outputs -2 2 0 1. What is going on here? What are the intermediate steps?

标签: c++ c expression
8条回答
够拽才男人
2楼-- · 2019-01-20 10:36

C does short-circuiting of logical expressions, so evaluation of ++i is enough to figure out that m should be true.

查看更多
女痞
3楼-- · 2019-01-20 10:38
  1. The || operator forces left-to-right evaluation, so the expression ++i is fully evaluated first, with a result of -2.
  2. The || operator forces a sequence point, so the side effect is applied and i is now equal to -2.
  3. The result of the expression ++i is not 0, so the expression ++j && ++k is not evaluated at all.
  4. Since the LHS is non-zero, the result of the entire expression ++i || ++j && ++k is 1 (true), which is assigned to m.

Just to echo what several others have said, precedence and order of evaluation are not the same thing.

查看更多
登录 后发表回答