• Java Arrays
  • Java Strings
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Spring Boot

Compound assignment operators in Java

  • Java Assignment Operators with Examples
  • Basic Operators in Java
  • Bitwise Operators in Java
  • Difference between Simple and Compound Assignment in Java
  • Assignment Operators in C
  • Assignment Operators In C++
  • JavaScript Assignment Operators
  • Augmented Assignment Operators in Python
  • Assignment Operators in Python
  • Bitwise OR Assignment (|=) Operator in JavaScript
  • Bitwise AND Assignment (&=) Operator in JavaScript
  • Addition Assignment (+=) Operator in Javascript
  • Subtraction Assignment( -=) Operator in Javascript
  • Right Shift Assignment(>>=) Operator in JavaScript
  • Arithmetic Operators in C
  • Assignment Operators in Programming
  • Multiplication Assignment(*=) Operator in JavaScript
  • Self assignment check in assignment operator
  • 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:

Implementation of all compound assignment operator

Rules for resolving the Compound assignment operators

At run time, the expression is evaluated in one of two ways.Depending upon the programming conditions:

  • First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.
  • Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion to the appropriate standard value set, and the result of the conversion is stored into the variable.
  • First, the array reference sub-expression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the index sub-expression (of the left-hand operand array access expression) and the right-hand operand are not evaluated and no assignment occurs.
  • Otherwise, the index sub-expression of the left-hand operand array access expression is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and the right-hand operand is not evaluated and no assignment occurs.
  • Otherwise, if the value of the array reference sub-expression is null, then no assignment occurs and a NullPointerException is thrown.
  • Otherwise, the value of the array reference sub-expression indeed refers to an array. If the value of the index sub-expression is less than zero, or greater than or equal to the length of the array, then no assignment occurs and an ArrayIndexOutOfBoundsException is thrown.
  • Otherwise, the value of the index sub-expression is used to select a component of the array referred to by the value of the array reference sub-expression. The value of this component is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

Examples : Resolving the statements with Compound assignment operators

We all know that whenever we are assigning a bigger value to a smaller data type variable then we have to perform explicit type casting to get the result without any compile-time error. If we did not perform explicit type-casting then we will get compile time error. But in the case of compound assignment operators internally type-casting will be performed automatically, even we are assigning a bigger value to a smaller data-type variable but there may be a chance of loss of data information. The programmer will not responsible to perform explicit type-casting. Let’s see the below example to find the difference between normal assignment operator and compound assignment operator. A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

For example, the following code is correct:

and results in x having the value 7 because it is equivalent to:

Because here 6.6 which is double is automatically converted to short type without explicit type-casting.

Refer: When is the Type-conversion required?

Explanation: In the above example, we are using normal assignment operator. Here we are assigning an int (b+1=20) value to byte variable (i.e. b) that’s results in compile time error. Here we have to do type-casting to get the result.

Explanation: In the above example, we are using compound assignment operator. Here we are assigning an int (b+1=20) value to byte variable (i.e. b) apart from that we get the result as 20 because In compound assignment operator type-casting is automatically done by compile. Here we don’t have to do type-casting to get the result.

Reference: http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.26.2

Please Login to comment...

Similar reads.

  • Java-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Java Compound Operators

Last updated: March 17, 2024

examples of compound assignment

  • Java Operators

announcement - icon

Now that the new version of REST With Spring - “REST With Spring Boot” is finally out, the current price will be available until the 22nd of June , 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

Building a REST API with 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

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

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

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

Creating PDFs is actually surprisingly hard. When we first tried, none of the existing PDF libraries met our needs. So we made DocRaptor for ourselves and later launched it as one of the first HTML-to-PDF APIs.

We think DocRaptor is the fastest and most scalable way to make PDFs , especially high-quality or complex PDFs. And as developers ourselves, we love good documentation, no-account trial keys, and an easy setup process.

>> Try DocRaptor's HTML-to-PDF Java Client (No Signup Required)

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

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
  • Understanding the Concatenation of Strings in Java
  • 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
  • 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

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

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Assignment operators

  • 8 contributors

expression assignment-operator expression

assignment-operator : one of   =   *=   /=   %=   +=   -=   <<=   >>=   &=   ^=   |=

Assignment operators store a value in the object specified by the left operand. There are two kinds of assignment operations:

simple assignment , in which the value of the second operand is stored in the object specified by the first operand.

compound assignment , in which an arithmetic, shift, or bitwise operation is performed before storing the result.

All assignment operators in the following table except the = operator are compound assignment operators.

Assignment operators table

Operator Meaning
Store the value of the second operand in the object specified by the first operand (simple assignment).
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.

Operator keywords

Three of the compound assignment operators have keyword equivalents. They are:

Operator Equivalent

C++ specifies these operator keywords as alternative spellings for the compound assignment operators. In C, the alternative spellings are provided as macros in the <iso646.h> header. In C++, the alternative spellings are keywords; use of <iso646.h> or the C++ equivalent <ciso646> is deprecated. In Microsoft C++, the /permissive- or /Za compiler option is required to enable the alternative spelling.

Simple assignment

The simple assignment operator ( = ) causes the value of the second operand to be stored in the object specified by the first operand. If both objects are of arithmetic types, the right operand is converted to the type of the left, before storing the value.

Objects of const and volatile types can be assigned to l-values of types that are only volatile , or that aren't const or volatile .

Assignment to objects of class type ( struct , union , and class types) is performed by a function named operator= . The default behavior of this operator function is to perform a member-wise copy assignment of the object's non-static data members and direct base classes; however, this behavior can be modified using overloaded operators. For more information, see Operator overloading . Class types can also have copy assignment and move assignment operators. For more information, see Copy constructors and copy assignment operators and Move constructors and move assignment operators .

An object of any unambiguously derived class from a given base class can be assigned to an object of the base class. The reverse isn't true because there's an implicit conversion from derived class to base class, but not from base class to derived class. For example:

Assignments to reference types behave as if the assignment were being made to the object to which the reference points.

For class-type objects, assignment is different from initialization. To illustrate how different assignment and initialization can be, consider the code

The preceding code shows an initializer; it calls the constructor for UserType2 that takes an argument of type UserType1 . Given the code

the assignment statement

can have one of the following effects:

Call the function operator= for UserType2 , provided operator= is provided with a UserType1 argument.

Call the explicit conversion function UserType1::operator UserType2 , if such a function exists.

Call a constructor UserType2::UserType2 , provided such a constructor exists, that takes a UserType1 argument and copies the result.

Compound assignment

The compound assignment operators are shown in the Assignment operators table . These operators have the form e1 op = e2 , where e1 is a non- const modifiable l-value and e2 is:

an arithmetic type

a pointer, if op is + or -

a type for which there exists a matching operator *op*= overload for the type of e1

The built-in e1 op = e2 form behaves as e1 = e1 op e2 , but e1 is evaluated only once.

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. When the left operand is of an integral type, the right operand must not be of a pointer type.

Result of built-in 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. These operators have right-to-left associativity. The left operand must be a modifiable l-value.

In ANSI C, the result of an assignment expression isn't an l-value. That means the legal C++ expression (a += b) += c isn't allowed in C.

Expressions with binary operators C++ built-in operators, precedence, and associativity C assignment operators

Was this page helpful?

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

