C++ Assignment Operators
C++ Assignment Operators
In C++, assignment operators are used to assign values to variables. There are several assignment operators available in C++, including the simple assignment operator (=
) and compound assignment operators such as +=
, -=
, *=
, /=
, and %=
.
The simple assignment operator (=
) is used to assign the value on the right-hand side of the operator to the variable on the left-hand side. For example:
int x = 5;
In this example, the value 5
is assigned to the variable x
.
Compound assignment operators combine an arithmetic operation with assignment. For example, the +=
operator adds the value on the right-hand side to the variable on the left-hand side and assigns the result back to the variable. Here's an example:
int x = 5;
x += 3; // equivalent to x = x + 3
In this example, the value of x
is incremented by 3
, and the result (8
) is assigned back to x
.
Other compound assignment operators work in a similar way, performing the specified arithmetic operation and assigning the result back to the variable.
It's important to note that assignment operators in C++ can be overloaded for user-defined types, allowing custom behavior for assignment. However, this explanation focuses on the built-in assignment operators for fundamental types.