Ternary Operators

Can somebody explain in simple terms how this works and what it produces?
 
a = --b ? b : (b = -99);
At first expression --b is executed. If the result is not equal to zero then the result is assigned to a. Otherwise -99 is assigned to b and to a.
You can check this yourself by writing a simple test program.
Last edited on
Ok, this is good - I see how -99 can be assigned to ' b', but how does 'a' get assigned too? Isn't 'a' only assigned to the operand on the right of the operator, --b?

And what is that second b after the '?' for?

finally, how do you get "is not equal to 0"? Is this because this ternary operator tests for true or false?
Last edited on
Please read description of the ternary operator in any book on C++ or here in documentation.
that is an short hand if else statement
For exemple:
1
2
3
4
5
6
7
8
if(a == 0)
{
  a++;
}
else
{
  a--;
}

is the same thing to
(a == 0) ? a++ : a--;

in our case that would be the same as
1
2
3
4
5
6
7
8
9
if(--b) // after the decrement b is diferent then 0
{
  a = b;
}
else
{
 b = -99;
 a = b;
}
Last edited on
For x = a ? b : c ;, x = (a ? b : c) ; is equivalent.

It could be rewritten as an if/else:

1
2
3
4
if ( x )
   a = b ;
else
   a = c ;


With that in mind the original statement above translates to:

1
2
3
4
if ( --b )
    a = b ;
else
    a = b = -99 ;


Last edited on
Excellent. Thanks
Topic archived. No new replies allowed.