11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Using Assignment OperatorsChapter 3: Performing Mathematical Operations 45An assignment operator is a binary operator that changes the value of its leftargument. The equal sign (=), a simple assignment operator, is an absolutenecessity in any programming language. This operator puts the value of theright-hand argument into the left argument. The other assignment operatorsare odd enough that they seem to be someone’s whim.The creators of C++ noticed that assignments often follow the form ofvariable = variable # constantwhere # is some binary operator. Thus, to increment an integer operator by2, the programmer might writenVariable = nVariable + 2;This expression says, “add two to the value of nVariable and store the resultsback into nVariable.” Doing so changes the value of nVariable to 2 morethan it was.It’s common to see the same variable on both the right and left side of anassignment.Because the same variable appears on both sides of the = sign, the sameFathers of the C++ Republic decided to create a version of the assignmentoperator in which a binary operator is attached. This says, in effect, “Thoushalt perform whatever operation on a variable and store the results rightback into the same variable.”Every binary operator has one of these nifty assignment versions. Thus, theassignment just given could have been written this way:nVariable = nVariable + 2;nVariable += 2;Here the first line says (being very explicit now) “Take the value of nVariable,add 2, and store the results back into nVariable.” The line is a second formif the same expression, saying (a bit more abruptly), “Add 2 to the value ofnVariable.”Other than assignment itself, these assignment operators are not used allthat often. However, as odd as they might look, sometimes they can actuallymake the resulting program easier to read.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!