Logo image

Introduction to C-Programming: As seen in ENGS 20

Petra Bonfert-Taylor

Search Results:

Section 13.4 compound assignment operators.

If you cannot see this codecast, please click here .

Check Your Understanding Check Your Understanding

admin ..... open in new window

examples of compound assignment

pep

Find what you need to study

1.4 Compound Assignment Operators

7 min read • december 27, 2022

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

Compound Assignment Operators

Compound operators.

Sometimes, you will encounter situations where you need to perform the following operation:

This is a bit clunky with the repetition of integerOne in line two. We can condense this with this statement:

The "* = 2" is an example of a compound assignment operator , which multiplies the current value of integerOne by 2 and sets that as the new value of integerOne. Other arithmetic operators also have compound assignment operators as well, with addition, subtraction, division, and modulo having +=, -=, /=, and %=, respectively.

Incrementing and Decrementing

There are special operators for the two following operations in the following snippet well:

These can be replaced with a pre-increment /pre-decrement (++i or - -i) or post-increment /post-decrement (i++ or i- -) operator . You only need to know the post-variant in this course, but it is useful to know the difference between the two. Here is an example demonstrating the difference between them:

By itself, there is no difference between the pre-increment and post-increment operators, but it's evident when you use it in a method such as the println method. For this statement, I will write a debugging output , which happens when we trace the code, which means to follow it line-by-line.

Code Tracing Practice

Now that you’ve learned about code tracing , let’s do some practice! You can use trace tables like the ones shown below to keep track of the values of your variables as they change.

x

y

z

output

x

y

z

output

Here are some practice problems that you can use to practice code tracing . Feel free to use whichever method you’re the most comfortable with!

Trace through the following code:

Note: Your answers could look different depending on how you’re tracking your code tracing .

a *= 3: This line multiplies a by 3 and assigns the result back to a. The value of a is now 18.

b -= 2: This line subtracts 2 from b and assigns the result back to b. The value of b is now 2.

c = a % b: This line calculates the remainder of a divided by b and assigns the result to c. The value of c is now 0.

a += c: This line adds c to a and assigns the result back to a. The value of a is now 18.

b = a - b: This line subtracts b from a and assigns the result back to b. The value of b is now 16.

c *= b: This line multiplies c by b and assigns the result back to c. The value of c is now 0.

The final values of the variables are:

double x = 15.0;

double y = 4.0;

double z = 0;

x /= y: This line divides x by y and assigns the result back to x. The value of x is now 3.75.

y *= x: This line multiplies y by x and assigns the result back to y. The value of y is now 15.0.

z = y % x: This line calculates the remainder of y divided by x and assigns the result to z. The value of z is now 3.75.

x += z: This line adds z to x and assigns the result back to x. The value of x is now 7.5.

y = x / z: This line divides x by z and assigns the result back to y. The value of y is now 2.0.

z *= y: This line multiplies z by y and assigns the result back to z. The value of z is now 7.5.

int a = 100;

int b = 50;

int c = 25;

a -= b: This line subtracts b from a and assigns the result back to a. The value of a is now 50.

b *= 2: This line multiplies b by 2 and assigns the result back to b. The value of b is now 100.

c %= 4: This line calculates the remainder of c divided by 4 and assigns the result back to c. The value of c is now 1.

a = b + c: This line adds b and c and assigns the result to a. The value of a is now 101.

b = c - a: This line subtracts a from c and assigns the result to b. The value of b is now -100.

c = a * b: This line multiplies a and b and assigns the result to c. The value of c is now -10201.

a *= 2: This line multiplies a by 2 and assigns the result back to a. The value of a is now 10.

b -= 1: This line subtracts 1 from b and assigns the result back to b. The value of b is now 2.

a += c: This line adds c to a and assigns the result back to a. The value of a is now 10.

b = a - b: This line subtracts b from a and assigns the result back to b. The value of b is now 8.

int y = 10;

int z = 15;

x *= 2: This line multiplies x by 2 and assigns the result back to x. The value of x is now 10.

y /= 3: This line divides y by 3 and assigns the result back to y. The value of y is now 3.3333... (rounded down to 3).

z -= x: This line subtracts x from z and assigns the result back to z. The value of z is now 5.

x = y + z: This line adds y and z and assigns the result to x. The value of x is now 8.

y = z - x: This line subtracts x from z and assigns the result to y. The value of y is now -3.

z = x * y: This line multiplies x and y and assigns the result to z. The value of z is now -24.

double x = 10;

double y = 3;

x /= y: This line divides x by y and assigns the result back to x. The value of x is now 3.3333... (rounded down to 3.33).

y *= x: This line multiplies y by x and assigns the result back to y. The value of y is now 10.

z = y - x: This line subtracts x from y and assigns the result to z. The value of z is now 6.67.

x += z: This line adds z to x and assigns the result back to x. The value of x is now 10.0.

y = x / z: This line divides x by z and assigns the result back to y. The value of y is now 1.5.

z *= y: This line multiplies z by y and assigns the result back to z. The value of z is now 10.0.

Want some additional practice? CSAwesome created this really cool Operators Maze game that you can do with a friend for a little extra practice! 

Key Terms to Review ( 5 )

Fiveable

Stay Connected

© 2024 Fiveable Inc. All rights reserved.

AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.

examples of compound assignment

  • 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" >

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.

cppreference.com

Assignment operators.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
block

    

/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)      

expression
pointer
specifier

specifier (C++11)    
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
General
(C++11)
(C++26)

(C++11)
(C++11)
-expression
-expression
-expression
(C++11)
(C++11)
(C++17)
(C++20)
    

Assignment operators modify the value of the object.

Operator name  Syntax  Prototype examples (for class T)
Inside class definition Outside class definition
simple assignment Yes T& T::operator =(const T2& b);
addition assignment Yes T& T::operator +=(const T2& b); T& operator +=(T& a, const T2& b);
subtraction assignment Yes T& T::operator -=(const T2& b); T& operator -=(T& a, const T2& b);
multiplication assignment Yes T& T::operator *=(const T2& b); T& operator *=(T& a, const T2& b);
division assignment Yes T& T::operator /=(const T2& b); T& operator /=(T& a, const T2& b);
remainder assignment Yes T& T::operator %=(const T2& b); T& operator %=(T& a, const T2& b);
bitwise AND assignment Yes T& T::operator &=(const T2& b); T& operator &=(T& a, const T2& b);
bitwise OR assignment Yes T& T::operator |=(const T2& b); T& operator |=(T& a, const T2& b);
bitwise XOR assignment Yes T& T::operator ^=(const T2& b); T& operator ^=(T& a, const T2& b);
bitwise left shift assignment Yes T& T::operator <<=(const T2& b); T& operator <<=(T& a, const T2& b);
bitwise right shift assignment Yes T& T::operator >>=(const T2& b); T& operator >>=(T& a, const T2& b);

this, and most also return *this so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including void). can be any type including .
Definitions Assignment operator syntax Built-in simple assignment operator Assignment from an expression Assignment from a non-expression initializer clause Built-in compound assignment operator Example Defect reports See also

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

replaces the contents of the object a with the contents of b, avoiding copying if possible (b may be modified). For class types, this is performed in a special member function, described in .

(since C++11)

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

