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:

  • Java Expressions Introduced
  • Understanding the Concatenation of Strings in Java
  • Conditional Operators
  • Conditional Statements in Java
  • Working With Arrays in Java
  • Declaring Variables in Java
  • If-Then and If-Then-Else Conditional Statements in Java
  • How to Use a Constant in Java
  • Common Java Runtime Errors
  • What Is Java?
  • What Is Java Overloading?
  • Definition of a Java Method Signature
  • What a Java Package Is In Programming
  • Java: Inheritance, Superclass, and Subclass
  • Understanding Java's Cannot Find Symbol Error Message
  • Using Java Naming Conventions

All Subjects

AP Computer Science A

Compound Assignment Operators

Compound assignment operators are shorthand notations that combine an arithmetic operation with the assignment operator. They allow you to perform an operation and assign the result to a variable in a single step.

Related terms

+= operator : This operator adds the value on the right side of it to the variable on the left side, and then assigns the result back to that variable.

-= operator : This operator subtracts the value on the right side of it from the variable on the left side, and then assigns the result back to that variable.

*= operator : This operator multiplies the value on the right side of it with the variable on the left side, and then assigns the result back to that variable.

" Compound Assignment Operators " appears in:

Study guides ( 1 ).

  • AP Computer Science A - 1.4 Compound Assignment Operators

Practice Questions ( 1 )

  • Which arithmetic operators do not have compound assignment operators?

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

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

cppreference.com

Assignment operators.

(C11)
Miscellaneous
General
(C11)
(C99)

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

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

[ edit ] Simple assignment

The simple assignment operator expressions have the form

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

Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs .

Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non-lvalue (so that expressions such as ( a = b ) = c are invalid).

rhs and lhs must satisfy one of the following:

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

[ edit ] Notes

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

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

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

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

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

[ edit ] Compound assignment

The compound assignment operator expressions have the form

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

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

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

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

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

[ edit ] References

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

[ edit ] See Also

Operator precedence

Common operators

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a == b
a != b
a < b
a > b
a <= b
a >= b

a[b]
*a
&a
a->b
a.b

a(...)
a, b
(type) a
a ? b : c
sizeof


_Alignof
(since C11)

[ edit ] See also

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

Powered by MediaWiki

Introduction to Java 0 / 14

Control Flow and Decision Making 0 / 16

Arrays and Collections 0 / 5

Strings and Methods 0 / 6

Java Exception Handling 0 / 7

Threads and Multithreading in Java 0 / 2

Object-Oriented Programming in Java 0 / 8

Important Concepts 0 / 26

Learning Resources 0 / 4

Introduction

Efficiency and readability often go hand in hand in programming. As developers, we constantly strive to strike a balance between concise code and code that is easy to understand and maintain. 

This balancing act is made more elegant through the use of compound assignment operators in Java. These unassuming symbols, such as +=, -=, *=, /=, and more, possess the ability to transform the way we manipulate variables and perform arithmetic operations .

In this article, let’s know about the Java's compound assignment operators with examples and programs.

What are Compound Assignment Operators in Java?

Compound assignment operators in Java are shorthand notations that combine an arithmetic or bitwise operation with an assignment. They allow you to perform an operation on a variable's value and then assign the result back to the same variable in a single step. 

These operators are a convenient way to make your code more concise and readable. Compound assignment operators of Java are particularly useful when you want to modify a variable's value by a specific amount or using a specific operation.

Suggested Java Concepts:-

Java Constants

  Operators in Java

Java Arithmetic Operators

Bitwise Operators in Java

Java Compound Assignment Operators

Let’s understand all the compound assignment operators in Java with examples:

1. Addition and Assignment (+=)

This operator adds the right-hand operand to the left-hand operand and assigns the result back to the left-hand operand.

2. Subtraction and Assignment (-=)

This operator subtracts the right-hand operand from the left-hand operand and assigns the result back to the left-hand operand.

3. Multiplication and Assignment (*=)

This operator multiplies the left-hand operand by the right-hand operand and assigns the result back to the left-hand operand.

4. Division and Assignment (/=)

This operator divides the left-hand operand by the right-hand operand and assigns the result back to the left-hand operand.

5. Modulus and Assignment (%=)

This operator calculates the remainder of the division of the left-hand operand by the right-hand operand and assigns the result back to the left-hand operand.

6. Bitwise AND and Assignment (&=)

This operator performs a bitwise AND operation between the left-hand operand and the right-hand operand and assigns the result back to the left-hand operand.

7. Bitwise OR and Assignment (|=)

This operator performs a bitwise OR operation between the left-hand operand and the right-hand operand and assigns the result back to the left-hand operand.

8. Bitwise XOR and Assignment (^=)

This operator performs a bitwise XOR (exclusive OR) operation between the left-hand operand and the right-hand operand and assigns the result back to the left-hand operand.

Java Program With Compound Assignment Operators

Here's an example program that shows the use of compound assignment operators in Java language:

Explanation:

In this program, we start with several variables (a, b, c, etc.), and we apply compound assignment operators to modify their values. Each operator performs its respective operation on the variable and assigns the result back to the variable. The output at the end of the program shows the updated values of the variables after applying the compound assignment operators.

Suggested Java Programs for Practice:-

How to Convert Char to Int in Java? Character to Integer Conversion

How to Convert Int to Char in Java? Integer to Character

How to Convert Long to Int in Java? Long to Integer

How to Convert Int to Long in Java? Integer to Long Program

How to Convert Boolean to String in Java? (Parse Bool to String)

How to Convert String to Boolean in Java? 3 Ways With Program

How to Convert String to Int in Java? String to Integer Program

How to Convert Int to String in Java? Integer to String Program

How to Convert Int to Double in Java? (Integer to Double)

How to Convert Double to Int in Java? 4 Ways

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

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

Compound assignment operators are commonly used as they require less code to type. It's a shorter syntax of assigning the result of an arithmetic or bitwise operator, given that the variable to store the expression value is being used as an operand .

Compound Assignment Operator using Addition

Consider an example where we want to increase a given number by 3. The long version can be written as follows:

The number variable is used as the variable to store the expression value and as an operand. Because of this, we can use a shorter syntax of compound assignment operators. The code can be written as:

Let's see another example using string concatenation:

Using compound assignment operators, this can be condensed to:

Compound Assignment Operator using Subtraction

As another example, let's see how we can decrease a number by 3:

Again, since number is used as the variable to store the expression value and an operand, we can use the compound assignment operator:

All arithmetic and bitwise operators can be used in compound assignment operators. This post shows examples using addition and subtraction to show the general syntax. Division, multiplication, modulus, AND, OR, XOR,left shift, right shift, and unsigned right shift would also work. Overall, using the compound assignment operator requires less code to type and is more common to see code written this way.

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

