Compound-Assignment Operators

  • Java Programming
  • PHP Programming
  • Javascript Programming
  • Delphi Programming
  • C & C++ Programming
  • Ruby Programming
  • Visual Basic
  • M.A., Advanced Information Systems, University of Glasgow

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 in Java

Java supports 11 compound-assignment operators:

Example Usage

To assign the result of an addition operation to a variable using the standard syntax:

But use a compound-assignment operator to effect the same outcome with the simpler syntax:

  • Popular Math Terms and Definitions
  • 10 Math Tricks That Will Blow Your Mind
  • Conditional Operators
  • Java Expressions Introduced
  • The 7 Best Programming Languages to Learn for Beginners
  • The Associative and Commutative Properties
  • The JavaScript Ternary Operator as a Shortcut for If/Else Statements
  • Parentheses, Braces, and Brackets in Math
  • Understanding the Concatenation of Strings in Java
  • Basic Guide to Creating Arrays in Ruby
  • Dividing Monomials in Basic Algebra
  • C++ Handling Ints and Floats
  • An Abbreviated JavaScript If Statement
  • Using the Switch Statement for Multiple Choices in Java
  • How to Make Deep Copies in Ruby
  • Definition of Variable

Java Compound Operators

Last updated: March 17, 2024

what is a compound assignment operator

  • Java Operators

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Now that the new version of REST With Spring - “REST With Spring Boot” is finally out, the current price will be available until this Friday , after which it will permanently increase by 50$

>> GET ACCESS NOW

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

The Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

And, you can participate in a very quick (1 minute) paid user research from the Java on Azure product team.

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

>> Try out the Profiler

A quick guide to materially improve your tests with Junit 5:

Do JSON right with Jackson

Download the E-book

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll have a look at Java compound operators, their types and how Java evaluates them.

We’ll also explain how implicit casting works.

2. 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:

This statement declares a new variable x , assigns x the value of 5 and returns 5 .

Compound Assignment Operators are a shorter way to apply an arithmetic or bitwise operation and to assign the value of the operation to the variable on the left-hand side.

For example, the following two multiplication statements are equivalent, meaning  a and b will have the same value:

It’s important to note that the variable on the left-hand of a compound assignment operator must be already declared. In other words,  compound operators can’t be used to declare a new variable.

Like the “=” assignment operator, compound operators return the assigned result of the expression:

Both x and y will hold the value 3 .

The assignment (x+=2) does two things: first, it adds 2 to the value of the variable x , which becomes  3;  second, it returns the value of the assignment, which is also 3 .

3. Types of Compound Assignment Operators

Java supports 11 compound assignment operators. We can group these into arithmetic and bitwise operators.

Let’s go through the arithmetic operators and the operations they perform:

  • Incrementation: +=
  • Decrementation: -=
  • Multiplication: *=
  • Division: /=
  • Modulus: %=

Then, we also have the bitwise operators:

  • AND, binary: &=
  • Exclusive OR, binary: ^=
  • Inclusive OR, binary: |=
  • Left Shift, binary: <<=
  • Right Shift, binary: >>=
  • Shift right zero fill: >>>=

Let’s have a look at a few examples of these operations:

As we can see here, the syntax to use these operators is consistent.

4. Evaluation of Compound Assignment Operations

There are two ways Java evaluates the compound operations.

First, when the left-hand operand is not an array, then Java will, in order:

  • Verify the operand is a declared variable
  • Save the value of the left-hand operand
  • Evaluate the right-hand operand
  • Perform the binary operation as indicated by the compound operator
  • Convert the result of the binary operation to the type of the left-hand variable (implicit casting)
  • Assign the converted result to the left-hand variable

Next, when the left-hand operand is an array, the steps to follow are a bit different:

  • Verify the array expression on the left-hand side and throw a NullPointerException  or  ArrayIndexOutOfBoundsException if it’s incorrect
  • Save the array element in the index
  • Check if the array component selected is a primitive type or reference type and then continue with the same steps as the first list, as if the left-hand operand is a variable.

If any step of the evaluation fails, Java doesn’t continue to perform the following steps.

Let’s give some examples related to the evaluation of these operations to an array element:

As we’d expect, this will throw a  NullPointerException .

However, if we assign an initial value to the array:

We would get rid of the NullPointerException, but we’d still get an  ArrayIndexOutOfBoundsException , as the index used is not correct.

