• 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
  • Java Arithmetic Operators with Examples
  • Interesting facts about Increment and Decrement operators in Java
  • Java Logical Operators with Examples
  • Java | Operators | Question 8
  • Java | Operators | Question 1
  • Java | Operators | Question 3
  • Java | Operators | Question 7
  • Java | Operators | Question 4
  • Assignment Operators in C
  • Assignment Operators In C++
  • Augmented Assignment Operators in Python
  • Assignment Operators in Programming
  • Operators in Java
  • Solidity - Assignment Operators
  • Arithmetic Operators in Solidity
  • Arrays in Java
  • Spring Boot - Start/Stop a Kafka Listener Dynamically
  • Parse Nested User-Defined Functions using Spring Expression Language (SpEL)
  • Split() String method in Java with examples
  • Arrays.sort() in Java with examples
  • For-each loop in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Reverse a string in Java
  • HashMap in Java
  • How to iterate any Map 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

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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.

Inscreva-se

Game dev series vol.01, o primeiro livro didático sobre programação para jogos digitais..

gdsv1_book01_d

Comece com os conceitos básicos de programação.

Conheça o nosso curso gratuito para você que quer começar a aprender programação., conheça as nossas publicações na página de artigos..

should compound assignment operators be avoided

Termos de uso

Política de Privacidade

should compound assignment operators be avoided

Este site usa cookies para garantir que você obtenha a melhor experiência.

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:

  • Conditional Operators
  • Java Expressions Introduced
  • Understanding the Concatenation of Strings in Java
  • The 7 Best Programming Languages to Learn for Beginners
  • Math Glossary: Mathematics Terms and Definitions
  • 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
  • The History of Algebra

The Creating Coder

Lesson 24: compound assignment operators.

In some of the earlier lessons, we went over some of the different math operators.  In the chart below, it shows the most common math operators we use in Java. Equation Type Operator Division / Multiplication * Addition + Subtraction – In this lesson, we are going to learn about a shortcut that can be…

In some of the earlier lessons, we went over some of the different math operators.  In the chart below, it shows the most common math operators we use in Java.

In this lesson, we are going to learn about a shortcut that can be used to cut back on syntax.  For simplicity’s sake, we will start with addition.  

Let’s say that we had an int i = 1 in our program, and that we want to add 5 to i.  Based on what we have gone over, we would put something like the following:

should compound assignment operators be avoided

The output would be 6 because int i is equal to 1, and then we add our value of i to 5 to get 6.  Now, let’s look at the code below to see how it would look if we had used a compound assignment operator.

should compound assignment operators be avoided

See the difference?  Instead of the i = i + 5 , we simply replace it with i += 5 and it gives us the exact same answer of 6.  

The important thing to note is that the first coding example does the exact same thing as the second coding example.  The only difference between the two is the syntax.  One is not necessarily better than the other.  It is just a simple way that some people prefer to shorten their code.  Look at the chart below to see how addition, subtraction, multiplication, and division would be written in a compound assignment operator’s form.

Even if you find yourself sticking to the way you originally learned, do not worry about it.  I still find myself trying to avoid using compound assignment operators and the minor complications that can arise from using them.  However, it is still important to know and recognize them when we are looking over other programmer’s code.

GitHub link.

Share this:

Leave a reply cancel reply.

' src=

  • Already have a WordPress.com account? Log in now.
  • Subscribe Subscribed
  • Copy shortlink
  • Report this content
  • View post in Reader
  • Manage subscriptions
  • Collapse this bar

05 - compound assignment

Compound assignment operators can be defined both as free functions and as member functions. Member functions are preferred because their implementation is simpler and since the operation has no symmetry ( a += b is not the same as b += a for non-numeric abstractions, e.g. strings) there are no problems with inconsistent implicit convertion.

Both free and member function implementations can return a reference to allow chained operations like a = b = c = d (most commonly done with operators << and >> ) (member function uses return * this ; statement, free function returns first parameter which for the cause of modification is taken by non-const reference).

To avoid code duplication, there are 2 choices:

compound assignments reuse other operators

other operators reuse compound assignments

The second one is preferred. Reason: just simpler and less code to write.

Updated code:

cppreference.com

Assignment operators.

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

[ edit ] Simple assignment

The simple assignment operator expressions have the form

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)

