O'Reilly logo

Sams Teach Yourself C++ in 24 Hours, Third Edition by Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Combining the Assignment and Mathematical Operators

It is not uncommon to want to add a value to a variable and then to assign the result back into the variable. If you have a variable myAge and you want to increase the value by two, you can write

int myAge = 5;
int temp;
temp = myAge + 2;  // add 5 + 2 and put it in temp
myAge = temp;             // put it back in myAge

This method, however, is terribly convoluted and wasteful. In C++ you can put the same variable on both sides of the assignment operator, and thus the preceding becomes

myAge = myAge + 2;

which is much better. In algebra this expression would be meaningless, but in C++ it is read as “add two to the value in myAge and assign the result to myAge.”

Even simpler to write, but perhaps a bit ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required