a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b
++a
--a
a++
a--
+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b
!a
a && b
a || b
a == b
a != b
a < b
a > b
a <= b
a >= b
a[b]
*a
&a
a->b
a.b
a(...)
a, b
(type) a
a ? b : c
sizeof
_Alignof
(since C11)
for Assignment operators |
Compound assignment operators are commonly used as they require less code to type. It's a shorter syntax of assigning the result of an arithmetic or bitwise operator, given that the variable to store the expression value is being used as an operand .
Consider an example where we want to increase a given number by 3. The long version can be written as follows:
The number variable is used as the variable to store the expression value and as an operand. Because of this, we can use a shorter syntax of compound assignment operators. The code can be written as:
Let's see another example using string concatenation:
Using compound assignment operators, this can be condensed to:
As another example, let's see how we can decrease a number by 3:
Again, since number is used as the variable to store the expression value and an operand, we can use the compound assignment operator:
All arithmetic and bitwise operators can be used in compound assignment operators. This post shows examples using addition and subtraction to show the general syntax. Division, multiplication, modulus, AND, OR, XOR,left shift, right shift, and unsigned right shift would also work. Overall, using the compound assignment operator requires less code to type and is more common to see code written this way.
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
Time estimate: 45 min.
Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x . It is the same as x = x + 1 . This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound operators are written like += or =+ , just remember that the operation ( + ) is done first to produce the new value which is then assigned ( = ) back to the variable. So it’s operator then equal sign: += .
Since changing the value of a variable by one is especially common, there are two extra concise operators ++ and -- , also called the plus-plus or increment operator and minus-minus or decrement operator that set a variable to one greater or less than its current value.
Thus x++ is even more concise way to write x = x + 1 than the compound operator x += 1 . You’ll see this shortcut used a lot in loops when we get to them in Unit 4. Similarly, y-- is a more concise way to write y = y - 1 . These shortcuts only exist for + and - as they don’t really make sense for other operators.
If you’ve heard of the programming language C++, the name is an inside joke that C, an earlier language which C++ is based on, had been incremented or improved to create C++.
Here’s a table of all the compound arithmetic operators and the extra concise incremend and decrement operators and how they relate to fully written out assignment expressions. You can run the code below the table to see these shortcut operators in action!
Operator |
|
|
|
|
|
---|---|---|---|---|---|
Written out | = x + 1 | = x - 1 | = x * 2 | = x / 2 | = x % 2 |
Compound | += 1 | -= 1 | *= 2 | /= 2 | %= 2 |
Extra concise |
|
| |||
Run the code below to see what the ++ and shorcut operators do. Click on the Show Code Lens button to trace through the code and the variable values change in the visualizer. Try creating more compound assignment statements with shortcut operators and work with a partner to guess what they would print out before running the code.
If you look at real-world Java code, you may occassionally see the ++ and -- operators used before the name of the variable, like ++x rather than x++ . That is legal but not something that you will see on the AP exam.
Putting the operator before or after the variable only changes the value of the expression itself. If x is 10 and we write, System.out.println(x++) it will print 10 but aftewards x will be 11. On the other hand if we write, System.out.println(++x) , it will print 11 and afterwards the value will be 11.
In other words, with the operator after the variable name, (called the postfix operator) the value of the variable is changed after evaluating the variable to get its value. And with the operator before the variable (the prefix operator) the value of the variable in incremented before the variable is evaluated to get the value of the expression.
But the value of x after the expression is evaluated is the same in either case: one greater than what it was before. The -- operator works similarly.
The AP exam will never use the prefix form of these operators nor will it use the postfix operators in a context where the value of the expression matters.
1-5-2: What are the values of x, y, and z after the following code executes?
1-5-3: What are the values of x, y, and z after the following code executes?
Use paper and pencil or the question response area below to trace through the following program to determine the values of the variables at the end.
Code Tracing is a technique used to simulate a dry run through the code or pseudocode line by line by hand as if you are the computer executing the code. Tracing can be used for debugging or proving that your program runs correctly or for figuring out what the code actually does.
Trace tables can be used to track the values of variables as they change throughout a program. To trace through code, write down a variable in each column or row in a table and keep track of its value throughout the program. Some trace tables also keep track of the output and the line number you are currently tracing.
Trace through the following code:
1-5-4: Write your trace table for x, y, and z here showing their results after each line of code.
After doing this challenge, play the Operators Maze game . See if you and your partner can get the highest score!
Compound assignment operators ( += , -= , *= , /= , %= ) can be used in place of the assignment operator.
The increment operator ( ++ ) and decrement operator ( -- ) are used to add 1 or subtract 1 from the stored value of a variable. The new value is assigned to the variable.
The use of increment and decrement operators in prefix form (e.g., ++x ) and inside other expressions (i.e., arr[x++] ) is outside the scope of this course and the AP Exam.
Assignment operators in programming are symbols used to assign values to variables. They offer shorthand notations for performing arithmetic operations and updating variable values in a single step. These operators are fundamental in most programming languages and help streamline code while improving readability.
Table of Content
Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign ( = ), which assigns the value on the right side of the operator to the variable on the left side.
Below is a table summarizing common assignment operators along with their symbols, description, and examples:
Operator | Description | Examples |
---|---|---|
= (Assignment) | Assigns the value on the right to the variable on the left. | assigns the value 10 to the variable x. |
+= (Addition Assignment) | Adds the value on the right to the current value of the variable on the left and assigns the result to the variable. | is equivalent to |
-= (Subtraction Assignment) | Subtracts the value on the right from the current value of the variable on the left and assigns the result to the variable. | is equivalent to |
*= (Multiplication Assignment) | Multiplies the current value of the variable on the left by the value on the right and assigns the result to the variable. | is equivalent to |
/= (Division Assignment) | Divides the current value of the variable on the left by the value on the right and assigns the result to the variable. | is equivalent to |
%= (Modulo Assignment) | Calculates the modulo of the current value of the variable on the left and the value on the right, then assigns the result to the variable. | is equivalent to |
Here are the implementation of Assignment Operator in C language:
Here are the implementation of Assignment Operator in C++ language:
Here are the implementation of Assignment Operator in java language:
Here are the implementation of Assignment Operator in python language:
Here are the implementation of Assignment Operator in C# language:
Here are the implementation of Assignment Operator in javascript language:
In conclusion, assignment operators in programming are essential tools for assigning values to variables and performing operations in a concise and efficient manner. They allow programmers to manipulate data and control the flow of their programs effectively. Understanding and using assignment operators correctly is fundamental to writing clear, efficient, and maintainable code in various programming languages.
Similar reads.
Now that we've talked about operators. Let's talk about something called the compound assignment operator and I'm going make one little change here in case you're wondering if you ever want to have your console take up the entire window you come up to the top right-hand side here you can undock it into a separate window and you can see that it takes up the entire window.
So just a little bit more room now.
Additionally, I have one other thing I'm going to show you in the show notes. I'm going to give you access to this entire set of assignment operators but we'll go through a few examples here. I'm going to use the entire window just to make it a little bit easier to see.
Let's talk about what assignment is. Now we've been using assignment ever since we started writing javascript code. You're probably pretty used to it. Assignment is saying something like var name and then setting up a name
And that is assignment the equals represents assignment.
Now javascript gives us the ability to have the regular assignment but also to have that assignment perform tasks. So for example say that you want to add items up so say that we want to add up a total set of grades to see the total number of scores. I can say var sum and assign it equal to zero.
And now let's create some grades.
I'm going to say var gradeOne = 100.
and then var gradeTwo = 80.
Now with both of these items in place say that we wanted to add these if you wanted to just add both of them together you definitely could do something like sum = (gradeOne + gradeTwo); and that would work.
However, one thing I want to show you is, there are many times where you don't have gradeOne or gradeTwo in a variable. You may have those stored in a database and then you're going to loop through that full set of records. And so you need to be able to add them on the fly. And so that's what a compound assignment operator can do.
Let's use one of the more basic ones which is to have the addition assignment.
Now you can see that sum is equal to 100.
Then if I do
If we had 100 grades we could simply add them just like that.
Essentially what this is equal to is it's a shorthand for saying something like
sum = sum + whatever the next one is say, that we had a gradeThree, it would be the same as doing that. So it's performing assignment, but it also is performing an operation. That's the reason why it's called a compound assignment operator.
Now in addition to having the ability to sum items up, you could also do the same thing with the other operators. In fact literally, every one of the operators that we just went through you can use those in order to do this compound assignment. Say that you wanted to do multiplication you could do sum astrix equals and then gradeTwo and now you can see it equals fourteen thousand four hundred.
This is that was the exact same as doing sum = whatever the value of sum was times gradeTwo. That gives you the exact same type of process so that is how you can use the compound assignment operators. And if you reference the guide that is included in the show notes. You can see that we have them for each one of these from regular equals all the way through using exponents.
Then for right now don't worry about the bottom items. These are getting into much more advanced kinds of fields like bitwise operators and right and left shift assignments. So everything you need to focus on is actually right at the top for how we're going to be doing this. This is something that you will see in a javascript code. I wanted to include it, so when you see it you're not curious about exactly what's happening.
It's a great shorthand syntax for whenever you want to do assignment but also perform an operation at the same time.
devCamp does not support ancient browsers. Install a modern version for best experience.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
The assignment operator = assigns the value of its right-hand operand to a variable, a property , or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand. The type of the right-hand operand must be the same as the type of the left-hand operand or implicitly convertible to it.
The assignment operator = is right-associative, that is, an expression of the form
is evaluated as
The following example demonstrates the usage of the assignment operator with a local variable, a property, and an indexer element as its left-hand operand:
The left-hand operand of an assignment receives the value of the right-hand operand. When the operands are of value types , assignment copies the contents of the right-hand operand. When the operands are of reference types , assignment copies the reference to the object.
This is called value assignment : the value is assigned.
Ref assignment = ref makes its left-hand operand an alias to the right-hand operand, as the following example demonstrates:
In the preceding example, the local reference variable arrayElement is initialized as an alias to the first array element. Then, it's ref reassigned to refer to the last array element. As it's an alias, when you update its value with an ordinary assignment operator = , the corresponding array element is also updated.
The left-hand operand of ref assignment can be a local reference variable , a ref field , and a ref , out , or in method parameter. Both operands must be of the same type.
For a binary operator op , a compound assignment expression of the form
is equivalent to
except that x is only evaluated once.
Compound assignment is supported by arithmetic , Boolean logical , and bitwise logical and shift operators.
You can use the null-coalescing assignment operator ??= to assign the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null . For more information, see the ?? and ??= operators article.
A user-defined type can't overload the assignment operator. However, a user-defined type can define an implicit conversion to another type. That way, the value of a user-defined type can be assigned to a variable, a property, or an indexer element of another type. For more information, see User-defined conversion operators .
A user-defined type can't explicitly overload a compound assignment operator. However, if a user-defined type overloads a binary operator op , the op= operator, if it exists, is also implicitly overloaded.
For more information, see the Assignment operators section of the C# language specification .
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .
Submit and view feedback for
The compound assignment operators are specified in the form e1 op= e2, where e1 is a modifiable l-value not of const type and e2 is one of the following −
The e1 op= e2 form behaves as e1 = e1 op e2, but e1 is evaluated only once.
The following are the compound assignment operators in C++ −
Operators | Description |
---|---|
*= | Multiply the value of the first operand by the value of the second operand; store the result in the object specified by the first operand. |
/= | Divide the value of the first operand by the value of the second operand; store the result in the object specified by the first operand. |
%= | Take modulus of the first operand specified by the value of the second operand; store the result in the object specified by the first operand. |
+= | Add the value of the second operand to the value of the first operand; store the result in the object specified by the first operand. |
–= | Subtract the value of the second operand from the value of the first operand; store the result in the object specified by the first operand. |
<<= | Shift the value of the first operand left the number of bits specified by the value of the second operand; store the result in the object specified by the first operand. |
>>= | Shift the value of the first operand right the number of bits specified by the value of the second operand; store the result in the object specified by the first operand. |
&= | Obtain the bitwise AND of the first and second operands; store the result in the object specified by the first operand. |
^= | Obtain the bitwise exclusive OR of the first and second operands; store the result in the object specified by the first operand. |
|= | Obtain the bitwise inclusive OR of the first and second operands; store the result in the object specified by the first operand. |
Let's have a look at an example using some of these operators −
This will give the output −
Note that Compound assignment to an enumerated type generates an error message. If the left operand is of a pointer type, the right operand must be of a pointer type or it must be a constant expression that evaluates to 0. If the left operand is of an integral type, the right operand must not be of a pointer type.
Related Articles
Get certified by completing the course
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
Is it necessary to overload the += operator even if we have already overloaded the + and the = operators?
Are you going to use the += operator? If yes, then yes, you should overload it.
The compiler does not automatically create one even if you have overloaded the operator+ and assignment operator. You can implemented them in terms of each other, but they all need to be implemented. In general, the addition and assignment will do the same thing as the compound assignment, but this is not always the case.
In general, when overloading the arithmetic operators ( + , - etc.) you should do them with their associated compound assignments as well ( += , -= etc.).
See the "Binary arithmetic operators" on cppreference for some canonical implementations.
class X { public: X& operator+=(const X& rhs) // compound assignment (does not need to be a member, { // but often is, to modify the private members) /* addition of rhs to *this takes place here */ return *this; // return the result by reference } // friends defined inside class body are inline and are hidden from non-ADL lookup friend X operator+(X lhs, // passing lhs by value helps optimize chained a+b+c const X& rhs) // otherwise, both parameters may be const references { lhs += rhs; // reuse compound assignment return lhs; // return the result by value (uses move constructor) } };
This SO Q&A for some basic rules on overloading.
Yes, in general it's a good idea to provide the same behaviour with build-in types (such as int ) when implement operator overloading, to avoid confusing.
And without operator+= , you have to use operator+ and operator= to do the same thing. Even with RVO, once more copy will be applied.
If you decide to implement operator+= , it's better to use it to implement operator+ for the consistency.
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
The comma ( , ) operator evaluates each of its operands (from left to right) and returns the value of the last operand. This is commonly used to provide multiple updaters to a for loop's afterthought.
One or more expressions, the last of which is returned as the value of the compound expression.
You can use the comma operator when you want to include multiple expressions in a location that requires a single expression. The most common usage of this operator is to supply multiple updaters in a for loop.
Because all expressions except the last are evaluated and then discarded, these expressions must have side effects to be useful. Common expressions that have side effects are assignments, function calls, and ++ and -- operators. Others may also have side effects if they invoke getters or trigger type coercions .
The comma operator has the lowest precedence of all operators. If you want to incorporate a comma-joined expression into a bigger expression, you must parenthesize it.
The comma operator is completely different from commas used as syntactic separators in other locations, which include:
In fact, although some of these places accept almost all expressions, they don't accept comma-joined expressions because that would be ambiguous with the syntactic comma separators. In this case, you must parenthesize the comma-joined expression. For example, the following is a const declaration that declares two variables, where the comma is not the comma operator:
It is different from the following, where b = 2 is an assignment expression , not a declaration. The value of a is 2 , the return value of the assignment, while the value of 1 is discarded:
Comma operators cannot appear as trailing commas .
If a is a 2-dimensional array with 10 elements on each side, the following code uses the comma operator to increment i and decrement j at once, thus printing the values of the diagonal elements in the array:
Because commas have the lowest precedence — even lower than assignment — commas can be used to join multiple assignment expressions. In the following example, a is set to the value of b = 3 (which is 3). Then, the c = 4 expression evaluates and its result becomes the return value of the entire comma expression.
Another example that one could make with the comma operator is processing before returning. As stated, only the last element will be returned but all others are going to be evaluated as well. So, one could do:
This is especially useful for one-line arrow functions . The following example uses a single map() to get both the sum of an array and the squares of its elements, which would otherwise require two iterations, one with reduce() and one with map() :
The comma operator always returns the last expression as a value instead of a reference . This causes some contextual information such as the this binding to be lost. For example, a property access returns a reference to the function, which also remembers the object that it's accessed on, so that calling the property works properly. If the method is returned from a comma expression, then the function is called as if it's a new function value, and this is undefined .
You can enter indirect eval with this technique, because direct eval requires the function call to happen on the reference to the eval() function.
Specification |
---|
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
IMAGES
VIDEO
COMMENTS
Compound-Assignment Operators. Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand.
Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand. The following are all possible assignment operator in java: 1.
The built-in assignment operators return the value of the object specified by the left operand after the assignment (and the arithmetic/logical operation in the case of compound assignment operators). The resultant type is the type of the left operand. The result of an assignment expression is always an l-value.
The compound-assignment operators combine the simple-assignment operator with another binary operator. Compound-assignment operators perform the operation specified by the additional operator, then assign the result to the left operand. For example, a compound-assignment expression such as. expression1 += expression2. can be understood as.
Compound Assignment Operators. In C++, the assignment operator can be combined into a single operator with some other operators to perform a combination of two operations in one single statement. These operators are called Compound Assignment Operators. There are 10 compound assignment operators in C++:
For all other compound assignment operators, the type of target-expr must be an arithmetic type. In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:
Compound Assignment Operators. An assignment operator is a binary operator that assigns the result of the right-hand side to the variable on the left-hand side. The simplest is the "=" assignment operator: int x = 5; This statement declares a new variable x, assigns x the value of 5 and returns 5. Compound Assignment Operators are a shorter ...
The compound assignment operator is the combination of more than one operator. It includes an assignment operator and arithmetic operator or bitwise operator. The specified operation is performed between the right operand and the left operand and the resultant assigned to the left operand. Generally, these operators are used to assign results ...
Compound assignment operators are a shorthand for combining an operation with an assignment. While you can achieve similar results using regular arithmetic operators and separate assignment statements, compound assignment operators offer a more concise and elegant syntax.
The compound operators are different in two ways, which we see by looking more precisely at their definition. The Java language specification says that: The compound assignment E1 op= E2 is equivalent to [i.e. is syntactic sugar for] E1 = (T) ((E1) op (E2)) where T is the type of E1, except that E1 is evaluated only once.
Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs . Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non ...
1.5. Compound Assignment Operators ¶. Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to x and assigns the sum to x. It is the same as x = x + 1. This pattern is possible with any operator put in front of the = sign, as seen below. + shortcuts. - shortcuts.
The compound assignment operators consist of a binary operator and the simple assignment operator. They perform the operation of the binary operator on both operands and store the result of that operation into the left operand, which must be a modifiable lvalue. The following table shows the operand types of compound assignment expressions:
Compound assignment operators are commonly used as they require less code to type. It's a shorter syntax of assigning the result of an arithmetic or bitwise operator, given that the variable to store the expression value is being used as an operand. Compound Assignment Operator using Addition.
1.5. Compound Assignment Operators¶. Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x.It is the same as x = x + 1.This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound ...
Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...
And so you need to be able to add them on the fly. And so that's what a compound assignment operator can do. Let's use one of the more basic ones which is to have the addition assignment. sum += gradeOne; // 100. Now you can see that sum is equal to 100. Then if I do. sum += gradeTwo; // 180.
Compound assignment. For a binary operator op, a compound assignment expression of the form. x op= y is equivalent to. x = x op y except that x is only evaluated once. Compound assignment is supported by arithmetic, Boolean logical, and bitwise logical and shift operators.
The compound assignment operators are specified in the form e1 op= e2, where e1 is a modifiable l-value not of const type and e2 is one of the following −. The e1 op= e2 form behaves as e1 = e1 op e2, but e1 is evaluated only once. The following are the compound assignment operators in C++ −. Multiply the value of the first operand by the ...
According to Microsoft, "However, the compound-assignment expression is not equivalent to the expanded version because the compound-assignment expression evaluates expression1 only once, while the expanded version evaluates expression1 twice: in the addition operation and in the assignment operation". Here is what I am expecting some kind of ...
The compound assignment operators are in the second lowest precedence group of all in C++ (taking priority over only the comma operator). Thus, your a += b % c case would be equivalent to a += ( b % c ), or a = a + ( b % c ). This explains why your two code snippets are different. The second:
In general, the addition and assignment will do the same thing as the compound assignment, but this is not always the case. In general, when overloading the arithmetic operators ( +, - etc.) you should do them with their associated compound assignments as well ( +=, -= etc.). See the "Binary arithmetic operators" on cppreference for some ...
The comma operator has the lowest precedence of all operators. If you want to incorporate a comma-joined expression into a bigger expression, you must parenthesize it. The comma operator is completely different from commas used as syntactic separators in other locations, which include: Elements in array initializers ([1, 2, 3])
The compound assignment operators consist of a binary operator and the simple assignment operator. They perform the operation of the binary operator on both operands and store the result of that operation into the left operand, which must be a modifiable lvalue. The following table shows the operand types of compound assignment expressions: The ...