-4

This is on C:

#include <stdio.h>

int main()
{
    int a=100,b;
    b= (a>100)?a++:a--;
    printf("%d %d\n",a,b);
}

b assigned the value 100 but when trying

int main()
{
    int a=100,b;
    b= (a>100)
    printf("%d %d\n",a,b);
}

b prints the value 1 as it returns true. why is it different when using '?:' operator?

Nikhil KR
  • 23
  • 2
  • 1
    Actually, the second example sets `b` to `0`. See [here](https://onlinegdb.com/B11oMThBV). – David Schwartz Feb 22 '19 at 00:30
  • 2
    Um... But your code sample are completely different. Why does it surprise you that they do different things? – AnT stands with Russia Feb 22 '19 at 00:34
  • Possible duplicate of [How does the ternary operator work?](https://stackoverflow.com/questions/463155/how-does-the-ternary-operator-work) and [How do I use the conditional operator?](https://stackoverflow.com/q/392932/62576) – Ken White Feb 22 '19 at 00:42

3 Answers3

4

The ?: operator evaluates either the thing before the : or the thing after the : to determine what it evaluates to. In this case, (a>100) is false, so it evaluates to a--. Since that's a post-decrement, the decrement happens after its value is provided, so it evaluates to the 100 value that b had before it was decremented. Thus b gets this value.

So in the first example, the result of evaluating a-- is assigned to b. In the second example, the result of evaluating (a>100) is assigned to b.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
4

In the first case,

b= (a>100)?a++:a--;

can be thought of as following in simple terms:

if(a>100) {
   b = a;
   a = a + 1;
}
else {
   b = a;
   a = a - 1;
}

In the second case,

b= (a>100)

the boolean operation a>100 returns false which is equivalent to 0. So b will get a value of 0, not 1.

that other guy
  • 116,971
  • 11
  • 170
  • 194
VHS
  • 9,534
  • 3
  • 19
  • 43
1

By definition, both a-- and a++ evaluate to the old, original value of a. This is how postfix operators behave. The original value of a is 100.

So, regardless of how your ?: plays out, b is assigned the original value of a, which is 100. In that sense the resultant value of b is not affected by ?: operator at all.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765