Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

C programming exercise

I am studying C in college and in some exercises like the one below I don't understand the operations of increment and decrement in an "if" statement. Why the answer is 0 2 ?

#include <stdio.h>

int main () {
  int x = 1, y = 1;

  if ((x-- || y --) && (--x || --y))
    printf ("%d %d
",x+1,y +1);
  else if ((x++ && y++) || (++ x && ++y))
    printf ("%d %d
",x+2,y +2);
  else
    printf ("%d %d
",x+3,y +3);

  return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The && returns 1 when both sides are non-zero. If the first expression evaluetes to 0, the second one it's not going to be executed.

The || returns 1 when at least one side is non-zero. If the first expression doesn't evaluetes to 0, the second one is not going to be executed.

The pre increment do its job before a value is used. The post increment doesn't do anything until a sequence point is found. && and || are sequence points.

Now in the first if there are two expressions divided by an &&. This means that the if will be entered only if both sides evaluetes to a non-zero value.

if ((x-- || y --) && (--x || --y))

x-- is 1, so the first || returns 1 straight away, without y-- being executed.

A sequence point is found and x becomes 0.

Now --x is -1 which is not 0. So even the second || returns 1 straight away.

Both sides of the && are non-zeros, so the if is entered with x being -1 and y being 1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...