In C++, the +
operator serves two distinct purposes: adding numeric values and combining (concatenating) text values (strings). This is a powerful feature, but knowing how C++ treats numbers and strings differently is vital to avoid errors.
Adding Numbers
When the +
operator is used with numbers, C++ performs mathematical addition.
Example
#include <iostream> using namespace std; int main() { int maxRPM = 10000; // Engine's maximum revolutions per minute int idleRPM = 900; // Engine's idle revolutions per minute int totalRPM = maxRPM + idleRPM; // Adds numbers together cout << "Total RPM: " << totalRPM; return 0; }
Output:
This program calculates and displays “Total RPM: 10900.”
Combining Strings
When the +
operator is used with strings, it performs concatenation, joining strings to form one.
Example
#include <iostream> #include <string> using namespace std; int main() { string helmetBrand = "Shoei "; string helmetType = "Full Face"; string fullHelmetInfo = helmetBrand + helmetType; // Combines text cout << "Helmet Info: " << fullHelmetInfo; return 0; }
Output:
This combines “Shoei “ and “Full Face” to display “Helmet Info: Shoei Full Face.”
Adding Numbers and Strings Together
Attempting to combine numbers and strings directly with the +
operator will cause an error, as C++ cannot perform both addition and concatenation simultaneously.
Example
#include <iostream> #include <string> using namespace std; int main() { string bikePrice = "100000"; // Price stored as text int discount = 5000; // Discount stored as a number // Uncommenting the following line will cause a compilation error // string totalPrice = bikePrice + discount; return 0; }