C++ Operator Overloading Guidelines

One of the nice features of C++ is that you can give special meanings to operators, when they are used with user-defined classes. This is called operator overloading . You can implement C++ operator overloads by providing special member-functions on your classes that follow a particular naming convention. For example, to overload the + operator for your class, you would provide a member-function named operator+ on your class.

  • = (assignment operator)
  • + - * (binary arithmetic operators)
  • += -= *= (compound assignment operators)
  • == != (comparison operators)

Here are some guidelines for implementing these operators. These guidelines are very important to follow, so definitely get in the habit early.

Assignment Operator =

The assignment operator has a signature like this: class MyClass { public: ... MyClass & operator=(const MyClass &rhs); ... } MyClass a, b; ... b = a; // Same as b.operator=(a);

Notice that the = operator takes a const-reference to the right hand side of the assignment. The reason for this should be obvious, since we don't want to change that value; we only want to change what's on the left hand side.

  • e = 42 assigns 42 to e , then returns e as the result
  • The value of e is then assigned to d , and then d is returned as the result
  • The value of d is then assigned to c , and then c is returned as the result

Now, in order to support operator chaining, the assignment operator must return some value. The value that should be returned is a reference to the left-hand side of the assignment.

Notice that the returned reference is not declared const . This can be a bit confusing, because it allows you to write crazy stuff like this: MyClass a, b, c; ... (a = b) = c; // What?? At first glance, you might want to prevent situations like this, by having operator= return a const reference. However, statements like this will work with primitive types. And, even worse, some tools actually rely on this behavior. Therefore, it is important to return a non- const reference from your operator= . The rule of thumb is, "If it's good enough for int s, it's good enough for user-defined data-types."

So, for the hypothetical MyClass assignment operator, you would do something like this: // Take a const-reference to the right-hand side of the assignment. // Return a non-const reference to the left-hand side. MyClass& MyClass::operator=(const MyClass &rhs) { ... // Do the assignment operation! return *this; // Return a reference to myself. } Remember, this is a pointer to the object that the member function is being called on. Since a = b is treated as a.operator=(b) , you can see why it makes sense to return the object that the function is called on; object a is the left-hand side.

But, the member function needs to return a reference to the object, not a pointer to the object. So, it returns *this , which returns what this points at (i.e. the object), not the pointer itself. (In C++, instances are turned into references, and vice versa, pretty much automatically, so even though *this is an instance, C++ implicitly converts it into a reference to the instance.)

Now, one more very important point about the assignment operator:

YOU MUST CHECK FOR SELF-ASSIGNMENT!