If we fix that, the operation will be completed successfully:

Finally, the x variable will be 6 at the end of the assignment.

5. Implicit Casting

One of the reasons compound operators are useful is that not only they provide a shorter way for operations, but also implicitly cast variables.

Formally, a compound assignment expression of the form:

is equivalent to:

E1 – (T)(E1 op E2)

where T is the type of E1 .

Let’s consider the following example:

Let’s review why the last line won’t compile.

Java automatically promotes smaller data types to larger data ones, when they are together in an operation, but will throw an error when trying to convert from larger to smaller types .

So, first,  i will be promoted to long and then the multiplication will give the result 10L. The long result would be assigned to i , which is an int , and this will throw an error.

This could be fixed with an explicit cast:

Java compound assignment operators are perfect in this case because they do an implicit casting:

This statement works just fine, casting the multiplication result to int and assigning the value to the left-hand side variable, i .

6. Conclusion

In this article, we looked at compound operators in Java, giving some examples and different types of them. We explained how Java evaluates these operations.

Finally, we also reviewed implicit casting, one of the reasons these shorthand operators are useful.

As always, all of the code snippets mentioned in this article can be found in our GitHub repository .

Slow MySQL query performance is all too common. Of course it is.

The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Build your API with SPRING - book cover

Javatpoint Logo

Java Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

In , assignment is used to assign values to a variable. In this section, we will discuss the .

The 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 in shorter syntax forms. In short, the compound assignment operator can be used in place of an assignment operator.

For example:

Let's write the above statements using the compound assignment operator.

Using both assignment operators generates the same result.

Java supports the following assignment operators:

Catagories Operator Description Example Equivalent Expression
It assigns the result of the addition. count += 1 count = count + 1
It assigns the result of the subtraction. count -= 2 count = count - 2
It assigns the result of the multiplication. price *= quantity price = price * quantity
It assigns the result of the division. average /= number_of_terms average = number_of_terms
It assigns the result of the remainder of the division. s %= 1000 s = s % 1000
It assigns the result of the signed left bit shift. res <<= num res = res << num
It assigns the result of the signed right bit shift. y >>= 1 y = y >> 1
It assigns the result of the logical AND. x &= 2 x = x & 2
It assigns the result of the logical XOR. a ^= b a = a ^ b
It assigns the result of the logical OR. flag |= true flag = flag | true
It assigns the result of the unsigned right bit shift. p >>>= 4 p = p >>> 4

Using Compound Assignment Operator in a Java Program

CompoundAssignmentOperator.java

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

cppreference.com

Assignment operators.

(C11)
Miscellaneous
General
(C11)
(C99)

Assignment and compound assignment operators are binary operators that modify the variable to their left using the value to their right.

Operator Operator name Example Description Equivalent of
= basic assignment a = b becomes equal to
+= addition assignment a += b becomes equal to the addition of and a = a + b
-= subtraction assignment a -= b becomes equal to the subtraction of from a = a - b
*= multiplication assignment a *= b becomes equal to the product of and a = a * b
/= division assignment a /= b becomes equal to the division of by a = a / b
%= modulo assignment a %= b becomes equal to the remainder of divided by a = a % b
&= bitwise AND assignment a &= b becomes equal to the bitwise AND of and a = a & b
|= bitwise OR assignment a |= b becomes equal to the bitwise OR of and a = a | b
^= bitwise XOR assignment a ^= b becomes equal to the bitwise XOR of and a = a ^ b
<<= bitwise left shift assignment a <<= b becomes equal to left shifted by a = a << b
>>= bitwise right shift assignment a >>= b becomes equal to right shifted by a = a >> b
Simple assignment Notes Compound assignment References See Also See also

[ edit ] Simple assignment

The simple assignment operator expressions have the form

lhs rhs
lhs - expression of any complete object type
rhs - expression of any type to lhs or with lhs

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-lvalue (so that expressions such as ( a = b ) = c are invalid).

rhs and lhs must satisfy one of the following:

  • both lhs and rhs have compatible struct or union type, or..
  • rhs must be implicitly convertible to lhs , which implies
  • both lhs and rhs have arithmetic types , in which case lhs may be volatile -qualified or atomic (since C11)
  • both lhs and rhs have pointer to compatible (ignoring qualifiers) types, or one of the pointers is a pointer to void, and the conversion would not add qualifiers to the pointed-to type. lhs may be volatile or restrict (since C99) -qualified or atomic (since C11) .
  • lhs is a (possibly qualified or atomic (since C11) ) pointer and rhs is a null pointer constant such as NULL or a nullptr_t value (since C23)