[ 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

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

[ 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

[ edit ] See also

  • 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 08:36.
  • This page has been accessed 54,567 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Chapter 9. Operators

This chapter gives an overview of operators.

Operators and Objects

All operators coerce (as discussed in Type Coercion ) their operands to appropriate types. Most operators only work with primitive values (e.g., arithmetic operators and comparison operators). That means that objects are converted to primitives before anything is done with them. One example where that is unfortunate is the plus operator, which many languages use for array concatenation. That’s not so with JavaScript, however, where this operator converts arrays to strings and appends them:

There is no way to overload or customize operators in JavaScript, not even equality.

Assignment Operators

There are several ways to use the plain assignment operator:

An assignment is an expression that evaluates to the assigned value. That allows you to chain assignments. For example, the following statement assigns 0 to both y and x :

Compound Assignment Operators

A compound assignment operator is written as op= , where op is one of several binary operators and = is the assignment operator. The following two expressions are equivalent:

In other words, a compound assignment operator op= applies op to both operands and assigns the result to the first operand. Let’s look at an example of using the plus operator ( + ) via compound assignment:

The following are all compound assignment operators:

  • Arithmetic operations (see Arithmetic Operators ): *= , /= , %= , += , -=
  • Bitwise operations (see Binary Bitwise Operators ): <<= , >>= , >>>= , &= , ^= , |=
  • String concatenation (see Concatenation: The Plus (+) Operator ): +=

Equality Operators: === Versus ==

JavaScript has two ways of determining whether two values are equal:

  • Strict equality ( === ) and strict inequality ( !== ) consider only values that have the same type to be equal.
  • Normal (or “lenient”) equality ( == ) and inequality ( != ) try to convert values of different types before comparing them as with strict (in)equality.

Lenient equality is problematic in two regards. First, how it performs conversion is confusing. Second, due to the operators being so forgiving, type errors can remain hidden longer.

Always use strict equality and avoid lenient equality. You only need to learn about the latter if you want to know why it should be avoided.

Equality is not customizable. Operators can’t be overloaded in JavaScript, and you can’t customize how equality works. There are some operations where you often need to influence comparison—for example, Array.prototype.sort() (see Sorting and Reversing Elements (Destructive) ). That method optionally accepts a callback that performs all comparisons between array elements.

Strict Equality (===, !==)

Values with different types are never strictly equal. If both values have the same type, then the following assertions hold:

  • undefined === undefined
  • null === null

Two numbers:

  • Two booleans, two strings: obvious results

Two objects (including arrays and functions): x === y if and only if x and y are the same object; that is, if you want to compare different objects, you have to implement your own comparison algorithm:

  • Everything else: not strictly equal.

Pitfall: NaN

The special number value NaN (see NaN ) is not equal to itself:

Thus, you need to use other means to check for it, which are described in Pitfall: checking whether a value is NaN .

Strict inequality (!==)

A strict inequality comparison:

is equivalent to the negation of a strict equality comparison:

Normal (Lenient) Equality (==, !=)

The algorithm for comparing via normal equality works as follows. If both operands have the same type (one of the six specification types—Undefined, Null, Boolean, Number, String, and Object), then compare them via strict equality.

Otherwise, if the operands are:

undefined and null , then they are considered leniently equal:

  • A string and a number, then convert the string to a number and compare both operands via strict equality.
  • A boolean and a nonboolean, then convert the boolean to a number and compare leniently (again).
  • An object and a number or a string, then try to convert the object to a primitive (via the algorithm described in Algorithm: ToPrimitive()—Converting a Value to a Primitive ) and compare leniently (again).

Otherwise—if none of the aforementioned cases apply—the result of the lenient comparison is false .

Lenient inequality (!=)

An inequality comparison:

is equivalent to the negation of an equality comparison:

Pitfall: lenient equality is different from conversion to boolean

Step 3 means that equality and conversion to boolean (see Converting to Boolean ) work differently. If converted to boolean, numbers greater than 1 become true (e.g., in if statements). But those numbers are not leniently equal to true . The comments explain how the results were computed:

Similarly, while the empty string is equal to false , not all nonempty strings are equal to true :

Pitfall: lenient equality and strings

Some of the leniency can be useful, depending on what you want:

Other cases are problematic, due to how JavaScript converts strings to numbers (see Converting to Number ):

Pitfall: lenient equality and objects

If you compare an object to a nonobject, it is converted to a primitive, which leads to strange results:

However, two objects are only equal if they are they same object. That means that you can’t really compare two wrapper objects:

There Are No Valid Use Cases for ==

You sometimes read about valid use cases for lenient equality ( == ). This section lists them and points out better alternatives.

Use case: checking for undefined or null

The following comparison ensures that x is neither undefined nor null :

While this is a compact way of writing this check, it confuses beginners, and experts can’t be sure whether it is a typo or not. Thus, if you want to check whether x has a value, use the standard check for truthiness (covered in Truthy and Falsy Values ):

If you want to be more precise, you should perform an explicit check for both values:

Use case: working with numbers in strings

If you are not sure whether a value x is a number or a number-as-a-string, you can use checks such as the following:

The preceding checks whether x is either 123 or '123' . Again, this is very compact, and again, it is better to be explicit:

Use case: comparing wrapper instances with primitives

Lenient equals lets you compare primitives with wrapped primitives:

There are three reasons against this approach. First, lenient equality does not work between wrapped primitives:

Second, you should avoid wrappers anyway. Third, if you do use them, it is better to be explicit:

Ordering Operators

JavaScript knows the following ordering operators:

  • Less than ( < )
  • Less than or equal ( <= )
  • Greater than ( > )
  • Greater than or equal ( >= )

These operators work for numbers and for strings:

For strings, they are not very useful, because they are case-sensitive and don’t handle features such as accents well (for details, see Comparing Strings ).

The Algorithm

You evaluate a comparison:

by taking the following steps:

  • Ensure that both operands are primitives. Objects obj are converted to primitives via the internal operation ToPrimitive(obj, Number) (refer to Algorithm: ToPrimitive()—Converting a Value to a Primitive ), which calls obj.valueOf() and, possibly, obj.toString() to do so.
  • If both operands are strings, then compare them by lexicographically comparing the 16-bit code units (see Chapter 24 ) that represent the JavaScript characters of the string.
  • Otherwise, convert both operands to numbers and compare them numerically.

The other ordering operators are handled similarly.

The Plus Operator (+)

Roughly, the plus operator examines its operands. If one of them is a string, the other is also converted to a string and both are concatenated:

Otherwise, both operands are converted to numbers (see Converting to Number ) and added:

That means that the order in which you evaluate matters:

You evaluate an addition:

  • Ensure that both operands are primitives. Objects obj are converted to primitives via the internal operation ToPrimitive(obj) (refer to Algorithm: ToPrimitive()—Converting a Value to a Primitive ), which calls obj.valueOf() and, possibly, obj.toString() to do so. For dates, obj.toString() is called first.
  • If either operand is a string, then convert both to strings and return the concatenation of the results.
  • Otherwise, convert both operands to numbers and return the sum of the results.

Operators for Booleans and Numbers

The following operators only have operands of a single type and also produce results of that type. They are covered elsewhere.

Boolean operators:

Binary logical operators (see Binary Logical Operators: And (&&) and Or (||) ):

Logical Not (see Logical Not (!) ):

Number operators:

Arithmetic operators (see Arithmetic Operators ):

Bitwise operators (see Bitwise Operators ):

Special Operators

Here we will review special operators, namely the conditional, comma, and void operators.

The Conditional Operator ( ? : )

The conditional operator is an expression:

If the condition is true , the result is if_true ; otherwise, the result is if_false . For example:

The parentheses around the operator are not needed, but they make it easier to read.

The Comma Operator

The comma operator evaluates both operands and returns the result of right . Roughly, it does for expressions what the semicolon does for statements.

This example demonstrates that the second operand becomes the result of the operator:

This example demonstrates that both operands are evaluated:

The comma operator is confusing. It’s better to not be clever and to write two separate statements whenever you can.

The void Operator

The syntax for the void operator is:

which evaluates expr and returns undefined . Here are some examples:

Thus, if you implement void as a function, it looks as follows:

The void operator is associated closely with its operand, so use parentheses as necessary. For example, void 4+7 binds as (void 4)+7 .

What is void used for?

Under ECMAScript 5, void is rarely useful. Its main use cases are:

In some situations, it is important to return undefined as opposed to the result of an expression. Then void can be used to discard that result. One such situation involves javascript: URLs, which should be avoided for links, but are useful for bookmarklets. When you visit one of those URLs, many browsers replace the current document with the result of evaluating the URL’s “content,” but only if the result isn’t undefined . Hence, if you want to open a new window without changing the currently displayed content, you can do the following:

Why does JavaScript have a void operator?

According to JavaScript creator Brendan Eich, he added it to the language to help with javascript: links (one of the aforementioned use cases):

I added the void operator to JS before Netscape 2 shipped to make it easy to discard any non-undefined value in a javascript: URL. [ 12 ]

Categorizing Values via typeof and instanceof

If you want to categorize a value, you unfortunately have to distinguish between primitives and objects (refer back to Chapter 8 ) in JavaScript:

  • The typeof operator distinguishes primitives from objects and determines the types of primitives.
  • The instanceof operator determines whether an object is an instance of a given constructor. Consult Chapter 17 for more information on object-oriented programming in JavaScript.

typeof: Categorizing Primitives

The typeof operator:

returns a string describing what kind of value value is. Here are some examples:

typeof is used to distinguish primitives and objects and to categorize primitives (which cannot be handled by instanceof ). Unfortunately, the results of this operator are not completely logical and only loosely correspond to the types of the ECMAScript specification (which are explained in JavaScript’s Types ):

Pitfall: typeof null

Unfortunately, typeof null is 'object' . This is considered a bug ( null is not a member of the internal type Object), but it can’t be fixed, because doing so would break existing code. You thus have to be wary of null . For example, the following function checks whether value is an object:

Trying it out:

The history of typeof null

The first JavaScript engine represented JavaScript values as 32-bit words. The lowest 3 bits of such a word were used as a type tag, to indicate whether the value was an object, an integer, a double, a string, or a boolean (as you can see, even this early engine already stored numbers as integers if possible).

The type tag for objects was 000. In order to represent the value null , the engine used the machine language NULL pointer, a word where all bits are zero. typeof checked the type tag to determine the type of value, which is why it reported null to be an object. [ 13 ]

Checking whether a variable exists

has two use cases:

  • It determines whether x is undefined .
  • It determines whether the variable x exists.

Here are examples of both use cases:

For the first use case, comparing directly with undefined is usually a better choice. However, it doesn’t work for the second use case:

instanceof: Checking Whether an Object Is an Instance of a Given Constructor

The instanceof operator :

determines whether value has been created by the constructor Constr or a subconstructor. Here are some examples:

As expected, instanceof is false for the nonvalues undefined and null :

But it is also false for all other primitive values:

For details on instanceof , consult The instanceof Operator .

Object Operators

The following three operators work on objects. They are explained elsewhere:

[ 10 ] Strictly speaking, setting an array element is a special case of setting a property.

[ 11 ] Thanks to Brandon Benvie (@benvie), who told me about using void for IIFEs.

[ 12 ] Source: http://en.wikipedia.org/wiki/Bookmarklet

[ 13 ] Thanks to Tom Schuster (@evilpies) for pointing me to the source code of the first JavaScript engine.

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

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

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

Javatpoint Logo

Java Tutorial

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

JavaTpoint

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

Assignment and Compound Assignment Operator

Get introduced to the functionality of the assignment and the compound assignment operator.

  • Assignment operator
  • Example program
  • Compound assignment operator

Assignment operator #

The assignment operator takes the value on its right-hand side and assigns it to the operand on the left-hand side.

Get hands-on with 1200+ tech skills courses.

Assignment operators

Simple assignment operator =, compound assignment operators.

All assignment operators have the same precedence and have right-to-left associativity.

The simple assignment operator has the following form:

lvalue = expr

The operator stores the value of the right operand expr in the object designated by the left operand lvalue .

If the left operand is not a class type, the right operand is implicitly converted to the type of the left operand. This converted type is not be qualified by const or volatile .

If the left operand is a class type, that type must be complete. The copy assignment operator of the left operand is called.

If the left operand is an object of reference type, the compiler assigns the value of the right operand to the object denoted by the reference.

If one operand is packed and the other is not, z/OS® XL C/C++ remaps the layout of the right operand to match the layout of the left. This remapping of structures might degrade performance. For efficiency, when you perform assignment operations with structures or unions, you should ensure that both operands are either packed or nonpacked.

The compound assignment operators consist of a binary operator and the simple assignment operator. They perform the operation of the binary operator on both operands and store the result of that operation into the left operand, which must be a modifiable lvalue.

The following table shows the operand types of compound assignment expressions:

The following table lists the compound assignment operators and shows an expression using each operator:

Although the equivalent expression column shows the left operands (from the example column) twice, it is in effect evaluated only once.

IMAGES

  1. SQL SERVER

    should compound assignment operators be avoided

  2. PPT

    should compound assignment operators be avoided

  3. Exploring Compound Assignment Operators in C

    should compound assignment operators be avoided

  4. Understanding Compound Assignment Operators in Java: Why They Can Be

    should compound assignment operators be avoided

  5. PPT

    should compound assignment operators be avoided

  6. PPT

    should compound assignment operators be avoided

VIDEO

  1. Lesson16 Compound assignment with Arithmetic Operators & Assignment By Reference

  2. 61. Compound Operators

  3. Compound Assignment Operators in C++ || C++ Programming #viral #subscribe

  4. GROUP ASSIGNMENT MAT112 (COMPOUND INTEREST & ANNUITY)

  5. C++ Basics: Operators

  6. 1.5 Compound Assignment Operators

COMMENTS

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

  2. Compound assignment operators in Java

    The following are all possible assignment operator in java: 1. += (compound addition assignment operator) 2. -= (compound subtraction assignment operator) 3. *= (compound multiplication assignment operator) 4. /= (compound division assignment operator) 5. %= (compound modulo assignment operator)

  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. The simplest is the "=" assignment operator: int x = 5; This statement declares a new variable x, assigns x the value of 5 and returns 5. Compound Assignment Operators are a shorter ...

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

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

  5. Compound assignment operators

    The ++ (increment) and −− (decrement) compound assignment operators are treated in a particular way. In fact, they are even simpler to understand. The ++ (increment) operator only adds one unit to the value of the numeric variable.. For example: the expression "x = x + 1" could be rewritten as "x++". The −− (decrement) operator only subtracts one unit from the value of the ...

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

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

  8. Lesson 24: Compound Assignment Operators

    Compound Assignment Operator: Add and equal to += Subtract and equal to-= Multiply and equal to *= Divide and equal to /= Even if you find yourself sticking to the way you originally learned, do not worry about it. I still find myself trying to avoid using compound assignment operators and the minor complications that can arise from using them.

  9. PDF Compound assignment operators

    Let d be an int-array and f(int) some function. In the first assignment below, f is called twice. In the second assignment, it is called only once. So the use of the compound operator is more efficient. d[f(5)]= d[f(5)] + 1; d[f(5)] += 1; There is even more of a difference between using += instead of = if one considers side effects. Evaluation of

  10. modern C++ by Xeverous

    05 - compound assignment. Compound assignment operators can be defined both as free functions and as member functions. Member functions are preferred because their implementation is simpler and since the operation has no symmetry (a += b is not the same as b += a for non-numeric abstractions, e.g. strings) there are no problems with inconsistent implicit convertion.

  11. Assignment operators

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

  12. Understanding Compound Assignment Operators in Java: Why They ...

    Many students assume that compound assignment operators like "+=" in Java are just shorthand for the corresponding simple assignment operators like "=". Howe...

  13. Chapter 9. Operators

    A compound assignment operator is written as op=, where op is one of several binary operators and = is the assignment operator. The following two expressions are equivalent: myvar op= value myvar = myvar op value. In other words, a compound assignment operator op= applies op to both operands and assigns the result to the first operand. Let's look at an example of using the plus operator ...

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

  15. Why there are no compound assignment operators for logical operators

    The hypothetical ||= operator does something fundamentally different from the other compound assignment operators. While the other operators are purely mathematical in nature, this one is different: it substitutes one value for another (in the context you described).

  16. Compound Assignment Operators in Java

    Dive into the world of Java programming with our immersive Codecademy series, "Mastering Java Programming." Whether you're a coding newbie or a seasoned deve...

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

  18. PDF Chapter 4: Expressions

    • There are nine other compound assignment operators, including the following: -= *= /= %= • All compound assignment operators work in much the same way: v += e adds v to e, storing the result in v v-= e subtracts e from v, storing the result in v v *= e multiplies v by e, storing the result in v v /= e divides v by e, storing the result in v

  19. Exploring Compound Assignment Operators in C

    Section 3: Advantages of Using Compound Assignment Operators. 1. Conciseness and Readability. By combining the operation and assignment, compound operators make code more concise and easier to read. 2. Improved Efficiency. They can lead to more efficient code execution, especially in situations where the same variable is used in multiple ...

  20. How are the operands ordered when using a compound assignment operator?

    1. When using C#, the compound assignment operators ( +=, *=, etc.) are automatically created from the corresponding binary operator: Compound assignment operators cannot be explicitly overloaded. However, when you overload a binary operator, the corresponding compound assignment operator, if any, is also implicitly overloaded.

  21. Assignment and Compound Assignment Operator

    Assignment and Compound Assignment Operator. Get introduced to the functionality of the assignment and the compound assignment operator. We'll cover the following. Assignment operator. Example program.

  22. Assignment operators

    Assignment operators. An assignment expression stores a value in the object designated by the left operand. There are two types of assignment operators: Simple assignment operator =. Compound assignment operators. The left operand in all assignment expressions must be a modifiable lvalue. The type of the expression is the type of the left operand.

  23. Resolving conversion warnings with compound assignment operators

    10. At our company we have a policy to compile with -Wconversion which produces some conversion warnings. While I do agree this extra checking prevents bugs, it is annoying to see warnings on shorthand operators such as in the following case: Now this can be solved by rewriting it as byte = (uint8_t)(byte+8) which in turn reduces code readability.