Souvik Datta
Souvik Datta

Reputation: 106

Basic Conditional Operator

I have tried using a conditional operator to reduce the lines of code in the following C Program, however, I'm not getting the desired result.

Objective - To set the value of x to 50 if y > 7 else set it to 25

#include <stdio.h> // Conditional Operator

int main()
{
    int x, y;

    printf("Enter x: ", x);

    scanf("%d", &x);

    printf("Enter y: ", y);

    scanf("%d", &y);

    if (x = y > 7 ? 25 : 50)
    { 
        printf("Value of x: %d", x);
    }  
    else
    {
        printf("Failed\n");
    }
}

Upvotes: 1

Views: 99

Answers (1)

4386427
4386427

Reputation: 44360

Objective - To set the value of x to 50 if y > 7 else set it to 25

Then you have swapped the values here:

y > 7 ? 25 : 50
        ^^   ^^
         wrong

It has to be:

y > 7 ? 50 : 25

The reason is:

y > 7 ? 50 : 25
\---/    |    |
  |      |    -----> Result if condition is FALSE
  |      |
  |      ---> Result if condition TRUE
  |
condition

Other notes

  1. Why do you take x as input when you always overwrite it with 50 or 25?

  2. Always check the return value from scanf

  3. The else part of your if statement can't be reached. So it can be deleted.

  4. printf("Enter y: ",y); is wrong. You don't print y. So delete ,y

So simply do:

#include <stdio.h>

int main(void)
{
    int x,y;

    printf("Enter y: ");

    if (scanf("%d",&y) != 1)
    {
        puts("wrong input");
        return 0;
    }

    x = y > 7 ? 50 : 25;
    printf("Value of x: %d", x);

    return 0;
}

Final note

Your code has this line:

if (x = y > 7 ? 25 : 50)

Here you do an assignment to x inside the if condition and the assigned value is then used as condition for the if.

While it's perfectly legal C code, most programmers consider it bad. The reason is that it easy to confuse with

if (x == y > 7 ? 25 : 50)
      ^^
    Did you really want a compare!?

In general it's better to avoid assignments in the if condition, i.e. you could have done:

x = y > 7 ? 25 : 50;
if (x)

instead. As another benefit of this, it's also much more clear that the else part can't be reached.

Upvotes: 2

Related Questions