target-expr new-value (1)
target-expr op new-value (2)
target-expr - the expression to be assigned to
op - one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |=
new-value - the expression (until C++11) (since C++11) to assign to the target
  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

If new-value is not an expression, the assignment expression will never match an overloaded compound assignment operator.

(since C++11)

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

If the type of target-expr is volatile-qualified, the assignment is deprecated, unless the (possibly parenthesized) assignment expression is a or an .

(since C++20)

new-value is only allowed not to be an expression in following situations:

is of a , and new-value is empty or has only one element. In this case, given an invented variable t declared and initialized as T t = new-value , the meaning of x = new-value  is x = t. is of class type. In this case, new-value is passed as the argument to the assignment operator function selected by .   <double> z; z = {1, 2}; // meaning z.operator=({1, 2}) z += {1, 2}; // meaning z.operator+=({1, 2})   int a, b; a = b = {1}; // meaning a = b = 1; a = {1} = b; // syntax error
(since C++11)

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

& operator=(T*&, T*);
volatile & operator=(T*volatile &, T*);

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

operator=(T&, T);

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 signature participates in overload resolution:

operator=(A1&, A2);

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • 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:

operator*=(A1&, A2);
operator/=(A1&, A2);
operator+=(A1&, A2);
operator-=(A1&, A2);

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

operator%=(I1&, I2);
operator<<=(I1&, I2);
operator>>=(I1&, I2);
operator&=(I1&, I2);
operator^=(I1&, I2);
operator|=(I1&, I2);

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

& operator+=(T*&, );
& operator-=(T*&, );
volatile & operator+=(T*volatile &, );
volatile & operator-=(T*volatile &, );

[ edit ] Example

Possible output:

[ edit ] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
C++11 for assignments to class type objects, the right operand
could be an initializer list only when the assignment
is defined by a user-defined assignment operator
removed user-defined
assignment constraint
C++11 E1 = {E2} was equivalent to E1 = T(E2)
( is the type of ), this introduced a C-style cast
it is equivalent
to E1 = T{E2}
C++20 compound assignment operators for volatile
-qualified types were inconsistently deprecated
none of them
is deprecated
C++11 an assignment from a non-expression initializer clause
to a scalar value would perform direct-list-initialization
performs copy-list-
initialization instead
C++20 bitwise compound assignment operators for volatile types
were deprecated while being useful for some platforms
they are not
deprecated

[ edit ] See also

Operator precedence

Operator overloading

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
a->b
a.b
a->*b
a.*b

function call
a(...)
comma
a, b
conditional
a ? b : c
Special operators

converts one type to another related type
converts within inheritance hierarchies
adds or removes -qualifiers
converts type to unrelated type
converts one type to another by a mix of , , and
creates objects with dynamic storage duration
destructs objects previously created by the new expression and releases obtained memory area
queries the size of a type
queries the size of a (since C++11)
queries the type information of a type
checks if an expression can throw an exception (since C++11)
queries alignment requirements of a type (since C++11)

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 25 January 2024, at 23:41.
  • This page has been accessed 428,577 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

examples of compound assignment

  • Introduction to C
  • Download MinGW GCC C Compiler
  • Configure MinGW GCC C Compiler
  • The First C Program
  • Data Types in C
  • Variables, Keywords, Constants
  • If Statement
  • If Else Statement
  • Else If Statement
  • Nested If Statement
  • Nested If Else Statement
  • Do-While Loop
  • Break Statement
  • Switch Statement
  • Continue Statement
  • Goto Statement
  • Arithmetic Operator in C
  • Increment Operator in C
  • Decrement Operator in C
  • Compound Assignment Operator
  • Relational Operator in C
  • Logical Operator in C
  • Conditional Operator in C
  • 2D array in C
  • Functions with arguments
  • Function Return Types
  • Function Call by Value
  • Function Call by Reference
  • Recursion in C
  • Reading String from console
  • C strchr() function
  • C strlen() function
  • C strupr() function
  • C strlwr() function
  • C strcat() function
  • C strncat() function
  • C strcpy() function
  • C strncpy() function
  • C strcmp() function
  • C strncmp() function
  • Structure with array element
  • Array of structures
  • Formatted Console I/O functions
  • scanf() and printf() function
  • sscanf() and sprintf() function
  • Unformatted Console I/O functions
  • getch(), getche(), getchar(), gets()
  • putch(), putchar(), puts()
  • Reading a File
  • Writing a File
  • Append to a File
  • Modify a File

Advertisement

+= operator

  • Add operation.
  • Assignment of the result of add operation.
  • Statement i+=2 is equal to i=i+2 , hence 2 will be added to the value of i, which gives us 4.
  • Finally, the result of addition, 4 is assigned back to i, updating its original value from 2 to 4.

Example with += operator

-= operator.

  • Subtraction operation.
  • Assignment of the result of subtract operation.
  • Statement i-=2 is equal to i=i-2 , hence 2 will be subtracted from the value of i, which gives us 0.
  • Finally, the result of subtraction i.e. 0 is assigned back to i, updating its value to 0.

Example with -= operator

*= operator.

  • Multiplication operation.
  • Assignment of the result of multiplication operation.
  • Statement i*=2 is equal to i=i*2 , hence 2 will be multiplied with the value of i, which gives us 4.
  • Finally, the result of multiplication, 4 is assigned back to i, updating its value to 4.

Example with *= operator

/= operator.

  • Division operation.
  • Assignment of the result of division operation.
  • Statement i/=2 is equal to i=i/2 , hence 4 will be divided by the value of i, which gives us 2.
  • Finally, the result of division i.e. 2 is assigned back to i, updating its value from 4 to 2.

Example with /= operator

Please share this article -.

Facebook

Please Subscribe

Decodejava Facebook Page

Notifications

Please check our latest addition C#, PYTHON and DJANGO

Dot Net Tutorials

Compound Assignment Operator in C++

Back to: C++ Tutorials For Beginners and Professionals

Compound Assignment Operator in C++ with Examples

In this article, I am going to discuss Compound Assignment Operator in C++ with Examples. Please read our previous article where we discussed Programming Exercises in C++ . We have already created a few simple programs using formulas and expressions where we used use arithmetic operators. We have a lot of other operators to learn so slowly we’ll be learning about them. Now, we will learn about compound assignment operators.

Compound Assignment is there not only for arithmetic operators but it is there for other operators also. However, we will discuss compound assignment arithmetic operators later whenever we discuss those operators at that time, I will discuss the compound operators also.

These are related to arithmetic as well as other operators also. So let us understand what these are and when they are useful. We have listed the compound assignment operators:

Compound Assignment Operator in C++ with Examples

You can see that the operators coming before the assignment. Usually, the expression or all the operators will be after the assignment but here it is coming before the assignment.

When it is useful?

When it is useful let us see. For that I have taken one example here,

int x = 3, y = 15, z = 21;

int sum = 3;

We have some variables x, y, and the sum which are having some values. Now the first thing is we want to perform the addition between sum and a and store the result in sum itself. So let us see how we can do that.

We can write it as sum = sum + a;

This statement means we add sum and a, and store the result in sum. Now the sum becomes 6. These types of statements are commonly used in programming. Now we will see the same statement can be written using the Compound Assignment Operator. Let us see this.

sum = sum + a;

