1

If I give an Equal to relational operator in the first expression of the ternary operator of the following code, then it outputs 10,20, which I have understood.

#include <stdio.h>

int main()
{
    int a=10, c, b;
    
    c = (a==99) ? b = 11:20;
    
    printf("%d, %d", a, c);

    return 0;
}

But, When I place an Assignment operator instead of the Equal to relational operator (code is given below), then it outputs 99, 11. Now I am not getting how this Assignment operator is treated in the first expression of the ternary operator.

#include <stdio.h>

int main()
{
    int a=10, c, b;
    
    c = (a=99) ? b = 11:20;
    
    printf("%d, %d", a, c);

    return 0;
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Rawnak Yazdani
  • 1,333
  • 2
  • 12
  • 23
  • 1
    The assignment operator sets a to 99 and since 99 is a nonzero value, it is true. So c is set to 11. – mediocrevegetable1 Mar 12 '21 at 07:21
  • 1
    As for the `b = 11` part, b is set to 11 and the value of b is "returned", so when the condition is true c is set to 11 too. – mediocrevegetable1 Mar 12 '21 at 07:25
  • 2
    Does this answer your question? [What does an assignment return?](https://stackoverflow.com/questions/9514569/what-does-an-assignment-return) – Paul Hankin Mar 12 '21 at 07:25
  • @PaulHankin Yes, I have got my answer. I will accept an answer. – Rawnak Yazdani Mar 12 '21 at 07:27
  • 1
    Notably, it's considered very bad practice to mix `=` with other operators except when it's used for storing the final result. Having more than one assignment in the same expression is some major code stink. Both `=` and `?:` are dangerous operators that come with a lot of subtle special rules. Since there is no award for most operators in a single line, such lines should instead be broken up into several. – Lundin Mar 12 '21 at 10:41
  • @Lundin You are correct, I don't want to make my code more complex. But this question came in an exam, so I asked this question. – Rawnak Yazdani Mar 12 '21 at 13:44

3 Answers3

1

a=99 is an assignment to the variable a of the value 99. 99 is true in C, so the variables c and b are both assigned the value 11 in your 2nd program.

Allan Wind
  • 23,068
  • 5
  • 28
  • 38
1

Assignment operator sets variable a to 99 and any value greater than zero is true,So it returns True and sets variable c to 11.

Ashish M J
  • 642
  • 1
  • 5
  • 11
1

This line

c = (a==99) ? b = 11:20;

is doing the same as

if (a == 99)
{
    c = b = 11;
}
else
{
    c = 20;
}

Likewise this line

c = (a=99) ? b = 11:20;

is doing the same as

if (a = 99)
{
    c = b = 11;
}
else
{
    c = 20;
}

The interresting part is

if (a = 99)
{
    ...

which performs an assignment to a and then checks whether the assigned value is zero (false) or non-zero (true). So it can be written as:

a = 99;
if (a != 0)
{
    ...

BTW: if (a != 0) can also be written as if (a)

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63