0

I just started learning C, and I have some problems with the ? : operator.

How can I change

x = c ? a : b;

into an if else statement?

if() { x=a; }  else { x=b;}

Is it correct like this? I don't know what the condition should be.

ajp15243
  • 7,704
  • 1
  • 32
  • 38
  • The conditional operator is beautiful in that it doesn't allow mutation, just return of a value of the same type from more than one branch. Why the need to change to an if statement? – StuartLC May 01 '14 at 16:16
  • 1
    I was just interested how it works:) – user3411919 May 01 '14 at 16:17

3 Answers3

1

It would be

if(c)
   x=a;
else
   x=b;
Rohan
  • 52,392
  • 12
  • 90
  • 87
1

A turnary statement is in the form:

result = (booleanValue ? valueA : valueB);

This converts to:

if (booleanValue) {
    result = valueA;
} else {
    result = valueB;
}

In your case "booleanValue" is "c", "valueA" is "a", "valueB" is "b". Hope that helps!

drew_w
  • 10,320
  • 4
  • 28
  • 49
0

Here is the equivalent if statement:

if (c)
{
    x = a;
}
else
{
    x = b;
}

The conditional operator ?: is described in chapter 2.11 of your C book, "The C Programming Language", 2nd edition, by Kernighan and Ritchie.

ouah
  • 142,963
  • 15
  • 272
  • 331