Reviewing C++ operators
Unary, binary, and ternary operators exist in C++. C++ allows operators to have different meanings based on the context of usage. C++ also allows programmers to redefine the meaning of selected operators when used in the context of at least one user defined type. The operators are listed in the following concise list. We’ll see examples of these operators throughout the remainder of this section and throughout the course. Here is a synopsis of the binary, unary, and ternary operators in C++:
Figure 1.1 – C++ operators
In the aforementioned binary operator list, notice how many of the operators have “shortcut” versions when paired with the assignment operator =
. For example, a = a * b
can be written equivalently using a shortcut operator a *= b
. Let’s take a look at an example that incorporates an assortment of operators, including the usage of a shortcut operator:
score += 5; score++; if (score == 100) cout << "You have a perfect score!" << endl; else cout << "Your score is: " << score << endl; // equivalent to if - else above, but using ?: operator (score == 100)? cout << "You have a perfect score" << endl: cout << "Your score is: " << score << endl;
In the previous code fragment, notice the use of the shortcut operator +=
. Here, the statement score += 5;
is equivalent to score = score + 5;
. Next, the unary increment operator ++
is used to increment score
by 1. Then we see the equality operator ==
to compare score
with a value of 100
. Finally, we see an example of the ternary operator ?:
to replace a simple if
- else
statement. It is instructive to note that ?:
is not preferred by some programmers, yet it is always interesting to review an example of its use.
Now that we have very briefly recapped the operators in C++, let’s revisit function basics.