简体   繁体   中英

Tricky array increment in C

I do not understand why before if-statement ++b[1] is equal to 1, but after if-statment ++b[1] is equal to 0. Why ++b[1] does not increase inside if-statement?

#include <stdio.h>

int main()
{
    int c = 0;
    int b[3] = {4};
    printf("%d\n", ++b[1]); // return 1
    b[1]--;
    if((c-- && ++b[1])|| b[0]++)
    {
        printf("%d\n", b[1]); // return 0
        printf("%d\n", c); // return -1
    }
    return 0;
}
if((c-- && ++b[1])|| b[0]++)

c-- yields 0 , so ++b[1] is not evaluated.

This is called short-circuit evaluation .

There's just some confusing operator usage going on here.

  • c-- is a postfix decrement, and so in the conditional statement c is evaluated as false (as it is 0 ), before being decremented.
  • Now since && short circuits and only evaluates the second condition if the first is true, we do not evaluate ++b[1] , but enter the conditional on the truthiness of b[0]++ .

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