Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly does the ?: operator work in C?

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.

like image 858
J0S Avatar asked Feb 11 '20 12:02

J0S


People also ask

How this operator works in C?

This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example: (a += b) can be written as (a = a + b) If initially value stored in a is 5. Then (a += 6) = 11.

How does the NOT operator work in C?

operator in C. Logical NOT is denoted by exclamatory characters (!), it is used to check the opposite result of any given test condition. If any condition's result is non-zero (true), it returns 0 (false) and if any condition's result is 0(false) it returns 1 (true).

How do you write not equal to in C?

The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .

How does the operator work in programming?

In mathematics and computer programming, an operator is a character that represents a specific mathematical or logical action or process. For instance, "x" is an arithmetic operator that indicates multiplication, while "&&" is a logical operator representing the logical AND function in programming.


1 Answers

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.
like image 113
Eric Postpischil Avatar answered Sep 29 '22 21:09

Eric Postpischil