In the above expression, the sum is used on the right-hand side of the assignment as well as the left-hand side of the assignment. So, the same thing can be written as

So instead of writing sum 2 times, we can write it as above. Now, this is easily readable. For a beginner, it is not readable but when you are writing C++ programming you get used to it. Writing the above statement by using a compound assignment operator is faster than the previous method. Internally compiler will make it faster. So, this statement is faster.

Compound Assignment Operator Example:

Now we take another example: int x = 3, y = 4, z = 2; int p = 1;

In some program we have to perform many operations on a single variable, so at that time we can use compound assignment. p *= x; — (i) p *= y; — (ii) p -= x + y + z; — (iii)

Here In the 1 st statement, we are performing multiplication between p and x and then store the result in p itself. Here value of p will 1 * 3 = 3. When we execute the first statement, the value of p will 3.

Now the 2 nd statement, we are performing multiplication between p and y and store results in p. But here the value of p is 3 as evaluated from 1 st statement. Now the value of p will be 3 * 4 = 12. So, at this point, the p value will be 12.

In the 3 rd statement, we are performing subtraction between p and the result of the addition of x, y, and z. And store that in p. Here p = 12. So, at execution, it will be 12 – (3+4+2) = 3. Now p = 3

Here we modified ‘ p ’ with multiple values. So, in such situations, we use this type of operator. That is a compound assignment. It can be done for subtraction, multiplication, division, and all the other operators like bitwise operators. We will look at them in the coming articles. Let’s see the code part:

Compound Assignment Operator Code in C++ Language:

Compound Assignment Operator Code in C++ Language

Why Compound Assignment Operator?

Compound assignment operator usually does the same thing that existing operators are doing but it gives more efficiency in compile time. To explain the compound assignment Operator let us take an example: I have a variable I want to repeat add another no to this variable. Currently, without a compound assignment operator, I am following this method. I am writing a pseudocode

int sum=0; Sum=sum+5; Sum=sum+8; Sum=sum+11; //here every time you are adding sum with other values and storing back it in sum only.

This has a disadvantage.

The Variable sum is evaluated in each instruction, which consumes more compile-time hence inefficient. To overcome this problem and also to increase program readability compound assignment operators or shorthand operators come into the picture. Now the same pseudo-code can be written as

int sum=0; Sum+=5; Sum+=8; Sum+=11; Let’s see how efficient it is by comparing the compile time for both.

Without compound assignment operator

Without shorthand operator/compound assignment operator Compile-time is 4.119 seconds

With compound assignment operator

With shorthand operator/compound assignment operator Compile-time is only 1.788 seconds.

Note : Assignment and Compound Assignment Operators have the least precedence when compare to other arithmetic operators.

In the next article, I am going to discuss Increment Decrement Operator in C++ with Examples. Here, in this article, I try to explain Compound Assignment Operator in C++ with Examples and I hope you enjoy this Compound Assignment Operator in C++ with Examples article.

About the Author: Pranaya Rout

Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.

1 thought on “Compound Assignment Operator in C++”

you are one of the best teacher, I never saw this much nice explaination

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Home » Learn C Programming from Scratch » C Assignment Operators

C Assignment Operators

Summary : in this tutorial, you’ll learn about the C assignment operators and how to use them effectively.

Introduction to the C assignment operators

An assignment operator assigns the vale of the right-hand operand to the left-hand operand. The following example uses the assignment operator (=) to assign 1 to the counter variable:

After the assignmment, the counter variable holds the number 1.

The following example adds 1 to the counter and assign the result to the counter:

The = assignment operator is called a simple assignment operator. It assigns the value of the left operand to the right operand.

Besides the simple assignment operator, C supports compound assignment operators. A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.

The following example uses a compound-assignment operator (+=):

The expression:

is equivalent to the following expression:

The following table illustrates the compound-assignment operators in C:

OperatorOperation PerformedExampleEquivalent expression
Multiplication assignmentx *= yx = x * y
Division assignmentx /= yx = x / y
Remainder assignmentx %= yx = x % y
Addition assignmentx += yx = x + y
Subtraction assignmentx -= yx = x – y
Left-shift assignmentx <<= yx = x <<=y
Right-shift assignmentx >>=yx = x >>= y
Bitwise-AND assignmentx &= yx = x & y
Bitwise-exclusive-OR assignmentx ^= yx = x ^ y
Bitwise-inclusive-OR assignmentx |= yx = x | y
  • A simple assignment operator assigns the value of the left operand to the right operand.
  • A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.

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
  • Assignment Operators in C++
  • What are assignment operators in C#?
  • 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++
  • What is an assignment operator in C#?
  • Copy constructor vs assignment operator in C++
  • Unary operators in C/C++
  • Ternary Operators in C/C++
  • Arithmetic Operators in C++

Kickstart Your Career

Get certified by completing the course

To Continue Learning Please Login

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

Compound assignment in C++

I would like to know the execution flow of compound assignments in C++. I came across a CodeChef question , where I am calculating NCR mod p values and adding them together to get the final answer:

This is happening because of integer overflow.

So, what is the execution sequence of compound assignment?

Let's say, if we have an equation a+=b%c then what would be the execution sequence:

  • assignment-operator
  • compound-assignment

Adrian Mole's user avatar

  • Start from the innermost parentheses. In case of equally parenthesised operations, see the order of precedence. –  eerorika Jan 20, 2021 at 14:43
  • Just google cppreference operator precedence ? Compound assignment isn't special there. –  underscore_d Jan 20, 2021 at 14:59
  • I was not very confident. –  Rahul Jan 20, 2021 at 15:28

2 Answers 2

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:

is equivalent to:

Which is clearly different from the first (correct) expression:

This statement

is equivalent to the statement

As you can see it differs from the statement

From the C++ 14 Standard (5.18 Assignment and compound assignment operators)

7 The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once. In += and -=, E1 shall either have arithmetic type or be a pointer to a possibly cv-qualified completely-defined object type. In all other cases, E1 shall have arithmetic type.

Vlad from Moscow'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++ assignment-operator compound-assignment or ask your own question .

  • Featured on Meta
  • The 2024 Developer Survey Is Live
  • The return of Staging Ground to Stack Overflow
  • The [tax] tag is being burninated
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • The symmetry of multiplications with the number 9
  • Find characters common among all strings
  • An application of the (100/e)% rule applied to postdocs: moving on from an academic career, perhaps
  • Can we combine a laser with a gauss rifle to get a cinematic 'laser rifle'?
  • What is the meaning of the 'ride out the clock'?
  • siblings/clones tour the galaxy giving technical help to collapsed societies
  • Has there ever been arms supply with restrictions attached prior to the current war in Ukraine?
  • How to unplug heating element connector in tumble dryer
  • Word for a country declaring independence from an empire
  • Can someone explain the damage distrubution on this aircraft that flew through a hailstorm?
  • Has ever a country by its own volition refused to join United Nations, or those which havent joined it's because they aren't recognized as such by UN?
  • Was it known in ancient Rome and Greece that boiling water made it safe to drink and if so, what was the theory behind this?
  • Universal PCB enclosure: what are these cylinders with holes for?
  • What is this symbol?
  • Starlink Satellite Orbits
  • How does Wolfram Alpha know this closed form?
  • Is it theoretically possible for the sun to go dark?
  • How can I use a router without gateway?
  • Preventing Javascript in a browser from connecting to servers
  • How do Authenticators work?
  • Why at 1 Corinthians 10:9 does the Jehovah's Witnesses NWT use the word "Jehovah" when the Greek uses "Christos/kurion" referring to Jesus Christ?
  • Do we know how the SpaceX Starship stack handles engine shutdowns?
  • How to explain the late added verses like in Matthew 18:11?
  • Selecting an opamp for a voltage follower circuit using a LTspice simulation