has type (possibly qualified or atomic(since C11)) _Bool and rhs is a pointer or a value(since C23) (since C99)
has type (possibly qualified or atomic) and rhs has type (since C23)

[ edit ] Notes

If rhs and lhs overlap in memory (e.g. they are members of the same union), the behavior is undefined unless the overlap is exact and the types are compatible .

Although arrays are not assignable, an array wrapped in a struct is assignable to another object of the same (or compatible) struct type.

The side effect of updating lhs is sequenced after the value computations, but not the side effects of lhs and rhs themselves and the evaluations of the operands are, as usual, unsequenced relative to each other (so the expressions such as i = ++ i ; are undefined)

Assignment strips extra range and precision from floating-point expressions (see FLT_EVAL_METHOD ).

In C++, assignment operators are lvalue expressions, not so in C.

[ edit ] Compound assignment

The compound assignment operator expressions have the form

lhs op rhs
op - one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |=
lhs, rhs - expressions with (where lhs may be qualified or atomic), except when op is += or -=, which also accept pointer types with the same restrictions as + and -

The expression lhs @= rhs is exactly the same as lhs = lhs @ ( rhs ) , except that lhs is evaluated only once.

If lhs has type, the operation behaves as a single atomic read-modify-write operation with memory order .

For integer atomic types, the compound assignment @= is equivalent to:

addr = &lhs; T2 val = rhs; T1 old = *addr; T1 new; do { new = old @ val } while (! (addr, &old, new);
(since C11)

[ edit ] References

  • C17 standard (ISO/IEC 9899:2018):
  • 6.5.16 Assignment operators (p: 72-73)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.5.16 Assignment operators (p: 101-104)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.5.16 Assignment operators (p: 91-93)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 3.3.16 Assignment operators

[ edit ] See Also

Operator precedence

Common operators

a = b
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)

[ edit ] See also

for Assignment operators
  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 19 August 2022, at 09:36.
  • This page has been accessed 58,085 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

What are Compound Assignment Operators in Java and Why You Should Use Them

Cover image for What are Compound Assignment Operators in Java and Why You Should Use Them

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

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:

Compound Assignment Operator using Subtraction

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.

what is a compound assignment operator

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • 1.1 Getting Started
  • 1.1.1 Preface
  • 1.1.2 About the AP CSA Exam
  • 1.1.3 Transitioning from AP CSP to AP CSA
  • 1.1.4 Java Development Environments
  • 1.1.5 Growth Mindset and Pair Programming
  • 1.1.6 Pretest for the AP CSA Exam
  • 1.1.7 Survey
  • 1.2 Why Programming? Why Java?
  • 1.3 Variables and Data Types
  • 1.4 Expressions and Assignment Statements
  • 1.5 Compound Assignment Operators
  • 1.6 Casting and Ranges of Values
  • 1.7 Unit 1 Summary
  • 1.8 Mixed Up Code Practice
  • 1.9 Toggle Mixed Up or Write Code Practice
  • 1.10 Coding Practice
  • 1.11 Multiple Choice Exercises
  • 1.4. Expressions and Assignment Statements" data-toggle="tooltip">
  • 1.6. Casting and Ranges of Values' data-toggle="tooltip" >

Before you keep reading...

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.

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 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.

exercise

1-5-2: What are the values of x, y, and z after the following code executes?

  • x = -1, y = 1, z = 4
  • This code subtracts one from x, adds one to y, and then sets z to to the value in z plus the current value of y.
  • x = -1, y = 2, z = 3
  • x = -1, y = 2, z = 2
  • x = 0, y = 1, z = 2
  • x = -1, y = 2, z = 4

1-5-3: What are the values of x, y, and z after the following code executes?

  • x = 6, y = 2.5, z = 2
  • This code sets x to z * 2 (4), y to y divided by 2 (5 / 2 = 2) and z = to z + 1 (2 + 1 = 3).
  • x = 4, y = 2.5, z = 2
  • x = 6, y = 2, z = 3
  • x = 4, y = 2.5, z = 3
  • x = 4, y = 2, z = 3

