C++: Increment and Decrement Operators

Increment and Decrement Operators

In this C++ video lesson, we cover the two most basic operations in C++: increment and decrement. Although these are the simplest elements of the language, there is a subtle difference between the prefix and postfix operators. Namely, when an operator is inline, the variable access comes after an operation with the prefix operator and, while it is just the opposite with the postfix operator.




Suppose, for example, that we have retrieved the price of a music CD from several websites. We would like to find the best price for the CD. Look at the code below. If we have an array of 10 prices and we would like to select the lowest price, which operator should we use inside the square brackets to properly access the array?

Arrays begin at 0 and this one has 10 elements. So, it ends at index 9. Therefore, we would like to access these elements of the array when we set the current price. Since the index begins at zero, we need to use an increment operator. However, if we use the prefix operator, we will access the prices at the indices 1 through 10. Since there is no price at index 10, we will be accessing improper memory. So, we need to use the postfix operator as shown below.

As an additional programming note, we would need to initialize the lowest price to something larger than the lowest music CD price. Hopefully, something like 100 dollars would do it, but relying on arbitrary values like this is bad practice. If inflation suddenly hit, our value might not be sufficiently high to be assured that the value is higher than the price of current music CDs. In this case, our code would fail. A better way to handle this is to initialize the lowest price to something like the first price in the array.