C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1

13. A Bigger Bag of Tricks—Some More Operators for Your


Programs


In This Chapter


  • Saying goodbye to if...else and hello to conditional

  • Using the small-change operators: ++ and --

  • Sizing up the situation


Have patience! You’ve learned about almost all the C operators. With the exception of a few more
advanced operators that you’ll read about in Chapter 24, “Solving the Mystery of Pointers,” this
chapter rounds out the order of operators table and explains conditional operators, increment
operators, and decrement operators.


C operators sometimes substitute for more wordy commands that you would use in other programming
languages. Not only can an assortment of operators speed your program development time, but they
also compile more efficiently and run faster than commands. The C operators do a lot to make C the
efficient language that it is.


Goodbye if...else; Hello, Conditional


The conditional operator is the only C operator that requires three arguments. Whereas division,
multiplication, and most of the others require two values to work, the conditional operator requires
three. Although the format of the conditional operator looks complex, you will see that it streamlines
some logic and is actually straightforward to use.


The conditional operator looks like this: ?:. Here is its format:


Click here to view code image


relation? trueStatement : falseStatement;

The relation is any relational test, such as age >= 21 or sales <= 25000.0. You also
can combine the relational operators with the logical operators you learned about in Chapter 12,
“Juggling Several Choices with Logical Operators.” The trueStatement is any valid C
statement, and the falseStatement is also any valid C statement. Here is an example of a
conditional operator:


Click here to view code image


(total <= 3850.0)? (total *= 1.10): (total *= 1.05);

Tip

The parentheses are not required, but they do help group the three parts of the
conditional operator so that you can see them easier.
Free download pdf