This is especially important when your class does its own memory allocation. Here is why: The typical sequence of operations within an assignment operator is usually something like this: MyClass& MyClass::operator=(const MyClass &rhs) { // 1. Deallocate any memory that MyClass is using internally // 2. Allocate some memory to hold the contents of rhs // 3. Copy the values from rhs into this instance // 4. Return *this } Now, what happens when you do something like this: MyClass mc; ... mc = mc; // BLAMMO. You can hopefully see that this would wreak havoc on your program. Because mc is on the left-hand side and on the right-hand side, the first thing that happens is that mc releases any memory it holds internally. But, this is where the values were going to be copied from, since mc is also on the right-hand side! So, you can see that this completely messes up the rest of the assignment operator's internals.

The easy way to avoid this is to CHECK FOR SELF-ASSIGNMENT. There are many ways to answer the question, "Are these two instances the same?" But, for our purposes, just compare the two objects' addresses. If they are the same, then don't do assignment. If they are different, then do the assignment.

So, the correct and safe version of the MyClass assignment operator would be this: MyClass& MyClass::operator=(const MyClass &rhs) { // Check for self-assignment! if (this == &rhs) // Same object? return *this; // Yes, so skip assignment, and just return *this. ... // Deallocate, allocate new space, copy values... return *this; } Or, you can simplify this a bit by doing: MyClass& MyClass::operator=(const MyClass &rhs) { // Only do assignment if RHS is a different object from this. if (this != &rhs) { ... // Deallocate, allocate new space, copy values... } return *this; } Remember that in the comparison, this is a pointer to the object being called, and &rhs is a pointer to the object being passed in as the argument. So, you can see that we avoid the dangers of self-assignment with this check.

  • Take a const-reference for the argument (the right-hand side of the assignment).
  • Return a reference to the left-hand side, to support safe and reasonable operator chaining. (Do this by returning *this .)
  • Check for self-assignment, by comparing the pointers ( this to &rhs ).

Compound Assignment Operators += -= *=

I discuss these before the arithmetic operators for a very specific reason, but we will get to that in a moment. The important point is that these are destructive operators, because they update or replace the values on the left-hand side of the assignment. So, you write: MyClass a, b; ... a += b; // Same as a.operator+=(b) In this case, the values within a are modified by the += operator.

How those values are modified isn't very important - obviously, what MyClass represents will dictate what these operators mean.

The member function signature for such an operator should be like this: MyClass & MyClass::operator+=(const MyClass &rhs) { ... } We have already covered the reason why rhs is a const-reference. And, the implementation of such an operation should also be straightforward.

But, you will notice that the operator returns a MyClass -reference, and a non-const one at that. This is so you can do things like this: MyClass mc; ... (mc += 5) += 3;

Don't ask me why somebody would want to do this, but just like the normal assignment operator, this is allowed by the primitive data types. Our user-defined datatypes should match the same general characteristics of the primitive data types when it comes to operators, to make sure that everything works as expected.

This is very straightforward to do. Just write your compound assignment operator implementation, and return *this at the end, just like for the regular assignment operator. So, you would end up with something like this: MyClass & MyClass::operator+=(const MyClass &rhs) { ... // Do the compound assignment work. return *this; }

As one last note, in general you should beware of self-assignment with compound assignment operators as well. Fortunately, none of the C++ track's labs require you to worry about this, but you should always give it some thought when you are working on your own classes.

Binary Arithmetic Operators + - *

The binary arithmetic operators are interesting because they don't modify either operand - they actually return a new value from the two arguments. You might think this is going to be an annoying bit of extra work, but here is the secret:

Define your binary arithmetic operators using your compound assignment operators.

There, I just saved you a bunch of time on your homeworks.

So, you have implemented your += operator, and now you want to implement the + operator. The function signature should be like this: // Add this instance's value to other, and return a new instance // with the result. const MyClass MyClass::operator+(const MyClass &other) const { MyClass result = *this; // Make a copy of myself. Same as MyClass result(*this); result += other; // Use += to add other to the copy. return result; // All done! } Simple!

Actually, this explicitly spells out all of the steps, and if you want, you can combine them all into a single statement, like so: // Add this instance's value to other, and return a new instance // with the result. const MyClass MyClass::operator+(const MyClass &other) const { return MyClass(*this) += other; } This creates an unnamed instance of MyClass , which is a copy of *this . Then, the += operator is called on the temporary value, and then returns it.

If that last statement doesn't make sense to you yet, then stick with the other way, which spells out all of the steps. But, if you understand exactly what is going on, then you can use that approach.

You will notice that the + operator returns a const instance, not a const reference. This is so that people can't write strange statements like this: MyClass a, b, c; ... (a + b) = c; // Wuh...? This statement would basically do nothing, but if the + operator returns a non- const value, it will compile! So, we want to return a const instance, so that such madness will not even be allowed to compile.

  • Implement the compound assignment operators from scratch, and then define the binary arithmetic operators in terms of the corresponding compound assignment operators.
  • Return a const instance, to prevent worthless and confusing assignment operations that shouldn't be allowed.

Comparison Operators == and !=

The comparison operators are very simple. Define == first, using a function signature like this: bool MyClass::operator==(const MyClass &other) const { ... // Compare the values, and return a bool result. } The internals are very obvious and straightforward, and the bool return-value is also very obvious.

The important point here is that the != operator can also be defined in terms of the == operator, and you should do this to save effort. You can do something like this: bool MyClass::operator!=(const MyClass &other) const { return !(*this == other); } That way you get to reuse the hard work you did on implementing your == operator. Also, your code is far less likely to exhibit inconsistencies between == and != , since one is implemented in terms of the other.

compound assignment define

  • 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.12 Method Signatures (preview 2026 curriculum)
  • 1.13 Calling Class Methods (preview 2026 curriculum)
  • 1.4. Expressions and Assignment Statements" data-toggle="tooltip">
  • 1.6. Casting and Ranges of Values' data-toggle="tooltip" >

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

Time estimate: 45 min.

1.5. Compound Assignment Operators ¶

Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x . It is the same as x = x + 1 . This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound operators are written like += or =+ , just remember that the operation ( + ) is done first to produce the new value which is then assigned ( = ) back to the variable. So it’s operator then equal sign: += .

Since changing the value of a variable by one is especially common, there are two extra concise operators ++ and -- , also called the plus-plus or increment operator and minus-minus or decrement operator that set a variable to one greater or less than its current value.

Thus x++ is even more concise way to write x = x + 1 than the compound operator x += 1 . You’ll see this shortcut used a lot in loops when we get to them in Unit 4. Similarly, y-- is a more concise way to write y = y - 1 . These shortcuts only exist for + and - as they don’t really make sense for other operators.

If you’ve heard of the programming language C++, the name is an inside joke that C, an earlier language which C++ is based on, had been incremented or improved to create C++.

Here’s a table of all the compound arithmetic operators and the extra concise incremend and decrement operators and how they relate to fully written out assignment expressions. You can run the code below the table to see these shortcut operators in action!

Operator

Written out

= x + 1

= x - 1

= x * 2

= x / 2

= x % 2

Compound

+= 1

-= 1

*= 2

/= 2

%= 2

Extra concise

Run the code below to see what the ++ and shorcut operators do. Click on the Show Code Lens button to trace through the code and the variable values change in the visualizer. Try creating more compound assignment statements with shortcut operators and work with a partner to guess what they would print out before running the code.

If you look at real-world Java code, you may occassionally see the ++ and -- operators used before the name of the variable, like ++x rather than x++ . That is legal but not something that you will see on the AP exam.

Putting the operator before or after the variable only changes the value of the expression itself. If x is 10 and we write, System.out.println(x++) it will print 10 but aftewards x will be 11. On the other hand if we write, System.out.println(++x) , it will print 11 and afterwards the value will be 11.

In other words, with the operator after the variable name, (called the postfix operator) the value of the variable is changed after evaluating the variable to get its value. And with the operator before the variable (the prefix operator) the value of the variable in incremented before the variable is evaluated to get the value of the expression.

But the value of x after the expression is evaluated is the same in either case: one greater than what it was before. The -- operator works similarly.

The AP exam will never use the prefix form of these operators nor will it use the postfix operators in a context where the value of the expression matters.

exercise

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

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

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

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

1.5.1. Code Tracing Challenge and Operators Maze ¶

Use paper and pencil or the question response area below to trace through the following program to determine the values of the variables at the end.

Code Tracing is a technique used to simulate a dry run through the code or pseudocode line by line by hand as if you are the computer executing the code. Tracing can be used for debugging or proving that your program runs correctly or for figuring out what the code actually does.

Trace tables can be used to track the values of variables as they change throughout a program. To trace through code, write down a variable in each column or row in a table and keep track of its value throughout the program. Some trace tables also keep track of the output and the line number you are currently tracing.

../_images/traceTable.png

Trace through the following code:

1-5-4: Write your trace table for x, y, and z here showing their results after each line of code.

After doing this challenge, play the Operators Maze game . See if you and your partner can get the highest score!

1.5.2. Summary ¶

Compound assignment operators ( += , -= , *= , /= , %= ) can be used in place of the assignment operator.

The increment operator ( ++ ) and decrement operator ( -- ) are used to add 1 or subtract 1 from the stored value of a variable. The new value is assigned to the variable.

The use of increment and decrement operators in prefix form (e.g., ++x ) and inside other expressions (i.e., arr[x++] ) is outside the scope of this course and the AP Exam.

  • Java Course
  • 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

Java Assignment Operators with Examples

Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical, arithmetic, relational, etc. They are classified based on the functionality they provide.

Types of Operators: 

  • Arithmetic Operators
  • Unary Operators
  • Assignment Operator
  • Relational Operators
  • Logical Operators
  • Ternary Operator
  • Bitwise Operators
  • Shift Operators

This article explains all that one needs to know regarding Assignment Operators. 

Assignment Operators

These operators are used to assign values to a variable. The left side operand of the assignment operator is a variable, and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type of the operand on the left side. Otherwise, the compiler will raise an error. This means that the assignment operators have right to left associativity, i.e., the value given on the right-hand side of the operator is assigned to the variable on the left. Therefore, the right-hand side value must be declared before using it or should be a constant. The general format of the assignment operator is, 

Types of Assignment Operators in Java

The Assignment Operator is generally of two types. They are:

1. Simple Assignment Operator: The Simple Assignment Operator is used with the “=” sign where the left side consists of the operand and the right side consists of a value. The value of the right side must be of the same data type that has been defined on the left side.

2. Compound Assignment Operator: The Compound Operator is used where +,-,*, and / is used along with the = operator.

Let’s look at each of the assignment operators and how they operate: 

1. (=) operator: 

This is the most straightforward assignment operator, which is used to assign the value on the right to the variable on the left. This is the basic definition of an assignment operator and how it functions. 

Syntax:  

Example:  

2. (+=) operator: 

This operator is a compound of ‘+’ and ‘=’ operators. It operates by adding the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

Note: The compound assignment operator in Java performs implicit type casting. Let’s consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5 Method 2: x += 4.5 As per the previous example, you might think both of them are equal. But in reality, Method 1 will throw a runtime error stating the “i ncompatible types: possible lossy conversion from double to int “, Method 2 will run without any error and prints 9 as output.

Reason for the Above Calculation

Method 1 will result in a runtime error stating “incompatible types: possible lossy conversion from double to int.” The reason is that the addition of an int and a double results in a double value. Assigning this double value back to the int variable x requires an explicit type casting because it may result in a loss of precision. Without the explicit cast, the compiler throws an error. Method 2 will run without any error and print the value 9 as output. The compound assignment operator += performs an implicit type conversion, also known as an automatic narrowing primitive conversion from double to int . It is equivalent to x = (int) (x + 4.5) , where the result of the addition is explicitly cast to an int . The fractional part of the double value is truncated, and the resulting int value is assigned back to x . It is advisable to use Method 2 ( x += 4.5 ) to avoid runtime errors and to obtain the desired output.

Same automatic narrowing primitive conversion is applicable for other compound assignment operators as well, including -= , *= , /= , and %= .

3. (-=) operator: 

This operator is a compound of ‘-‘ and ‘=’ operators. It operates by subtracting the variable’s value on the right from the current value of the variable on the left and then assigning the result to the operand on the left. 

4. (*=) operator:

 This operator is a compound of ‘*’ and ‘=’ operators. It operates by multiplying the current value of the variable on the left to the value on the right and then assigning the result to the operand on the left. 

5. (/=) operator: 

This operator is a compound of ‘/’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the quotient to the operand on the left. 

6. (%=) operator: 

This operator is a compound of ‘%’ and ‘=’ operators. It operates by dividing the current value of the variable on the left by the value on the right and then assigning the remainder to the operand on the left. 

Please Login to comment...

Similar reads.

  • Java-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Why add an increment/decrement operator when compound assignments exist?

Many languages have compound assignment statements, for example += . However, for the common task of adding or subtracting 1 from a variable some languages (mostly those close to C) have additional ++ and -- operators. For example, x += 1 can be written as x++ in these languages. Some languages decide not to have these operators. This can make some sense, as there is already a short way to increment something. Why would you add an increment/decrement operator when you have compound assignments? For completeness, I'll allow arguments for the other position as well.

Seggan's user avatar

  • 4 $\begingroup$ I think the reason is that the specialized corresponding add/subtract by 1 instructions exist in Assembly. $\endgroup$ –  CPlus Commented Jul 8, 2023 at 0:42
  • 8 $\begingroup$ FYI, the increment/decrement operators came first. C inherited them from B, which didn't have compound assignments. The latter were a generalization that was added in C. $\endgroup$ –  Barmar Commented Jul 8, 2023 at 14:14
  • 4 $\begingroup$ For one thing, "C+=1" would be an awful name for a programming language. $\endgroup$ –  bta Commented Jul 10, 2023 at 19:43
  • 1 $\begingroup$ Why add compound assignment operators when separate assignment and arithmetic operators exist? Some languages choose not to have compound assignment operators. This can make some sense, as there is already a way to increment / decrement / etc . something. Why would you add compound assignments when you already have ordinary assignment and ordinary arithmetic operators? $\endgroup$ –  John Bollinger Commented Jul 10, 2023 at 20:40
  • 2 $\begingroup$ In PDP-11 assembly (other assembly languages were likely similar), ++ and += were natural representations for INC and ADD . Whereas in assembler you'd write MOV X, Y; ADD X, Z ( x = y; x += z; in C), C allowed you to write x = y + z . The fact that x += 1 and x++ are equivalent in the semantics of C doesn't change that fact that INC X was cheaper in several ways than ADD X, 1 . $\endgroup$ –  chepner Commented Jul 10, 2023 at 21:05

9 Answers 9

While x += 1 may be replaced by ++x, x++ is special in that it is essentially temp = x, x += 1, temp . I am making a C-like which is an evolution of C, so removing x++ was never even something I considered, but I will also say that I prefer to have ++x and x += 1 because they communicate different things in the code if both are available in the language.

++x tells me: "increment to the next value". That is, we're iterating over something. This might be walking through an array or looking at every value in a range. But it is not making any jumps or anything.

x += 1 on the other hand is saying "increase x by one", so this could be to adjust something by one, or jumping some amount, which just happened to be 1 but could just as well have been 2 or 5. Typically I would assume this means we're not using x to iterate (when ++ and -- exists in the language), and x += 1 is that hint.

That said, they are conveniences and can be dropped. Going as far as saying they're "actively harmful" like Swift does, seems like a very extreme opinion.

Nuoji's user avatar

  • 10 $\begingroup$ Yes, I've always been bothered by the use of x++ when ++x is appropriate. I know modern compilers will generate the same code, but my ancient brain still sees it as (temp = x, x += 1, temp) . $\endgroup$ –  Ray Butterworth Commented Jul 8, 2023 at 0:57
  • 2 $\begingroup$ @RayButterworth Hey, it sounds better like that ngl (my brain is probably not as ancient). $\endgroup$ –  Syed M. Sannan Commented Jul 8, 2023 at 6:31
  • 2 $\begingroup$ @Ray Modern compilers cannot generate the same code for each. For the actual increment or decrement, maybe. But the difference is that the ++a uses the new value immediately, wheras a++ continues to use the old value. The distinction is only resolved at the next "sequence point" (typically end of statement), which opens the door to a hatful of UB. $\endgroup$ –  Paul_Pedant Commented Jul 8, 2023 at 7:33
  • 3 $\begingroup$ If you look at it in SSA form the code will be pretty much identical, showing how the old value of x can easily be kept in a register. If you have int b = a++ , then it's also possible to think of that as int b = a; a += 1; . The lack of sequence points is just by definition in C. A language can easily decide UB due to ++ and -- well defined. $\endgroup$ –  Nuoji Commented Jul 9, 2023 at 8:24
  • 3 $\begingroup$ @Paul_Pedant they can generate the same code in cases where the value isn't observed until after that sequence-point, which is true in the (extremely) common case where x++ is a statement on its own. $\endgroup$ –  hobbs Commented Jul 10, 2023 at 1:43

C isn't a language that comes with fancy iteration constructs like foreach or map . This means programmers need to increment something every time they loop over indices of an array or a string, or over pointers.

Making i++ a shorthand for i += 1 makes a little more sense when you're going to spend so much time writing for (int i = 0; i < n; i++) or for (p = s; *p; p++) all over again.

Maybe more interestingly, even though += is more general and more powerful than ++ , more power might be bad . Having increment be distinct from compound assignment means you are encouraged to think at a different level of abstraction.

You're not "using the full power of addition", you're just doing the loop thing .

You don't need to visually slow down to verify that you're actually adding the digit 1 instead of a lowercase l that crept in here, you're just doing the loop thing .

To make this point clearer, I could make a parallel with while being a distinct, less powerful version of goto (remember: more expressive power isn't necessarily a good thing). Reading a goto instills fear in me, and makes me read the entire function again because otherwise I might miss some subtle control flow possibility. Reading a while is just reading a regular, well-known and well-delimited local construct.

In a way, it is the same for ++ . (And for equivalents in other languages, like inc in Pascal/Delphi.)

Eldritch Conundrum's user avatar

  • 5 $\begingroup$ I would disagree. I've had to write loops with i += 2 , or 4, or 8 rather than 1 enough times that it doesn't bother me when I see a for loop written that way. Heck, I've even sometimes seen those desugared into while loops, and the overall result is just as readable. $\endgroup$ –  Bbrk24 Commented Jul 7, 2023 at 21:52
  • 2 $\begingroup$ I don't think loops with += are less readable at all. I'm saying it's harder to confuse a ++ loop with a += loop. $\endgroup$ –  Eldritch Conundrum Commented Jul 8, 2023 at 7:22

The ++ and -- operators aren't really necessary. There are languages that get along just fine with x += 1 and x -= 1 . Like Python, or Swift (which had these operators but removed them for being error-prone ).

But because incrementing or decrementing a variable by 1 is extremely common (especially in a for loop), and because PDP-11 assembly language happened to make it easy to implement those operations, C's designers decided to provide ++ and -- as syntactic sugar. And then a bunch of other languages decided to adopt the C syntax for their operators.

dan04's user avatar

  • 2 $\begingroup$ This strikes me as a huge facepalm 🤦‍♂️ for swift. Their reasoning seems unsound given that they acknlowedge both the difference between statements and expressions (one returns a value) and the difference between pre and post increment. Perhaps there is some context in how people tend to write swift code. $\endgroup$ –  Bruce Adams Commented Jul 8, 2023 at 8:22
  • 3 $\begingroup$ I couldn't disagree more with Swift's decision, but +1 for this as an answer to the question asked. $\endgroup$ –  Jack Aidley Commented Jul 8, 2023 at 10:13
  • 3 $\begingroup$ @BruceAdams: Yeah, I'm not experienced with Swift, but the decision seems weird. They could have just changed the return value of the operators to Void , which would still allow x++ and x-- as standalone statements, while avoiding confusing uses like f(++x, x++) . $\endgroup$ –  dan04 Commented Jul 8, 2023 at 19:21
  • 4 $\begingroup$ @dan04 What would be the point of having x++ and ++x if they wouldn't return anything? The only difference between them is what they return. $\endgroup$ –  xigoi Commented Jul 8, 2023 at 19:51
  • 2 $\begingroup$ @xigoi: Just backwards compatibility. Both x++ and ++x would become redundant ways of spelling x += 1 as a standalone statement. $\endgroup$ –  dan04 Commented Jul 8, 2023 at 19:57

(Yes, I'm writing another answer to this question.) Sometimes i++ really is what you need. Here's an example where it shines. Consider the following code fragment:

How would you write that in a language that doesn't have, specifically, the postfix increment operator?

You could use constants:

But this is error prone! If you ever need to reorder these lines, or to insert another line, or to delete one of those lines, it's easy to forget updating the index constants.

You could use compound assignment:

But this is twice as many lines of code! And the alternation of lines isn't as easy to inspect... We make this look better:

But now the code is unaligned, again it is not easy to verify that the repeated part is correctly done and no index += 1 was forgotten (imagine longer lines). We can do better by moving the similar part towards the beginning of the line:

Now the code is compact and easy to verify again... But the index starts at -1, that's weird!

You could introduce a separate function:

Now this is good! Code is compact, it's easy to insert/delete/update lines, it's easy to verify that the index is good!

But we basically reimplemented i++ .

Looks like sometimes ++ is useful after all. Now, this doesn't mean it needs to be built-into the language ! The last solution can be acceptable, even more so if it can inline ReturnAndInc.

  • 2 $\begingroup$ You could also have the helper function do both the increment and the call to Set... But what if Set has overloads? Now you need to make many similar helper functions, kept in sync with the number of overloads... I didn't want to include that case in the answer. $\endgroup$ –  Eldritch Conundrum Commented Jul 8, 2023 at 8:08
  • 1 $\begingroup$ Yuck. Modern language design includes elements of adding syntactic sugar to remove boilerplate. Removing it for something so common seems wrong. $\endgroup$ –  Bruce Adams Commented Jul 8, 2023 at 8:24
  • 3 $\begingroup$ You could use i = -1; Set(i += 1, "Draw"); Set(i += 1, GetDistance()); etc. too, but that's also a bit awkward and then not everyone likes using (compound) assignments as expressions. Then again, why doesn't your Set() thingy have an append-like function that would keep track of the last used / first free index? $\endgroup$ –  ilkkachu Commented Jul 8, 2023 at 14:55
  • 1 $\begingroup$ Swift, in which ++ was removed, also decided to have += return void... And making a Set() that also increments the index is boilerplate work that might not always pay for itself, compared to sprinkling some ++ . $\endgroup$ –  Eldritch Conundrum Commented Jul 8, 2023 at 19:17
  • 2 $\begingroup$ Honestly I think the version that uses the constants is the most clear one. If you have a lot of these you can just iterate an integer range instead of mutating a variable. $\endgroup$ –  Aiono Commented Jul 8, 2023 at 19:54

In many cases, ++ and -- are used to move to the "next" thing or the "previous" thing. Although this is equivalent to adding 1, the essential concept embodied in the operation is "next" or "previous", and not "1".(*)

The situation is somewhat analogous to the way many languages allow a programmer to write if (flags & BITMASK) ... rather than if ((flags & BITMASK) != 0) . One might describe the former operation as "is the set of bits in common between the two values non-empty" and the latter as "is the set of bits of values equal to something other than the empty set".

IMHO, good languages should avoid requiring programmers to write "phony constants". If there's only one constant value that has a certain property, having a construct that embodies that property is cleaner than requiring that programmers specify the explicit construct.

(*) This becomes especially true if one views bytes of memory as being located between addresses, but with the convention that a single address will by default refer to the immediately following storage. Under this view, a 16-byte region of memory will have 17 addresses, with all but the last each uniquely pointing to the start of a byte, and all but the first each uniquely point to the end of a byte.

Viewing memory in this fashion, "incrementing" a pointer means that it should be made to identify an object that starts where the current object ends, and "decrementing" a pointer means it should be made to identify an object that ends where the current object starts. Note that in this scenario, there would be no space between the previously and newly identified objects.

supercat's user avatar

Why add an increment/decrement operator when compound assignnments exist?

Why add compound assignment when regular assignment exists? After all, in C, x += 1 is equivalent to x = x + 1 . Going further, there are many things that look redundant: why have all three of do..while , while and for ? Why have loops to begin with if you can use goto or recursion instead? Why do CPUs have all these instructions when x86's mov instruction is Turing complete ?

Languages are created to make programming more easy , but you also have to remember that you need to be able to create an interpreter and/or compiler for it. It's easy to forget that when K&R released their first specification of C, most consumer computers were still using 8-bit processors, and 64 kiB of RAM was considered a large amount. The PDP-11 that C was developed on was a 16-bit computer which could be made to support up to 4 MiB of RAM, but programs were still limited to a 16-bit address space. So compilers couldn't be very fancy.

As dan04 already mentioned, the PDP-11 had pre- and post-increment operations in its instruction set. So having increment/decrement operators in the language that are easy to parse and easy to generate instructions for makes a lot of sense. Also, consider that incrementing by one is an extremely common operation (already mentioned in several other answers), so it makes programming in C more easy. Consider this string copy function, which is just a one-liner when using post-increment on the pointers:

Some people object to this because they find it hard to follow. What if I write:

Even if it's well-defined it's hard to tell what this does without knowing exactly what the rules are for the ordering of operations here. It's worse if it's implementation-defined what will happen. That's an argument against these operators.

G. Sliepen's user avatar

  • $\begingroup$ x += 1 is not necessarily equivalent to x = x + 1 if you substitute a more complex expression for x , such as arr[rand() % arr_len] . $\endgroup$ –  xigoi Commented Jul 8, 2023 at 19:55
  • 1 $\begingroup$ @xigoi True, but you can easily work around that without needing compound assignment. My point is that a lot of things in languages are not really necessary, even if they are very convenient. $\endgroup$ –  G. Sliepen Commented Jul 8, 2023 at 21:10

C had those operators because C was designed to mirror the assembly of the particular machine it was developed for. Some modern languages have no such operator -- Swift in particular cited that ++ and -- were "actively harmful".

Bbrk24's user avatar

  • 5 $\begingroup$ It wasn't exactly designed for the purpose of mirroring the machine language; it was designed to take advantage of it. Compiling ++x trivially generated a single instruction. Compiling x+=1 would require testing for the 1 value in order to decide to handle that special case, which would make the compile take longer. (And yes, compilers really were very slow, so any time saving was worth it.) $\endgroup$ –  Ray Butterworth Commented Jul 8, 2023 at 0:54

There are some good long answers. The short one is that it makes working with arrays and other containers with dense index-based access easier, shorter and less error prone. You can easily misstype 2 instead of 1.

feldentm's user avatar

There are some important semantic differences between increment and decrement operators vs the addition and subtraction assignment operators.

Consider an iterator walking some kind of data structure like an array vs an expensive generator function. It may not be possible to jump to the Nth element without computing the intermediate elements first.

is equivalent to:

and indeed you can construct the whole of arithmetic this way, it is not necessarily efficient.

Defining a additional assignment operator can be used to imply that there is a short cut.

In some languages it is useful to imply the computational cost but not defining additional assignment if it is not efficient.

So for a number type you can easily do:

It would seem less intuitive to write:

There is potentially a loop in the second case which does not exist in the first case. Though it gives the right answer, Peano arithmetic is not computationally efficient.

Another difference is that increment and decrement tend to be usable as expressions while addition assignment tends to useable only as a statement.

is more intuitive than:

If used as an expression it would also be a pre-increment whereas x++ is a post increment.

With increment and decrement operators (in C and C++ at least) you can define whether the value is incremented before or after the return.

That is in the context of:

Whereas in the context of:

All this is true even without considering the historical origins of increment and decrement in relation to C as a layer on top of assembly languages which may themselves have distinct increment and addition operations.

Bruce Adams's user avatar

  • 1 $\begingroup$ This is the most compelling reason, IMO. $\endgroup$ –  leftaroundabout Commented Jul 10, 2023 at 9:33

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged operators assignment ..

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • Who became an oligarch after the collapse of the USSR
  • How to handle stealth before combat starts?
  • Isn't an appeal to emotions in fact necessary to validate our ethical decisions?
  • Cover letter format in Germany
  • Convert a Dataset into a list of lists and back to a Dataset
  • Dial “M” for murder
  • Does the Ghost achievement require no kills?
  • A short story where a space pilot has a device that sends the ship back in time just before losing a space battle. He is duplicated by accident
  • Function to find the most common numeric ordered pairings (value, count)
  • Why HIMEM was implemented as a DOS driver and not a TSR
  • Why does editing '/etc/shells' file using 'sudo open' shows an error saying I don't own the file?
  • Venus’ LIP period starts today, can we save the Venusians?
  • Non-linear recurrence for rational sequences with generating function with radicals?
  • Duffing Equation:Transition to Chaos
  • What's wrong with my app authentication scheme?
  • A study on the speed of gravity
  • Is there any point "clean-installing" on a brand-new MacBook?
  • Stargate "instructional" videos
  • DIN Rail Logic Gate
  • How do you "stealth" a relativistic superweapon?
  • I submitted a paper and later realised one reference was missing, although I had written the authors in the body text. What could happen?
  • tmux - How to remove delay after pressing prefix key and Up key
  • How did Jason Bourne know the garbage man isn't CIA?
  • Can I use the Chi-square statistic to evaluate theoretical PDFs against an empirical dataset of 60,000 values?

compound assignment define

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

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.

Advantage of using compound assignment

What is the real advantage of using compound assignment in C/C++ (or may be applicable to many other programming languages as well)?

I looked at few links like microsoft site , SO post1 , SO Post2 . But the advantage says exp1 is evaluated only once in case of compound statement. How exp1 is really evaluated twice in first case? I understand that current value of exp1 is read first and then new value is added. Updated value is written back to the same location. How this really happens at lower level in case of compound statement? I tried to compare assembly code of two cases, but I did not see any difference between them.

  • compound-assignment

Rajesh's user avatar

  • There's a good chance that your compiler optimised it. Anyway, assembly language usually has increment opcodes. In fact, they don't have anything else. If you do something like 1 + 2 in C, it would be compiled to something like move 1,a and add 2,a . –  SeverityOne Commented Apr 19, 2018 at 13:22
  • @SeverityOne's response should be the answer... –  Frederick Commented Apr 19, 2018 at 13:27

6 Answers 6

For simple expressions involving ordinary variables, the difference between

is syntactical only. The two expressions will behave exactly the same, and might well generate identical assembly code. (You're right; in this case it doesn't even make much sense to ask whether a is evaluated once or twice.)

Where it gets interesting is when the left-hand side of the assignment is an expression involving side effects. So if you have something like

it makes much more of a difference! The former tries to increment p twice (and is therefore undefined). But the latter evaluates p++ precisely once, and is well-defined.

As others have mentioned, there are also advantages of notational convenience and readability. If you have

it can be hard to spot the bug. But if you use

it's impossible to even have that bug, and a later reader doesn't have to scrutinize the terms to rule out the possibility.

A minor advantage is that it can save you a pair of parentheses (or from a bug if you leave those parentheses out). Consider:

Finally (thanks to Jens Gustedt for reminding me of this), we have to go back and think a little more carefully about what we meant when we said "Where it gets interesting is when the left-hand side of the assignment is an expression involving side effects." Normally, we think of modifications as being side effects, and accesses as being "free". But for variables qualified as volatile (or, in C11, as _Atomic ), an access counts as an interesting side effect, too. So if variable a has one of those qualifiers, a = a + b is not a "simple expression involving ordinary variables", and it may not be so identical to a += b , after all.

Steve Summit's user avatar

  • Got the real issue now. I think most books does not highlight this concept of two time evaluation by giving good example. In fact this is the most important difference than the readability. @dbush also gave another good example where we can easily see the result of two time evaluation. Disadvantage indicated by chux also give us better clarity. –  Rajesh Commented Apr 19, 2018 at 14:58
  • No, they are not always the same. It depends on what a is. If it is volatile or _Atomic the result is fundamentally different. –  Jens Gustedt Commented Apr 19, 2018 at 18:54
  • How would tmp = *XYZ; be interpreted and why? my compiler interprets this as: Copy *XYZ to temp, and why not tmp = tmp * XYZ ? Note: XYZ is pointer. –  M Sharath Hegde Commented Aug 30, 2018 at 6:58
  • 1 @MSharathHegde If the compound assignment operator were spelled " =* ", there might be some ambiguity here, but since it is in fact spelled " *= ", it's perfectly clear that tmp=*XYZ must involve a pointer access, not a multiplication. (Now, in the earliest days of C, the compound assignment operator was spelled " =* ", and there was ambiguity, which is why the compound assignment operators were rejiggered to their modern form.) –  Steve Summit Commented Aug 30, 2018 at 9:27

Evaluating the left side once can save you a lot if it's more than a simple variable name. For example:

In this case some_long_running_function() is only called once. This differs from:

Which calls the function twice.

dbush's user avatar

There is a disadvantage too. Consider the effect of types.

10 + b addition below will use int math and overflow ( undefined behavior )

chux - Reinstate Monica's user avatar

  • even clang -Weverything don't produce warning... it's should ! –  Stargateur Commented Apr 19, 2018 at 14:42

This is what the standard 6.5.16.2 says:

A compound assignment of the form E1 op = E2 is equivalent to the simple assignment expression E1 = E1 op ( E2 ), except that the lvalue E1 is evaluated only once

So the "evaluated once" is the difference. This mostly matters in embedded systems where you have volatile qualifiers and don't want to read a hardware register several times, as that could cause unwanted side-effects.

That's not really possible to reproduce here on SO, so instead here's an artificial example to demonstrate why multiple evaluations could lead to different program behavior:

The simple assignment version did not only give a different result, it also introduced unspecified behavior in the code, so that two different results are possible depending on the compiler.

Eric Postpischil's user avatar

  • correct. in addition to volatile it can also make a difference for atomic qualified types. –  Jens Gustedt Commented Apr 19, 2018 at 18:57

Not sure what you're after. Compound assignment is shorter, and therefore simpler (less complex) than using regular operations.

Consider this:

Which one is easier to read and understand, and verify?

This, to me, is a very very real advantage, and is just as true regardless of semantic details like how many times something is evaluated.

unwind's user avatar

  • Arguably the main issue with your example is that you don't follow the law of Demeter. The difference between x += dt * speed and x =x + dt * speed is less, but still worth having. –  Pete Kirkham Commented Apr 19, 2018 at 13:38
  • I agree with this answer. Modern compilers usually do not need any "help" by programmers using specific language constructs. In fact today better readability of a code fragment usually also means better optimization by the compiler. –  Blue Commented Apr 19, 2018 at 13:41
  • @unwind I am mainly talking about performance related issues rather than readability. According to Microsoft, "However, the compound-assignment expression is not equivalent to the expanded version because the compound-assignment expression evaluates expression1 only once, while the expanded version evaluates expression1 twice: in the addition operation and in the assignment operation". Here is what I am expecting some kind of explanation. –  Rajesh Commented Apr 19, 2018 at 13:49

A language like C is always going to be an abstraction of the underlying machine opcodes. In the case of addition, the compiler would first move the left operand into the accumulator, and add the right operand to it. Something like this (pseudo-assembler code):

This is what 1+2 would compile to in assembler. Obviously, this is perhaps over-simplified, but you get the idea.

Also, compiler tend to optimise your code, so exp1=exp1+b would very likely compile to the same opcodes as exp1+=b .

And, as @unwind remarked, the compound statement is a lot more readable.

SeverityOne's user avatar

  • I am using TDM-GCC-64 compiler. Optimization is turned off. Here is the log 'gcc.exe -Wall -s -pedantic -Wextra -Wall -g -c "C:\sample_Project_Only_Main\main.c" -o Debug\main.o g++.exe -o Debug\sample_Project_Only_Main.exe Debug\main.o " –  Rajesh Commented Apr 19, 2018 at 13:54
  • Fair enough. Still, assembly always works along the lines of "add something to a register or memory location", which is what the += operator does. –  SeverityOne Commented Apr 19, 2018 at 17:03

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 c11 compound-assignment or ask your own question .

  • The Overflow Blog
  • Scaling systems to manage all the metadata ABOUT the data
  • Navigating cities of code with Norris Numbers
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • Venus’ LIP period starts today, can we save the Venusians?
  • What majority age is taken into consideration when travelling from country to country?
  • Parasols on an Alderson Disk
  • Would donations count as revenue from a free software?
  • How to create a extruded 4-star shape that is rotated inwards?
  • What is a word/phrase that best describes a "blatant disregard or neglect" for something, but with the connotation of that they should have known?
  • Violation of the Law of Total Expectation in the Unit Square?
  • How did Jason Bourne know the garbage man isn't CIA?
  • A short story where a space pilot has a device that sends the ship back in time just before losing a space battle. He is duplicated by accident
  • Is there a "simplest" way to embed a graph in 3-space?
  • Why is this white line between the two vertical boxes?
  • Why was I was allowed to bring 1.5 liters of liquid through security at Frankfurt Airport?
  • Word to classify what powers a god is associated with?
  • Stargate "instructional" videos
  • Guitar amplifier placement for live band
  • How to handle stealth before combat starts?
  • Old ESTA overwritten by new ESTA?
  • Does the Ghost achievement require no kills?
  • Did the Space Shuttle weigh itself before deorbit?
  • Why does editing '/etc/shells' file using 'sudo open' shows an error saying I don't own the file?
  • Why HIMEM was implemented as a DOS driver and not a TSR
  • DIN Rail Logic Gate
  • Advice needed: Team needs developers, but company isn't posting jobs
  • What does it mean to have a truth value of a 'nothing' type instance?

compound assignment define

IMAGES

  1. 025 Compound assignment operators (Welcome to the course C programming)

    compound assignment define

  2. PPT

    compound assignment define

  3. Answered: Pick out the compound assignment…

    compound assignment define

  4. Exploring Compound Assignment Operators in C

    compound assignment define

  5. Define on Compound Management

    compound assignment define

  6. Compound Assignment Operators in C Programming Language

    compound assignment define

COMMENTS

  1. What Is a Compound-Assignment Operator?

    Compound-Assignment Operators in Java. Java supports 11 compound-assignment operators: += assigns the result of the addition. -= assigns the result of the subtraction. *= assigns the result of the multiplication. /= assigns the result of the division. %= assigns the remainder of the division. &= assigns the result of the logical AND.

  2. Assignment operators

    For all other compound assignment operators, the type of target-expr must be an arithmetic type. In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

  3. C Compound Assignment

    The result of a compound-assignment operation has the value and type of the left operand. #define MASK 0xff00 n &= MASK; In this example, a bitwise-inclusive-AND operation is performed on n and MASK, and the result is assigned to n. The manifest constant MASK is defined with a #define preprocessor directive. See also. C Assignment Operators

  4. Compound assignment operators in Java

    The compound assignment operators are +=, -=, *=, /=, %= etc. The. 2 min read. Java Assignment Operators with Examples. Operators constitute the basic building block of any programming language. Java too provides many types of operators which can be used according to the need to perform various calculations and functions, be it logical ...

  5. Assignment operators

    Compound assignment. For a binary operator op, a compound assignment expression of the form. x op= y is equivalent to. x = x op y ... However, a user-defined type can define an implicit conversion to another type. That way, the value of a user-defined type can be assigned to a variable, a property, or an indexer element of another type.

  6. Compound Assignment Operators

    Definition. Compound assignment operators are shorthand notations that combine an arithmetic operation with the assignment operator. They allow you to perform an operation and assign the result to a variable in a single step.

  7. Assignment Operators In C++

    Compound Assignment Operators. In C++, the assignment operator can be combined into a single operator with some other operators to perform a combination of two operations in one single statement. These operators are called Compound Assignment Operators. There are 10 compound assignment operators in C++: Addition Assignment Operator ( += )

  8. Assignment operators

    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

  9. PDF Compound assignment operators

    The compound operators are different in two ways, which we see by looking more precisely at their definition. The Java language specification says that: The compound assignment E1 op= E2 is equivalent to [i.e. is syntactic sugar for] E1 = (T) ((E1) op (E2)) where T is the type of E1, except that E1 is evaluated only once. E1 is evaluated once.

  10. Assignment operators

    Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs . Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non ...

  11. Compound Assignment Operators in Java (With Examples)

    These operators are a convenient way to make your code more concise and readable. Compound assignment operators of Java are particularly useful when you want to modify a variable's value by a specific amount or using a specific operation. Suggested Java Concepts:-Java Constants Operators in Java. Java Arithmetic Operators. Bitwise Operators in Java

  12. PDF Compound assignment operators

    The compound operators are different in two ways, which we see by looking more precisely at their definition. The Java language specification says that: The compound assignment E1 op= E2 is equivalent to [i.e. is syntactic sugar for] E1 = (T) ((E1) op (E2)) where T is the type of E1, except that E1 is evaluated only once.

  13. 1.5. Compound Assignment Operators

    Compound Assignment Operators — CS Java. 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.

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

    Compound assignment operators are commonly used as they require less code to type. It's a shorter syntax of assigning the result of an arithmetic or bitwise operator, given that the variable to store the expression value is being used as an operand. Compound Assignment Operator using Addition.

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

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

  17. C++ Operator Overloading Guidelines

    Implement the compound assignment operators from scratch, and then define the binary arithmetic operators in terms of the corresponding compound assignment operators. Return a const instance, to prevent worthless and confusing assignment operations that shouldn't be allowed. Comparison Operators == and !=

  18. 1.5. Compound Assignment Operators

    1.5. Compound Assignment Operators¶. Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x.It is the same as x = x + 1.This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound ...

  19. Java Assignment Operators with Examples

    Note: The compound assignment operator in Java performs implicit type casting. Let's consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5. Method 2: x += 4.5.

  20. What is the use of >>= or <<= compound assignment in c++?

    those are called compound assignment operators. There are almost 10 of them in C/C++ language. ex += -= *= <<= >>=. When one of the operand is same as the variable to which final result to be assigned is same, in a binary operation this can be used as a short hand syntax. Ex a=a+b can be written as a+=b. in the same a=a<<2 can be written as a<<=2.

  21. Compound assignment in C++

    6. The compound assignment operators are in the second lowest precedence group of all in C++ (taking priority over only the comma operator). Thus, your a += b % c case would be equivalent to a += ( b % c ), or a = a + ( b % c ). This explains why your two code snippets are different. The second:

  22. Why add an increment/decrement operator when compound assignments exist

    Many languages have compound assignment statements, for example +=.However, for the common task of adding or subtracting 1 from a variable some languages (mostly those close to C) have additional ++ and --operators. For example, x += 1 can be written as x++ in these languages. Some languages decide not to have these operators.

  23. c

    According to Microsoft, "However, the compound-assignment expression is not equivalent to the expanded version because the compound-assignment expression evaluates expression1 only once, while the expanded version evaluates expression1 twice: in the addition operation and in the assignment operation". Here is what I am expecting some kind of ...