In C++, when you want to do simple math like adding, subtracting, and so on, you use something called arithmetic operators. These operators allow you to easily carry out addition, subtraction, multiplication, division, and even find remainders. In this topic, you will explore the most common arithmetic operators in C++ and learn how to use them to perform basic mathematical operations.
Basic arithmetic operations
Let's start by understanding how to use arithmetic operators to perform basic mathematical operations.
Addition(+): Use it to add two operands together or add two values together. It works with integers, floating-point numbers, and even characters.
int sum = 10 + 8; // sum will be 18 float pi = 3.14 + 5.0; // pi will be 8.14 char letter = 'A' + 4; // letter will be 'E'Subtraction (-): Use it to subtract the second operand from the first operand.
int difference = 15 - 5; // difference will be 10 float result = 7.5 - 2.5; // result will be 5.0Multiplication (*): The multiplication operator (*) multiplies two values.
int product = 7 * 4; // product will be 28 float area = 5.5 * 3.0; // area will be 16.5Division (/): The division operator (/) divides one value by another. When both operands are integers, the result will also be an integer (integer division). When at least one operand is a floating-point number, the result will be a floating-point value.
int quotientOne = 20 / 3; // quotientOne will be 6 (integer division) float quotientTwo = 20.0 / 3; // quotient2 will be 6.6667 (floating-point division)Modulus (%): Use the modulus operator (%) to find the remainder of the division between two integers.
int remainder = 16 % 3; // remainder will be 1
You can only use the modulo(%) operator with integer type values.
Arithmetic operations with different data types
C++ supports various data types, such as integers (int), floating-point numbers (float, double), and even user-defined data types. You can use the arithmetic operators with these different data types, and the compiler takes care of implicit type conversion when necessary. However, it's important to note that the compiler tends to reduce data types to their smallest form, which requires cautious consideration on your part.
1. Integers
When performing arithmetic operations with integers, the result will be an integer. C++ automatically truncates any decimal portion that may arise during division, as shown in the below example:
int firstNum = 16;
int secondNum = 3;
int addition = firstNum + secondNum; // 19
int subtraction = firstNum - secondNum; // 13
int multiplication = firstNum * secondNum; // 48
int division = firstNum / secondNum; // result will be 5, not 5.33
int remainder = firstNum % secondNum; // 1 2. Floating-Point Numbers
Floating-point numbers can represent decimal values with fractional parts. The result will also be a floating-point number when performing arithmetic operations with floating-point numbers. Let's look at an example:
float firstNum = 16.0;
float secondNum = 3.0;
float addition = firstNum + secondNum; // 19.0
float subtraction = firstNum - secondNum; // 13.0
float multiplication = firstNum * secondNum; // 48.0
float division = firstNum / secondNum; // result will be 5.33333, not 5
int remainder = firstNum % secondNum; // error: invalid operands to binary expression ('float' and 'float') 3. Mixed Types and Implicit Type Conversion
When performing arithmetic operations with mixed data types (e.g., an integer and a floating-point number), C++ automatically performs implicit type conversion to ensure compatibility. Let's take some examples:
int firstNum = 16;
float secondNum = 3.0;
float addition = firstNum + secondNum; // 19
float subtraction = firstNum - secondNum; // 13
float multiplication = firstNum * secondNum; // 48
float division = firstNum / secondNum; // result will be 5.33333, not 5
int remainder = firstNum % secondNum; // error: invalid operands to binary expression ('int' and 'float')Shorthand operator
Shorthand operators in C++ are a concise way to combine arithmetic operations with assignments. They allow you to perform an arithmetic operation and update the value of a variable in a single step. These shorthand operators make your code more compact and efficient. Here are some common shorthand operators for arithmetic operations:
x += y; // Equivalent to x = x + y
x -= y; // Equivalent to x = x - y
x *= y; // Equivalent to x = x * y
x /= y; // Equivalent to x = x / y
x %= y; // Equivalent to x = x % yLet's take an example to understand the shorthand operators:
#include <iostream>
int main() {
int a = 10;
int b = 3;
a += b; // a is now 13
b *= 2; // b is now 6
std::cout << a << std::endl;
std::cout << b << std::endl;
a += 2; // a is now 15
b -= 5; // b is now 1
std::cout << a << std::endl;
std::cout << b << std::endl;
return 0;
}Here's the output of the above code snippet:
13
6
15
1Miscellaneous
1. Integer Division
As mentioned earlier, when performing division with integers, C++ truncates the decimal part, resulting in an integer quotient. This can lead to unexpected results when dealing with fractional values. Let’s see an example again:
int firstNum = 20;
int secondNum = 6;
float result = firstNum / secondNum; // result will be 3, not 3.3333To obtain more accurate results during division, at least one of the operands should be a floating-point number. And to avoid such unexpected results, you can explicitly cast the data types using static_cast<float> when necessary.
int firstNum = 20;
int secondNum = 6;
float result = static_cast<float>(firstNum) / secondNum; // The result will be 3.3333, and not 3.2. Overflow
In C++, the range of values that can be stored in a variable is limited by its data type. When performing arithmetic operations, especially with large numbers, there is a risk of overflow. Overflow occurs when the result of an operation exceeds the maximum value that can be stored in the data type. When an overflow happens, the result wraps around and may produce unexpected and incorrect results. For example, consider the following scenario:
int num = 2147483647; // Maximum value for a 32-bit integer
int result = num + 1; // The result will be -2147483648 due to overflowTo avoid overflow, it is essential to ensure that the data types used can accommodate the expected results of the arithmetic operations.
3. Floating-Point Precision
While floating-point numbers provide greater accuracy for decimal calculations compared to integers, they are not immune to precision limitations due to the nature of their representation in computers. Floating-point arithmetic can sometimes lead to subtle inaccuracies, especially when performing operations involving very small or very large numbers.
float num = 0.1;
float sum = num + num + num;
if (sum == 0.3) {
std::cout << "Equal" << std::endl;
} else {
std::cout << "Not Equal" << std::endl;
}Surprisingly, the output of this code might be "Not Equal" due to the way floating-point numbers are represented in binary. Floating-point numbers are stored in a binary format that may not precisely represent certain decimal values. In this case, the value 0.1 cannot be exactly represented in binary floating-point format, which leads to a small rounding error in each addition operation. There are some ways to solve this issue. However, it is not in the scope of this topic, so you will see it later.
Conclusion
Arithmetic operators in C++ are used for performing basic mathematical computations. They allow you to add, subtract, multiply, divide, and find remainders with ease. Understanding the behavior of these operators when working with different data types, as well as being mindful of floating-point precision and potential overflow, is crucial for writing accurate and reliable code.