The latest version of this topic can be found at C Assignment Operators.
An assignment operation assigns the value of the right-hand operand to the storage location named by the left-hand operand. Therefore, the left-hand operand of an assignment operation must be a modifiable l-value. After the assignment, an assignment expression has the value of the left operand but is not an l-value.
unary-expression assignment-operator assignment-expression
assignment-operator: one of
= *=–= <<= >>= &=
The assignment operators in C can both transform and assign values in a single operation. C provides the following assignment operators:
In assignment, the type of the right-hand value is converted to the type of the left-hand value, and the value is stored in the left operand after the assignment has taken place. The left operand must not be an array, a function, or a constant. The specific conversion path, which depends on the two types, is outlined in detail in Type Conversions.
In this tutorial we will learn about assignment operators in C programming language.
We use the assignment operators to assign the result of an expression to a variable.
In the following example we are assigning integer value 10 to a variable score of data type integer.
Shorthand Assignment Operators
Lets say we have an integer variable and we have initially assigned 10 to it. Then lets say we increase the value by 5 and assign the new value to it.
Another way to write the code is by using the shorthand assignment as shown below.
Following is a list of shorthand assignment operators.
|Simple assignment||Shorthand assignment|
|x = x + 1||x += 1|
|x = x - 1||x -= 1|
|x = x * (n + 1)||x *= (n + 1)|
|x = x / (n + 1)||x /= (n + 1)|
|x = x % y||x %= y|
In the following example we are taking a value x from user then we are taking a new value y from user. Then we are adding y to x and assigning the result to x. Finally we are printing the new value stored in variable x.
Another way of adding y to x and re-assigning the new value to x is by using the shorthand assignment operator .