1.5.1. Code Tracing Challenge and Operators Maze ¶

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.

../_images/traceTable.png

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!

1.5.2. Summary ¶

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.

  • Trending Now
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial

Assignment Operators in Programming

  • Arithmetic Operators in Programming
  • Binary Operators in Programming
  • Operator Associativity in Programming
  • C++ Assignment Operator Overloading
  • What are Operators in Programming?
  • Assignment Operators In C++
  • Bitwise AND operator in Programming
  • Increment and Decrement Operators in Programming
  • Types of Operators in Programming
  • Logical AND operator in Programming
  • Modulus Operator in Programming
  • Solidity - Assignment Operators
  • Augmented Assignment Operators in Python
  • Pre Increment and Post Increment Operator in Programming
  • JavaScript Assignment Operators
  • Operator Precedence and Associativity in Programming
  • Assignment Operators in Python
  • Assignment Operators in C
  • Subtraction Assignment( -=) Operator in Javascript

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

What are Assignment Operators?

  • Types of Assignment Operators
  • Assignment Operators in C++
  • Assignment Operators in Java
  • Assignment Operators in C#
  • Assignment Operators in Javascript
  • Application of Assignment Operators

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.

Types of Assignment Operators:

  • Simple Assignment Operator ( = )
  • Addition Assignment Operator ( += )
  • Subtraction Assignment Operator ( -= )
  • Multiplication Assignment Operator ( *= )
  • Division Assignment Operator ( /= )
  • Modulus Assignment Operator ( %= )

Below is a table summarizing common assignment operators along with their symbols, description, and examples:

