Basic Arithmetic & Casting
Basic Arithmetic in C++
C++ provides a number of operators for performing basic arithmetic operations. These operators include:
- +: Addition
- -: Subtraction
- *: Multiplication
- /: Division
- %: Modulo (remainder)
These operators can be used to perform arithmetic operations on variables of different data types. For example, the following code performs arithmetic operations on variables of type int and float:
int a = 10; float b = 3.14159; // Add two integers. int c = a + 5; // Multiply two floats. float d = b * 2; // Divide two integers. float e = a / 2; // Calculate the remainder of a division operation. int f = a % 2;
The results of these operations are stored in the corresponding variables.
Casting in C++
Casting is a way to convert a value from one data type to another. This can be useful when you need to perform arithmetic operations on values of different data types.
There are two types of casting in C++:
- Implicit casting: Implicit casting occurs when the compiler automatically converts a value from one data type to another. For example, the following code implicitly converts the value of the variable
afrom type int to type float before performing the multiplication operation:
int a = 10; float b = 3.14159; // Multiply an int and a float. float c = a * b;
- Explicit casting: Explicit casting is when the programmer explicitly converts a value from one data type to another. This can be done using the cast operators (
dynamic_cast). For example, the following code explicitly converts the value of the variable
bfrom type float to type int before performing the division operation:
int a = 10; float b = 3.14159; // Divide a float by an int. int c = static_cast<int>(b) / a;
Explicit casting is often used to prevent errors that can occur when implicitly casting values.
Here is an example of how to use casting in C++:
// Convert a string to an integer. int a = static_cast<int>("10"); // Convert a floating-point number to a character. char b = static_cast<char>(3.14159); // Convert a pointer to an integer to a pointer to a float. float *c = reinterpret_cast<float*>(pInt); // Convert a const object to a non-const object. int *d = const_cast<int*>(pInt);
Casting can be a powerful tool for converting values between different data types. However, it is important to use it carefully to avoid errors.