examples of compound assignment

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

Expressions and operators

This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that purely evaluate .

The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to 7 .

The expression 3 + 4 is an example of the second type. This expression uses the + operator to add 3 and 4 together and produces a value, 7 . However, if it's not eventually part of a bigger construct (for example, a variable declaration like const z = 3 + 4 ), its result will be immediately discarded — this is usually a programmer mistake because the evaluation doesn't produce any effects.

As the examples above also illustrate, all complex expressions are joined by operators , such as = and + . In this section, we will introduce the following operators:

Assignment operators

Comparison operators, arithmetic operators, bitwise operators, logical operators, bigint operators, string operators, conditional (ternary) operator, comma operator, unary operators, relational operators.

These operators join operands either formed by higher-precedence operators or one of the basic expressions . A complete and detailed list of operators and expressions is also available in the reference .

The precedence of operators determines the order they are applied when evaluating an expression. For example:

Despite * and + coming in different orders, both expressions would result in 7 because * has precedence over + , so the * -joined expression will always be evaluated first. You can override operator precedence by using parentheses (which creates a grouped expression — the basic expression). To see a complete table of operator precedence as well as various caveats, see the Operator Precedence Reference page.

JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:

For example, 3 + 4 or x * y . This form is called an infix binary operator, because the operator is placed between two operands. All binary operators in JavaScript are infix.

A unary operator requires a single operand, either before or after the operator:

For example, x++ or ++x . The operator operand form is called a prefix unary operator, and the operand operator form is called a postfix unary operator. ++ and -- are the only postfix operators in JavaScript — all other operators, like ! , typeof , etc. are prefix.

An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x .

There are also compound assignment operators that are shorthand for the operations listed in the following table:

Name Shorthand operator Meaning

Assigning to properties

If an expression evaluates to an object , then the left-hand side of an assignment expression may make assignments to properties of that expression. For example:

For more information about objects, read Working with Objects .

If an expression does not evaluate to an object, then assignments to properties of that expression do not assign:

In strict mode , the code above throws, because one cannot assign properties to primitives.

It is an error to assign values to unmodifiable properties or to properties of an expression without properties ( null or undefined ).

Destructuring

For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.

Without destructuring, it takes multiple statements to extract values from arrays and objects:

With destructuring, you can extract multiple values into distinct variables using a single statement:

Evaluation and nesting

In general, assignments are used within a variable declaration (i.e., with const , let , or var ) or as standalone statements.

However, like other expressions, assignment expressions like x = f() evaluate into a result value. Although this result value is usually not used, it can then be used by another expression.

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, some JavaScript style guides discourage chaining or nesting assignments . Nevertheless, assignment chaining and nesting may occur sometimes, so it is important to be able to understand how they work.

By chaining or nesting an assignment expression, its result can itself be assigned to another variable. It can be logged, it can be put inside an array literal or function call, and so on.

The evaluation result matches the expression to the right of the = sign in the "Meaning" column of the table above. That means that x = f() evaluates into whatever f() 's result is, x += f() evaluates into the resulting sum x + f() , x **= f() evaluates into the resulting power x ** f() , and so on.

In the case of logical assignments, x &&= f() , x ||= f() , and x ??= f() , the return value is that of the logical operation without the assignment, so x && f() , x || f() , and x ?? f() , respectively.

When chaining these expressions without parentheses or other grouping operators like array literals, the assignment expressions are grouped right to left (they are right-associative ), but they are evaluated left to right .

Note that, for all assignment operators other than = itself, the resulting values are always based on the operands' values before the operation.

For example, assume that the following functions f and g and the variables x and y have been declared:

Consider these three examples:

Evaluation example 1

y = x = f() is equivalent to y = (x = f()) , because the assignment operator = is right-associative . However, it evaluates from left to right:

  • The y on this assignment's left-hand side evaluates into a reference to the variable named y .
  • The x on this assignment's left-hand side evaluates into a reference to the variable named x .
  • The function call f() prints "F!" to the console and then evaluates to the number 2 .
  • That 2 result from f() is assigned to x .
  • The assignment expression x = f() has now finished evaluating; its result is the new value of x , which is 2 .
  • That 2 result in turn is also assigned to y .
  • The assignment expression y = x = f() has now finished evaluating; its result is the new value of y – which happens to be 2 . x and y are assigned to 2 , and the console has printed "F!".

Evaluation example 2

y = [ f(), x = g() ] also evaluates from left to right:

  • The y on this assignment's left-hand evaluates into a reference to the variable named y .
  • The function call g() prints "G!" to the console and then evaluates to the number 3 .
  • That 3 result from g() is assigned to x .
  • The assignment expression x = g() has now finished evaluating; its result is the new value of x , which is 3 . That 3 result becomes the next element in the inner array literal (after the 2 from the f() ).
  • The inner array literal [ f(), x = g() ] has now finished evaluating; its result is an array with two values: [ 2, 3 ] .
  • That [ 2, 3 ] array is now assigned to y .
  • The assignment expression y = [ f(), x = g() ] has now finished evaluating; its result is the new value of y – which happens to be [ 2, 3 ] . x is now assigned to 3 , y is now assigned to [ 2, 3 ] , and the console has printed "F!" then "G!".

Evaluation example 3

x[f()] = g() also evaluates from left to right. (This example assumes that x is already assigned to some object. For more information about objects, read Working with Objects .)

  • The x in this property access evaluates into a reference to the variable named x .
  • Then the function call f() prints "F!" to the console and then evaluates to the number 2 .
  • The x[f()] property access on this assignment has now finished evaluating; its result is a variable property reference: x[2] .
  • Then the function call g() prints "G!" to the console and then evaluates to the number 3 .
  • That 3 is now assigned to x[2] . (This step will succeed only if x is assigned to an object .)
  • The assignment expression x[f()] = g() has now finished evaluating; its result is the new value of x[2] – which happens to be 3 . x[2] is now assigned to 3 , and the console has printed "F!" then "G!".

Avoid assignment chains

Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, chaining assignments in the same statement is discouraged .

In particular, putting a variable chain in a const , let , or var statement often does not work. Only the outermost/leftmost variable would get declared; other variables within the assignment chain are not declared by the const / let / var statement. For example:

This statement seemingly declares the variables x , y , and z . However, it only actually declares the variable z . y and x are either invalid references to nonexistent variables (in strict mode ) or, worse, would implicitly create global variables for x and y in sloppy mode .

A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:

Comparison operators
Operator Description Examples returning true
( ) Returns if the operands are equal.

( ) Returns if the operands are not equal.
( ) Returns if the operands are equal and of the same type. See also and .
( ) Returns if the operands are of the same type but not equal, or are of different type.
( ) Returns if the left operand is greater than the right operand.
( ) Returns if the left operand is greater than or equal to the right operand.
( ) Returns if the left operand is less than the right operand.
( ) Returns if the left operand is less than or equal to the right operand.

