Ternary Operators

rcast (42)
Can somebody explain in simple terms how this works and what it produces?
 
a = --b ? b : (b = -99);
vlad from moscow (3662)
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
rcast (42)
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
vlad from moscow (3662)
Please read description of the ternary operator in any book on C++ or here in documentation.
nedo (31)
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
cire (2347)
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
rcast (42)
Excellent. Thanks
Registered users can post here. Sign in or register to post.