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

(Romina) #1

10. Powering Up Your Variables with Assignments and


Expressions


In This Chapter


  • Saving time with compound operators

  • Fitting compound operators into the order of operators

  • Typecasting your variables


As you can see from Table 9.1 in the last chapter, C has a rich assortment of operators. Many
operators help C keep its command vocabulary small. C doesn’t have many commands, but it has a lot
more operators than in most other programming languages; whereas most computer programming
languages have relatively few operators and lots of commands, C retains its succinct nature by
providing many powerful operators.


This chapter explores a few more operators that you need as you write programs. The compound
assignment operators and the typecast operator provide the vehicles for several advanced operations.


Compound Assignment


Many times in your programs, you will have to change the value of a variable. Until now, all
variables have been assigned values based on constant literal values or expressions. However, often
you will need to update a variable.


Suppose your program had to count the number of times a profit value went below zero. You would
need to set up a counter variable. A counter variable is a variable that you add 1 to when a certain
event takes place. Every time a profit value goes negative, you might do this:


Click here to view code image


lossCount = lossCount + 1; /* Adds 1 to lossCount variable */

Warning

In math, nothing can be equal to itself plus 1. With computers, though, the previous
assignment statement adds 1 to lossCount and then assigns that new value to
lossCount, essentially adding 1 to the value of lossCount. Remember that an
equals sign means to take whatever is on the right of the equals sign and store that
computed value in the variable on the left.

The following simple program prints the numbers from 1 to 5 using a counter assignment statement
before each printf() and then counts back down to 1:


Click here to view code image


// Example program #1 from Chapter 10 of Absolute Beginner's Guide
Free download pdf