Note: => is not a comparison operator but rather is the notation for Arrow functions .

An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:

In addition to the standard arithmetic operations ( + , - , * , / ), JavaScript provides the arithmetic operators listed in the following table:

Arithmetic operators
Operator Description Example
( ) Binary operator. Returns the integer remainder of dividing the two operands. 12 % 5 returns 2.
( ) Unary operator. Adds one to its operand. If used as a prefix operator ( ), returns the value of its operand after adding one; if used as a postfix operator ( ), returns the value of its operand before adding one. If is 3, then sets to 4 and returns 4, whereas returns 3 and, only then, sets to 4.
( ) Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. If is 3, then sets to 2 and returns 2, whereas returns 3 and, only then, sets to 2.
( ) Unary operator. Returns the negation of its operand. If is 3, then returns -3.
( ) Unary operator. Attempts to , if it is not already.

returns .

returns .

( ) Calculates the to the power, that is, returns .
returns .

A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.

The following table summarizes JavaScript's bitwise operators.

Operator Usage Description
Returns a one in each bit position for which the corresponding bits of both operands are ones.
Returns a zero in each bit position for which the corresponding bits of both operands are zeros.
Returns a zero in each bit position for which the corresponding bits are the same. [Returns a one in each bit position for which the corresponding bits are different.]
Inverts the bits of its operand.
Shifts in binary representation bits to the left, shifting in zeros from the right.
Shifts in binary representation bits to the right, discarding bits shifted off.
Shifts in binary representation bits to the right, discarding bits shifted off, and shifting in zeros from the left.

Bitwise logical operators

Conceptually, the bitwise logical operators work as follows:

  • The operands are converted to thirty-two-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer: Before: 1110 0110 1111 1010 0000 0000 0000 0110 0000 0000 0001 After: 1010 0000 0000 0000 0110 0000 0000 0001
  • Each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on.
  • The operator is applied to each pair of bits, and the result is constructed bitwise.

For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:

Expression Result Binary Description

Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation). ~x evaluates to the same value that -x - 1 evaluates to.

Bitwise shift operators

The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.

Shift operators convert their operands to thirty-two-bit integers and return a result of either type Number or BigInt : specifically, if the type of the left operand is BigInt , they return BigInt ; otherwise, they return Number .

The shift operators are listed in the following table.

Bitwise shift operators
Operator Description Example

( )
This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, yields -3, because the sign is preserved.
( ) This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result.

Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.

Logical operators
Operator Usage Description
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if both operands are true; otherwise, returns .
( ) Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if either operand is true; if both are false, returns .
( ) Returns if its single operand that can be converted to ; otherwise, returns .

Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.

The following code shows examples of the && (logical AND) operator.

The following code shows examples of the || (logical OR) operator.

The following code shows examples of the ! (logical NOT) operator.

Short-circuit evaluation

As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:

  • false && anything is short-circuit evaluated to false.
  • true || anything is short-circuit evaluated to true.

The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.

Note that for the second case, in modern code you can use the Nullish coalescing operator ( ?? ) that works like || , but it only returns the second expression, when the first one is " nullish ", i.e. null or undefined . It is thus the better alternative to provide defaults, when values like '' or 0 are valid values for the first expression, too.

Most operators that can be used between numbers can be used between BigInt values as well.

One exception is unsigned right shift ( >>> ) , which is not defined for BigInt values. This is because a BigInt does not have a fixed width, so technically it does not have a "highest bit".

BigInts and numbers are not mutually replaceable — you cannot mix them in calculations.

This is because BigInt is neither a subset nor a superset of numbers. BigInts have higher precision than numbers when representing large integers, but cannot represent decimals, so implicit conversion on either side might lose precision. Use explicit conversion to signal whether you wish the operation to be a number operation or a BigInt one.

You can compare BigInts with numbers.

In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.

For example,

The shorthand assignment operator += can also be used to concatenate strings.

The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:

If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.

This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .

The comma operator ( , ) evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop. It is regarded bad style to use it elsewhere, when it is not necessary. Often two separate statements can and should be used instead.

For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:

A unary operation is an operation with only one operand.

The delete operator deletes an object's property. The syntax is:

where object is the name of an object, property is an existing property, and propertyKey is a string or symbol referring to an existing property.

If the delete operator succeeds, it removes the property from the object. Trying to access it afterwards will yield undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.

Deleting array elements

Since arrays are just objects, it's technically possible to delete elements from them. This is, however, regarded as a bad practice — try to avoid it. When you delete an array property, the array length is not affected and other elements are not re-indexed. To achieve that behavior, it is much better to just overwrite the element with the value undefined . To actually manipulate the array, use the various array methods such as splice .

The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.

Suppose you define the following variables:

The typeof operator returns the following results for these variables:

For the keywords true and null , the typeof operator returns the following results:

For a number or string, the typeof operator returns the following results:

For property values, the typeof operator returns the type of value the property contains:

For methods and functions, the typeof operator returns results as follows:

For predefined objects, the typeof operator returns results as follows:

The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them to avoid precedence issues.

A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.

The in operator returns true if the specified property is in the specified object. The syntax is:

where propNameOrNumber is a string, numeric, or symbol expression representing a property name or array index, and objectName is the name of an object.

The following examples show some uses of the in operator.

The instanceof operator returns true if the specified object is of the specified object type. The syntax is:

where objectName is the name of the object to compare to objectType , and objectType is an object type, such as Date or Array .

Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.

For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.

Basic expressions

All operators eventually operate on one or more basic expressions. These basic expressions include identifiers and literals , but there are a few other kinds as well. They are briefly introduced below, and their semantics are described in detail in their respective reference sections.

Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:

Suppose a function called validate validates an object's value property, given the object and the high and low values:

You could call validate in each form element's onChange event handler, using this to pass it to the form element, as in the following example:

Grouping operator

The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.

You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:

The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.

What Is Compound Interest?

When it comes to calculating interest, there are two basic choices: simple and compound. Simple interest simply means a set percentage of the principal amount every year.

For example, if you invest $1,000 at 5% simple interest for 10 years, you can expect to receive $50 in interest every year for the next decade. No more, no less. In the investment world, bonds are an example of an investment that typically pays simple interest.

What is compound interest?

On the other hand, compound interest is what you get when you reinvest your earnings, which then also earn interest. Compound interest essentially means "interest on the interest" and is why many investors are so successful.

Think of it this way. Let's say you invest $1,000 at 5% interest. After the first year, you receive a $50 interest payment, but instead of receiving it in cash, you reinvest the interest you earned at the same 5% rate. For the second year, your interest would be calculated on a $1,050 investment, which comes to $52.50. If you reinvest that, your third-year interest would be calculated on a $1,102.50 balance.

You get the idea. Compound interest means your principal gets larger over time and will generate larger and larger interest payments. The difference between simple and compound interest can be massive. Take a look at the difference on a $10,000 investment portfolio at 10% interest over time:

Simple and compound interest on a $10,000 investment portfolio at 10% interest over time. Calculations by author.
Time Period Simple Interest at 10% Compound Interest (annually at 10%)
Start $10,000 $10,000
1 year $11,000 $11,000
2 years $12,000 $12,100
5 years $15,000 $16,105
10 years $20,000 $25,937
20 years $30,000 $67,275
30 years $40,000 $174,494

