Conditional Expressions.


We have a short-hand construct for some if ... else ... constructs.

Consider the following two examples.

Example 1 Example 2

  if ( x == 1 ) 
    y = 10;
  else
    y = 20;
    

  y = (x == 1) ? 10 : 20;  

These examples both perform the same function. If x is 1 then y becomes 10 else y becomes 20. The example on the right evaluates the first expression '(x ==1 )' and if true evaluates the second '10'. If false the third is evaluated. Here is another example.

Example 1 Example 2

 if ( x == 1 ) 
   puts("take car"); 
 else
   puts("take bike");  

 (x == 1) ? puts("take car") : puts("take bike"); 
                                                  
    or

 puts( (x == 1) ? "take car" : "take bike");

It has been said that the compiler can create more efficent code from a conditional expression possibly at the expence of readable code. Unless you are writing time critical code (and lets face it, thats unlikely) the more efficent code is not much of a reason to use this construct. I feel that it has its uses, but should not be lost into some complex statement, but, since when did C programmers worry if anyone else could read their code ;-)


See also:


Top Master Index Keywords Functions


Martin Leslie

e='hidden' name='h' value='nds-private-remove'/>

path: root/drivers/usb/c67x00
AgeCommit message (Expand)AuthorFilesLines