简体   繁体   中英

How do logical && and || operators along with increment and decrement work?

Evaluate the following expressions. Find x,y,z values in each case. Assuming x=1 and y=5 initially, what do you observe:

  1. z=++x && ++y;
  2. z=--x && --y;
  3. z=++x || ++y;
  4. z=--x || --y;

How are logical operators affecting the values?

I believe "what do you observe" is very explicit in that you should see something. That almost certainly means writing the code and examining what happens.

In any case, the logical operators treat 0 as false, anything else as true. The output of those operators is 0 for false and 1 for true.

Also keep in mind that the pre-increment and -decrement operators change the value before use.

And, finally, be aware that && and || are short-circuiting operators which means the second sub-expression may not always be evaluated. For example:

int x = 1 ; int y = 5 ; int z = --x && --y;

will leave y equal to 5, because the --x is zero/false so we know that the whole expression will be false - there's no need to evaluate the second sub-expression.

That should be enough to figure out what the results are, based on your pre-conditions for x and y .


As a hint, let's look at the first one. ++x and ++y will be 2 and 6 respectively so both true. Hence true && true will give true, ending up as 1 .


And now, since you have written some code (as per your comment asking about what you considered strange behaviour of the -- and ++ operators in some cases), here's my sample code which shows the operations:

#include <stdio.h>

int main() {
    int x, y, z;

    x = 1; y = 5; printf("oldx = %d, oldy= %d", x, y);
    z=++x && ++y;
    printf(", newx= %d, newy = %d, z = %d\n", x, y, z);

    x = 1; y = 5; printf("oldx = %d, oldy= %d", x, y);
    z=--x && --y;
    printf(", newx= %d, newy = %d, z = %d\n", x, y, z);

    x = 1; y = 5; printf("oldx = %d, oldy= %d", x, y);
    z=++x || ++y;
    printf(", newx= %d, newy = %d, z = %d\n", x, y, z);

    x = 1; y = 5; printf("oldx = %d, oldy= %d", x, y);
    z=--x || --y;
    printf(", newx= %d, newy = %d, z = %d\n", x, y, z);

   return 0;
}

The output of that is:

oldx = 1, oldy= 5, newx= 2, newy = 6, z = 1
oldx = 1, oldy= 5, newx= 0, newy = 5, z = 0
oldx = 1, oldy= 5, newx= 2, newy = 5, z = 1
oldx = 1, oldy= 5, newx= 0, newy = 4, z = 1

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