Note that 10% is, roughly, the long-term annualized return of the S&P 500 . It was 9.65% for the 30-year period through 2022. Returns like this, compounded over long periods, can result in some pretty impressive performances.

It's also worth mentioning that there's a very similar concept known as  cumulative interest. Cumulative interest refers to the sum of the interest payments made, but it typically refers to payments made on a loan. For example, the cumulative interest on a 30-year mortgage would be how much you paid toward interest over the 30-year loan term.

How to calculate compound interest

How compound interest is calculated.

Compound interest is calculated by applying an exponential growth factor to the interest rate or rate of return you're using. The good news is that there are plenty of excellent calculators that will do the math for you.

Below is a mathematical formula you could use for calculating compound interest over a certain period:

A graphic showing and explaining the formula used to calculate compound interest.

With "A" as the final amount, here's what all the other variables mean:

  • Principal (P): The starting balance on which interest is calculated. For example, if you decide to invest $10,000 for five years, that amount would be your principal for the purposes of calculating compound interest.
  • Interest rate (or expected rate of return in investing) expressed as a decimal (r): For calculation purposes, if you expect your investments to grow at an average rate of 7% per year, you would use 0.07 here.
  • Compounding frequency (n): How frequently you're adding interest to the principal. Using the example of 7% interest, if we were to use annual compounding, you would simply add 7% to the principal once per year. On the other hand, semiannual compounding would involve applying half of that amount (3.5%) twice a year. Other common compounding frequencies include quarterly (every three months), monthly, weekly, or daily.
  • Time (T): The total time in years. In other words, if you're investing for 30 months, be sure to use 2.5 years in the formula.

Compounding frequency

Compounding frequency and why it matters.

In the previous example, we used annual compounding, meaning the interest is calculated once per year. In practice, compound interest is often calculated more frequently. For example, your savings account may calculate interest monthly. Common compounding intervals are quarterly, monthly, and daily, but many other possible intervals could be used.

The compounding frequency makes a difference. All other factors being equal, more frequent compounding leads to faster growth. For instance, the table below shows the growth of $10,000 at 8% interest compounded at several frequencies:

$10,000 invested at 8% interest compounded annually, quarterly, and monthly. Calculations by author.
Time Annual Compounding Quarterly Monthly
1 year $10,800 $10,824 $10,830
5 years $14,693 $14,859 $14,898
10 years $21,589 $22,080 $22,196

Example of calculating compound interest

As a basic example, let's say you're investing $20,000 at 5% interest compounded quarterly for 20 years. In this case, "n" would be four, as quarterly compounding occurs four times per year.

Based on this information, we can calculate the investment's final value after 20 years like this:

A hypothetical example of how to calculate compound interest.

Compound earnings vs. compound interest

You may hear the terms compound interest and compound earnings used interchangeably, especially when discussing investment returns. However, there's a subtle difference.

Specifically, compound earnings refers to the compounding effects of  both interest payments and dividends, as well as appreciation in the value of the investment itself. In other words, it's more of an all-in-one term to describe investment returns that aren't entirely interest.

For example, if a stock investment paid you a 4% dividend yield and the stock itself increased in value by 5%, you'd have total earnings of 9% for the year. When these dividends and price gains compound over time, it is a form of compound earnings and not interest, as not all of the gains come from payments to you.

In a nutshell, long-term returns from stocks, exchange-traded funds (ETFs) , or mutual funds are technically called compound earnings. However, it can still be calculated in the same manner if you know your expected rate of return.

Related investing topics

Accounts that earn compounding interest.

Interest compounds when interest payments also earn interest. Learn how to get compounding interest working for your portfolio.

What Is a Good Return on Investment?

You invest to get a return. So what makes a good ROI?

Municipal Bonds

Municipalities issue bonds that could be a great investment. How do they work?

Importance of compound interest

Why compound interest is such an important concept for investors.

Compound interest is the phenomenon that allows seemingly small amounts of money to grow into large amounts over time. To take full advantage of the power of compound interest, investments must be allowed to grow and compound for long periods.

Invest Smarter with The Motley Fool

Join over half a million premium members receiving….

  • New Stock Picks Each Month
  • Detailed Analysis of Companies
  • Model Portfolios
  • Live Streaming During Market Hours
  • And Much More

HOW THE MOTLEY FOOL CAN HELP YOU

Market beating stocks from our award-winning service

Investment news and high-quality insights delivered straight to your inbox

You can do it. Successful investing in just a few steps

Secrets and strategies for the post-work life you want.

Find the right brokerage account for you.

Hear our experts take on stocks, the market, and how to invest.

An infographic defining and explaining the term "conservatorship"

Premium Investing Services

Invest better with The Motley Fool. Get stock recommendations, portfolio guidance, and more from The Motley Fool's premium services.

A class of people prepare to do deadlifts in the gym.

What are compound exercises and why are they good for you?

examples of compound assignment

Senior Lecturer, Exercise Physiology. School of Health Sciences, UNSW Sydney

examples of compound assignment

PhD Candidate in Exercise Physiology, UNSW Sydney

Disclosure statement

Mandy Hagstrom is affiliated with Sports Oracle, a company that delivers the IOC diploma in Strength and Conditioning.

Anurag Pandit is currently on a Research Training Program scholarship for his PhD at UNSW.

UNSW Sydney provides funding as a member of The Conversation AU.

View all partners

So you’ve got yourself a gym membership or bought a set of home weights. Now what? With the sheer amount of confusing exercise advice out there, it can be hard to decide what to include in a weights routine.

It can help to know there are broadly two types of movements in resistance training (lifting weights): compound exercises and isolation exercises.

So what’s the difference? And what’s all this got to do with strength, speed and healthy ageing?

What’s the difference?

Compound exercises involve multiple joints and muscle groups working together.

In a push up, for example, your shoulder and elbow joints are moving together. This targets the muscles in the chest, shoulder and triceps.

When you do a squat, you’re using your thigh and butt muscles, your back, and even the muscles in your core.

It can help to think about compound movements by grouping them by primary movement patterns.

For example, some lower body compound exercises follow a “squat pattern”. Examples include bodyweight squats, weighted squats, lunges and split squats.

A woman does a Bulgarian split squat.

We also have “hinge patterns”, where you hinge from a point on your body (such as the hips). Examples include deadlifts, hip thrusts and kettle bell swings.

Upper body compounded exercises can be grouped into “push patterns” (such as vertical barbell lifts) or “pull patterns” (such as weighted rows, chin ups or lat pull downs, which is where you use a pulley system machine to lift weights by pulling a bar downwards).

In contrast, isolation exercises are movements that occur at a single joint.

For instance, bicep curls only require movement at the elbow joint and work your bicep muscles. Tricep extensions and lateral raises are other examples of isolation exercises.

A woman sets up to lift a heavy weight while her trainer observes.

Compound exercises can make daily life easier

Many compound exercises mimic movements we do every day.

Hinge patterns mimic picking something off the floor. A vertical press mimics putting a heavy box on a high shelf. A squat mimics standing up from the couch or getting on and off the toilet.

That might sound ridiculous to a young, fit person (“why would I need to practise getting on and off a toilet?”).