OperatorDescriptionExamples
= (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 

Assignment Operators in C:

Here are the implementation of Assignment Operator in C language:

Assignment Operators in C++:

Here are the implementation of Assignment Operator in C++ language:

Assignment Operators in Java:

Here are the implementation of Assignment Operator in java language:

Assignment Operators in Python:

Here are the implementation of Assignment Operator in python language:

Assignment Operators in C#:

Here are the implementation of Assignment Operator in C# language:

Assignment Operators in Javascript:

Here are the implementation of Assignment Operator in javascript language:

Application of Assignment Operators:

  • Variable Initialization : Setting initial values to variables during declaration.
  • Mathematical Operations : Combining arithmetic operations with assignment to update variable values.
  • Loop Control : Updating loop variables to control loop iterations.
  • Conditional Statements : Assigning different values based on conditions in conditional statements.
  • Function Return Values : Storing the return values of functions in variables.
  • Data Manipulation : Assigning values received from user input or retrieved from databases to variables.

Conclusion:

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.

Please Login to comment...

Similar reads.

  • Programming

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Read Tutorial
  • Watch Guide Video
  • Complete the Exercise

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.

large

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.

  • Documentation for Compound Assignment Operators
  • Source code

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.

Assignment operators (C# reference)

  • 11 contributors

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 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.

Compound assignment

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.

Null-coalescing assignment

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.

Operator overloadability

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.

C# language specification

For more information, see the Assignment operators section of the C# language specification .

  • C# operators and expressions
  • ref keyword
  • Use compound assignment (style rules IDE0054 and IDE0074)

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

Additional resources

Trending Articles on Technical and Non Technical topics

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Compound Assignment Operators in C++

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 −

  • An arithmetic type
  • A pointer, if op is + or –

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.

Govinda Sai

Related Articles

  • Compound assignment operators in C#
  • Compound assignment operators in Java\n
  • Perl Assignment Operators
  • Assignment operators in Dart Programming
  • Compound operators in Arduino
  • What is the difference between = and: = assignment operators?
  • Passing the Assignment in C++
  • Airplane Seat Assignment Probability in C++
  • Copy constructor vs assignment operator in C++
  • Unary operators in C/C++
  • Ternary Operators in C/C++
  • Operators Precedence in C++
  • Unary operators in C++
  • # and ## Operators in C ?
  • Bitwise Operators in C

Kickstart Your Career

Get certified by completing the course

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

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.

Overloading compound assignment operator

Is it necessary to overload the += operator even if we have already overloaded the + and the = operators?

  • operator-overloading

Niall's user avatar

  • 1 Doing addition and then assignment is not the same thing as doing += . Then end result may be the same, but different things are happening. This is especially important to remember if any overloaded operator have side-effects (intended or not). –  Some programmer dude Commented Feb 2, 2016 at 11:09

2 Answers 2

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.

Community's user avatar

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.

songyuanyao's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

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 .

Not the answer you're looking for? Browse other questions tagged c++ operator-overloading or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • The return of Staging Ground to Stack Overflow
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • Can apophatic theology offer a coherent resolution to the "problem of the creator of God"?
  • What is the explicit list of the situations that require RAII?
  • How to fix patchy garden and turn in into lush garden
  • Is there some sort of kitchen utensil/device like a cylinder with a strainer?
  • Rewarding the finding of zeroes of a hash function
  • Do I need to staple cable for new wire run through a preexisting wall?
  • Transpose these notes!
  • Who knows the tasks where the same fact is used by different parties to their advantage?
  • How can I get all results concatenated from a column group by UID?
  • Who is a "sibling"?
  • Creating a command to display blackboard font
  • Do wererats take falling damage?
  • How to turn a desert into a fertile farmland with engineering?
  • Do differently rendered measure numbers convey meaning?
  • What does it mean for observations to be uncorrelated and have constant variance?
  • Are the complex numbers a graded algebra?
  • Is the defendant liable for attempted murder when the attempt resulted in the death of an unintended second victim?
  • TikZ - diagram of a 1D spin chain
  • Freewheeling diode in a capacitor
  • The rules of alliteration in Germanic poetry as they pertain to single syllable triple consonant clusters starting with the letter s
  • Is zip tie a durable way to carry a spare tube on a frame?
  • Hard-to-find historical grey literature - any tips?
  • What was the submarine in the film "Ice Station Zebra"?
  • What happened to Slic3r?

what is a compound assignment operator

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Comma operator (,)

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.

Description

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:

  • Elements in array initializers ( [1, 2, 3] )
  • Properties in object initializers ( { a: 1, b: 2 } )
  • Parameters in function declarations /expressions ( function f(a, b) { … } )
  • Arguments in function calls ( f(1, 2) )
  • Binding lists in let , const , or var declarations ( const a = 1, b = 2; )
  • Import lists in import declarations ( import { a, b } from "c"; )
  • Export lists in export declarations ( export { a, b }; )

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 .

Using the comma operator in a for loop

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:

Using the comma operator to join assignments

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.

Processing and then returning

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() :

Discarding reference binding

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.

Specifications

Specification

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

IMAGES

  1. PPT

    what is a compound assignment operator

  2. PPT

    what is a compound assignment operator

  3. PPT

    what is a compound assignment operator

  4. PPT

    what is a compound assignment operator

  5. PPT

    what is a compound assignment operator

  6. Exploring Compound Assignment Operators in C

    what is a compound assignment operator

VIDEO

  1. Compound Assignment Operator and Escape Character in Python #50

  2. Lecture 5

  3. Compound assignment operator in C++ Programming Practice Course Tutorial #shorts #programming #viral

  4. PGC lecture || Types of Operators (part 2)

  5. Java for Testers

  6. CPP Lect08: Compound Assignment Statement

COMMENTS

  1. What Is a Compound-Assignment Operator?

    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.

  2. Compound assignment operators in Java

    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.

  3. Assignment operators

    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.

  4. C Compound Assignment

    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.

  5. Assignment Operators In C++

    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++:

  6. Assignment operators

    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:

  7. Java Compound Operators

    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 ...

  8. Compound Assignment Operator in Java

    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 ...

  9. Compound Assignment Operators in Java (With Examples)

    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.

  10. PDF Compound assignment operators

    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.

  11. Assignment operators

    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 ...

  12. 1.5. Compound Assignment Operators

    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.

  13. Compound assignment operators

    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:

  14. What are Compound Assignment Operators in Java and Why You Should Use

    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.

  15. 1.5. Compound Assignment Operators

    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 ...

  16. Assignment Operators in Programming

    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 ...

  17. Guide to Compound Assignment Operators in JavaScript

    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.

  18. Assignment operators

    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.

  19. Compound Assignment Operators in C++

    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 ...

  20. c

    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 ...

  21. Compound assignment in C++

    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:

  22. c++

    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 ...

  23. Comma operator (,)

    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])

  24. Compound assignment operators

    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 ...