How exactly does the ?: operator work in C?

N00b :

I have a question, how the compiler operate on the following code:

#include<stdio.h>

int main(void)
{
  int b=12, c=11;
  int d = (b == c++) ? (c+1) : (c-1);
  printf("d = %i\n", d);
}

I am not sure why the result is ‍‍‍d = 11.

Eric Postpischil :

In int d = (b == c++) ? (c+1) : (c-1);:

  • The value of c++ is the current value of c, 11. Separately, c is incremented to 12.
  • b == 11 is false, since b is 12.
  • Since (b == c++) is false, (c-1) is used. Also, the increment of c to 12 must be completed by this point.
  • Since c is 12, c-1 is 11.
  • d is initialized to that value, 11.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=32994&siteId=1