Unfortunately, we lose strength and muscle mass as we age. Men lose about 5% of their muscle mass per decade, while for women the figure is about 4% per decade.

When this decline begins can vary widely. However, approximately 30% of an adult’s peak muscle mass is lost by the time they are 80.

The good news is resistance training can counteract these age-related changes in muscle size and strength.

So building strength through compound exercise movements may help make daily life feel a bit easier. In fact, our ability to perform compound movements are a good indicator how well we can function as we age .

A woman gets a box down from a shelf.

What about strength and athletic ability?

Compound exercises use multiple joints, so you can generally lift heavier weights than you could with isolation exercises. Lifting a heavier weight means you can build muscle strength more efficiently.

One study divided a group of 36 people into two. Three times a week, one group performed isolation exercises, while the other group did compound exercises.

After eight weeks, both groups had lost fat. But the compound exercises group saw much better results on measures of cardiovascular fitness, bench press strength, knee extension strength, and squat strength.

If you play a sport, compound movements can also help boost athletic ability.

Squat patterns require your hip, knee, and ankle to extend at the same time (also known as triple extension).

Our bodies use this triple extension trick when we run, sprint, jump or change direction quickly. In fact, research has found squat strength is strongly linked to being able to sprint faster and jump higher .

Isolation exercises are still good

What if you’re unable to do compound movements, or you just don’t want to?

Don’t worry, you’ll still build strength and muscle with isolation exercises.

Isolation exercises are also typically easier to learn as there is no skill required. They are an easy and low risk way to add extra exercise at the end of the workout, where you might otherwise be too tired to do more compound exercises safely and with correct form.

In fact, both isolation and compound exercises seem to be equally effective in helping us lose body fat and increase fat-free muscle mass when total intensity and volume of exercises are otherwise equal.

Some people also do isolation exercises when they want to build up a particular muscle group for a certain sport or for a bodybuilding competition, for example.

An older man does bicep curls in the gym

I just want a time efficient workout

Considering the above factors, you could consider prioritising compound exercises if you’re:

keen to lift heavier weights

looking for an efficient way to train many muscles in the one workout

interested in healthy ageing.

That said, most well designed workout programs will include both compound and isolation movements.

Correction: This article has been amended to reflect the fact a weighted row is a pull pattern, not a push pattern.

  • lifting weights
  • Weightlifting
  • Sports training
  • Working out
  • Resistance exercise
  • Exercise science

examples of compound assignment

Head of School, School of Arts & Social Sciences, Monash University Malaysia

examples of compound assignment

Chief Operating Officer (COO)

examples of compound assignment

Clinical Teaching Fellow

examples of compound assignment

Data Manager

examples of compound assignment

Director, Social Policy

U.S. flag

Official websites use .gov

A .gov website belongs to an official government organization in the United States.

Secure .gov websites use HTTPS

A lock ( ) or https:// means you've safely connected to the .gov website. Share sensitive information only on official, secure websites.

CDC Current Outbreak List

Infectious disease outbreaks currently being reported on by CDC. Listings include those outbreaks for which content is currently published on the CDC website.

Recent investigations reported on CDC.gov

  • Cucumbers – Salmonella Outbreak Announced June 2024
  • Backyard Poultry – Salmonella Outbreaks Announced May 2024
  • Organic Walnuts – E coli Outbreak Announced April 2024
  • Fresh Basil – Salmonella Outbreak Announced April 2024
  • Measles Outbreaks 2024 Announced January 2024
  • Coronavirus Disease 2019 (COVID-19) Announced January 2020

Please see the Travelers’ Health site for a complete list.

In the last two years, CDC has sent scientists and doctors out more than 750 times to respond to health threats. Learn more below.

  • Investigating Foodborne Outbreaks
  • Waterborne Outbreaks Toolkit
  • Ebola Outbreak History Announced September 2022
  • Mpox Outbreaks Announced May 2022
  • Multistate Foodborne Outbreaks – Foodborne outbreaks listed by year
  • Hepatitis A Outbreaks – Hepatitis A outbreak investigations since 2013 where CDC supported or led the investigation.
  • US Outbreaks Linked to Contact with Animals or Animal Products
  • Health Alert Network – Health alerts, health advisories, updates, and info service messages. Designed for public health and medical communities.
  • Recent Outbreaks and Incidents – Events involving the CDC Emergency Operations Center
  • Morbidity and Mortality Weekly Report – Outbreak investigation reports included among other content. Note that outbreak material includes state health department investigations. Designed for public health and medical communities.

Exit Notification / Disclaimer Policy

  • The Centers for Disease Control and Prevention (CDC) cannot attest to the accuracy of a non-federal website.
  • Linking to a non-federal website does not constitute an endorsement by CDC or any of its employees of the sponsors or the information and products presented on the website.
  • You will be subject to the destination website's privacy policy when you follow the link.
  • CDC is not responsible for Section 508 compliance (accessibility) on other federal or private website.

COMMENTS

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

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

  3. 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. ... For example, the following two multiplication statements are equivalent, ...

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

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

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

  7. PDF Compound assignment operators

    The compound assignment operators are: += -= *= /= %= Consider variable k: int k= 5; Each of the following two lines contains equivalent assignment statements, so it looks like the compound assignment operators simply provide syntactic sugar:

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

  9. Compound Assignment Operators

    ️ Open Sans AaBbCc 123 PreTeXt; Roboto Serif AaBbCc 123 PreTeXt; Adjust font

  10. Compound Assignment Operators

    The "*= 2" is an example of a compound assignment operator, which multiplies the current value of integerOne by 2 and sets that as the new value of integerOne. Other arithmetic operators also have compound assignment operators as well, with addition, subtraction, division, ...

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

  12. Java Compound Operators

    Compound operators, also called combined assignment operators, are a shorthand way to update the value of a variableThey are+= (addition)-= (subtraction)*= (...

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

  14. Assignment operators

    For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment.. Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b. [] Assignment operator syntaThe assignment expressions have the form

  15. C

    There are four compound assignment operators in C language, such as +=, -= , *=, /=. Let's example each of these and their use with simple code examples.

  16. Compound Assignment Operator in C++

    In this article, I am going to discuss Compound Assignment Operator in C++ with Examples. We will learn about compound assignment operators

  17. C Assignment Operators

    A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand. The following example uses a compound-assignment operator (+=):

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

  19. c

    What is the real advantage of using compound assignment in C/C++ (or may be applicable to many other programming languages as well)? #include <stdio.h> int main() { int exp1=20; int...

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

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

  22. Expressions and operators

    This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.

  23. Compound Interest: What It Is, Formula, Examples

    Compound interest is the phenomenon that allows seemingly small amounts of money to grow into large amounts over time. Compound interest essentially means "interest on the interest" and is the ...

  24. What are compound exercises and why are they good for you?

    You could consider prioritising compound exercises if you're time poor, interested in healthy ageing and looking for an efficient way to train many muscles and joints in the one workout.

  25. CDC Current Outbreak List

    Multistate Foodborne Outbreaks - Foodborne outbreaks listed by year; Hepatitis A Outbreaks - Hepatitis A outbreak investigations since 2013 where CDC supported or led the investigation.; US Outbreaks Linked to Contact with Animals or Animal Products; Health Alert Network - Health alerts, health advisories, updates, and info service messages. Designed for public health and medical ...