5.12 Operators for Performing Shortcuts

I l @ ve RuBoard

C++ not only provides you with a rich set of declarations, but also gives you a large number of special-purpose operators. Frequently a programmer wants to increment (add 1 to) a variable. Using a normal assignment statement, this would look like:

 total_entries = total_entries + 1; 

C++ provides you a shorthand for performing this common task. The ++ operator is used for incrementing:

 ++total_entries; 

A similar operator, -- , can be used for decrementing (subtracting 1 from) a variable.

 --number_left;  // Is the same as number_left = number_left - 1; 

But suppose you want to add 2 instead of 1. Then you can use the following notation:

 total_entries += 2; 

This is equivalent to:

 total_entries = total_entries + 2; 

Each of the simple operators shown in Table 5-4 can be used in this manner.

Table 5-4. Shorthand operators

Operator

Shorthand

Equivalent statement

+=

x += 2;

x = x + 2;

-=

x -= 2;

x = x - 2;

*=

x *= 2;

x = x * 2;

/=

x /= 2;

x = x / 2;

%=

x %= 2;

x = x % 2;

++

++x;

x = x + 1;

--

-- x;

x = x - 1;

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net