This browser is no longer supported.

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

C Compound Assignment

The compound-assignment operators combine the simple-assignment operator with another binary operator. Compound-assignment operators perform the operation specified by the additional operator, then assign the result to the left operand. For example, a compound-assignment expression such as

expression1 += expression2

can be understood as

expression1 = expression1 + expression2

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.

The operands of a compound-assignment operator must be of integral or floating type. Each compound-assignment operator performs the conversions that the corresponding binary operator performs and restricts the types of its operands accordingly. The addition-assignment ( += ) and subtraction-assignment ( -= ) operators can also have a left operand of pointer type, in which case the right-hand operand must be of integral type. The result of a compound-assignment operation has the value and type of the left operand.

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.

C Assignment Operators

Submit and view feedback for

Additional resources

Related Articles

Compound assignment operators in Java

Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand. The following are all possible assignment operator in java:

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:

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

This article is contributed by Bishal Kumar Dubey . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Please Login to comment...

New Course Launch!

Improve your Coding Skills with Practice

Start your coding journey now.

Compound-Assignment Operators

Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation on the two operands before assigning the result to the first operand.

Compound-Assignment Operators 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:

compound assignment operators

compound assignment operators

By clicking “Accept All Cookies”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts.

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:

[ 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

[ edit ] See Also

Operator precedence

[ edit ] See also

Powered by MediaWiki

Related Tags

What are the compound assignment & identity operators in Python?

compound assignment operators

What are operators in Python?

Operators are special symbols in Python that carry out arithmetic or logical computations. The value that the operator operates on is called the operand. For example: 2+3 = 5 . Here, + is the operator that performs addition.

There are many operators in Python, some of them are:

Compound assignment operator

Identity operator.

However, in this shot, we will only be talking about the compound assignment operator and the identity operator.

The compound assignment operator performs the operation of the binary operator on both operands, and stores the result of that operation in the left operand (must be a modifiable value).

The above expression is equivalent to a = a+10 . In the same way, we can subtract, multiply, and divide a number.

The identity operator is used to compare objects

z returns False because x is not the same object as y.

v returns True because x is not the same object as y.

RELATED TAGS

CONTRIBUTOR

compound assignment operators

View all Courses

Learn in-demand tech skills in half the time

For Enterprise

For Individuals

For HR & Recruiting

For Bootcamps

Educative Learning

Educative Onboarding

Educative Skill Assessments

Educative Projects

Privacy Policy

Terms of Service

Business Terms of Service

Become an Author

Become an Affiliate

Become a Contributor

Educative Blog

Educative Sessions

Educative Answers

Frequently Asked Questions

GitHub Students Scholarship

Course Catalog

Early Access Courses

Earn Referral Credits

CodingInterview.com

Copyright © 2023 Educative, Inc. All rights reserved.

compound assignment operators

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.

../_images/time45.png

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.

The most common shortcut operator ++ , the plus-plus or increment operator, is used to add 1 to the current value; x++ is the same as x += 1 and the same as x = x + 1 . It is a shortcut that is used a lot in loops. If you’ve heard of the programming language C++, the ++ in C++ is an inside joke that C has been incremented or improved to create C++. The -- decrement operator is used to subtract 1 from the current value: y-- is the same as y = y - 1 . These are the only two double operators; this shortcut pattern does not exist with other operators. Run the following code to see these shortcut operators in action!

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.

On the exam you can use x++ or ++x to add one to the value of x . These two shortcuts only have different results if you assign the value of x to another variable as in int y = ++x; (where the value of x is incremented before y is set to it) or int y = x++; (where y is set to a copy of x’s value before x is incremented). The AP exam will never use a shortcut in an assignment statement, so you don’t need to worry about the difference between ++x or x++ .

exercise

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

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

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 (i.e., ++x) and inside other expressions (i.e., arr[x++]) is outside the scope of this course and the AP Exam.

DEV Community

DEV Community

Matheus Gomes 👨‍💻

Posted on Jan 5, 2020

Coalescing operator and Compound assignment operator in C#

Hello! Today i want to ask you this: Have you ever used a Null Coalescing operator or even a Compound assignment operator in C# ?

Until today i had never heard about this things, so i want to share with you what i learned about and how it can be applied to your code.

The problem

Let's say you want to give a given variable the value of null.

Now, if we want to print the value on the screen it will accuse the following error:

Let's see how to get around this...

The old way 👎

The old and 'commom way' to check this is using if else operators like this:

We see that in this case we cannot place a default value to x and y operators. So we display on screen when it is null.

The Null Coalescing operator way 👌

First, a null coalescing operator (??) is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null, otherwise, it returns the right operand.

So it's mainly used to simplify checking for null values and also assign a default value to a variable when the value is null.

Using our example:

This way i can make a default value on x and y when one of them is null. And so, we can print on screen!

But can it be better?

The Compound assignment operator way 😎

The Compound assignment operator (??=) was introduced on C# 8.0 and has made our job easier. It simply reduces what we have to write and has the same result.

Instead of writing double x = x ?? 0.0; We can just write double x ??= 0.0;

Simple, right?

Hope you enjoyed this post, it's simple but it's something worth sharing for me.

Thanks for your time!😊

Links: https://dzone.com/articles/nullable-types-and-null-coalescing-operator-in-c

https://dev.to/mpetrinidev/the-null-coalescing-operator-in-c-8-0-4ib4

https://docs.microsoft.com/pt-br/dotnet/csharp/language-reference/operators/null-coalescing-operator

Top comments (3)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

wakeupmh profile image

saint4eva profile image

Good article. Thank you.

arthurbarbero profile image

Awesome Dude, simple but unknown by most programmers

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

Here is a post you might want to check out:

Regex for lazy developers

regex for lazy devs

Sorry for the callout 😆

pbouillon profile image

Getting started with integration testing for your Minimal API

Pierre Bouillon - Jan 19

ivanitd profile image

7. Working Hours (Long Solution)

Ivan Ivanov - Jan 20

05. Journey

jesterxl profile image

Dutch Government's DigiD iOS App Code Snippet

Jesse Warden - Jan 19

Once suspended, matheusgomes062 will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, matheusgomes062 will be able to comment and publish posts again.

Once unpublished, all posts by matheusgomes062 will become hidden and only accessible to themselves.

If matheusgomes062 is not suspended, they can still re-publish their posts from their dashboard.

Once unpublished, this post will become invisible to the public and only accessible to Matheus Gomes 👨‍💻.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community safe. Here is what you can do to flag matheusgomes062:

matheusgomes062 consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy.

Unflagging matheusgomes062 will restore default visibility to their posts.

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Now that we've talked about operators. Let's talk about something called the compound assignment operator and I'm going make one little change here in case you're wondering if you ever want to have your console take up the entire window you come up to the top right-hand side here you can undock it into a separate window and you can see that it takes up the entire window.

large

So just a little bit more room now.

Additionally, I have one other thing I'm going to show you in the show notes. I'm going to give you access to this entire set of assignment operators but we'll go through a few examples here. I'm going to use the entire window just to make it a little bit easier to see.

Let's talk about what assignment is. Now we've been using assignment ever since we started writing javascript code. You're probably pretty used to it. Assignment is saying something like var name and then setting up a name

And that is assignment the equals represents assignment.

Now javascript gives us the ability to have the regular assignment but also to have that assignment perform tasks. So for example say that you want to add items up so say that we want to add up a total set of grades to see the total number of scores. I can say var sum and assign it equal to zero.

And now let's create some grades.

I'm going to say var gradeOne = 100.

and then var gradeTwo = 80.

Now with both of these items in place say that we wanted to add these if you wanted to just add both of them together you definitely could do something like sum = (gradeOne + gradeTwo); and that would work.

However, one thing I want to show you is, there are many times where you don't have gradeOne or gradeTwo in a variable. You may have those stored in a database and then you're going to loop through that full set of records. And so you need to be able to add them on the fly. And so that's what a compound assignment operator can do.

Let's use one of the more basic ones which is to have the addition assignment.

Now you can see that sum is equal to 100.

Then if I do

If we had 100 grades we could simply add them just like that.

Essentially what this is equal to is it's a shorthand for saying something like

sum = sum + whatever the next one is say, that we had a gradeThree, it would be the same as doing that. So it's performing assignment, but it also is performing an operation. That's the reason why it's called a compound assignment operator.

Now in addition to having the ability to sum items up, you could also do the same thing with the other operators. In fact literally, every one of the operators that we just went through you can use those in order to do this compound assignment. Say that you wanted to do multiplication you could do sum astrix equals and then gradeTwo and now you can see it equals fourteen thousand four hundred.

This is that was the exact same as doing sum = whatever the value of sum was times gradeTwo. That gives you the exact same type of process so that is how you can use the compound assignment operators. And if you reference the guide that is included in the show notes. You can see that we have them for each one of these from regular equals all the way through using exponents.

Then for right now don't worry about the bottom items. These are getting into much more advanced kinds of fields like bitwise operators and right and left shift assignments. So everything you need to focus on is actually right at the top for how we're going to be doing this. This is something that you will see in a javascript code. I wanted to include it, so when you see it you're not curious about exactly what's happening.

It's a great shorthand syntax for whenever you want to do assignment but also perform an operation at the same time.

devCamp does not support ancient browsers. Install a modern version for best experience.

IMAGES

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

    compound assignment operators

  2. PPT

    compound assignment operators

  3. PPT

    compound assignment operators

  4. Compound Assignment Operators Maze Activity.docx

    compound assignment operators

  5. What Is a Compound-Assignment Operator?

    compound assignment operators

  6. สอน Java เบื้องต้น ตอนที่ 5.2 Compound Assignment Operators http://share.olanlab.com/th/it/blog

    compound assignment operators

VIDEO

  1. Assignment problem |Introduction

  2. Math L 17 Examples of Operators

  3. Assignment Operators in C in Hindi

  4. Assignment operators in c

  5. Shorthand Assignment Operator on Arithmetic operators

  6. Miscellaneous

COMMENTS

  1. Why Are Organic Compounds Important?

    Organic compounds are important because they serve as the basis for all carbon-based life on Earth, create energy production in biological life, cause atmospheric depletion and release hydrocarbon energy.

  2. What Is the Difference Between an Element and a Compound?

    An element is made of only one kind of atom, while a compound contains the atoms of two or more elements. For example, gold is made of only one kind of atom, so it is an element, but water is a mix of hydrogen and oxygen, so it is a compoun...

  3. What Is a Compound-Assignment Operator?

    Compound assignment operators provide a shorter syntax to assign the results of the arithmetic and bitwise operators. Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They...

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

  5. C Compound Assignment

    The operands of a compound-assignment operator must be of integral or floating type. Each compound-assignment operator performs the conversions

  6. Compound assignment operators in Java

    Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator. They perform the operation

  7. What Is a Compound-Assignment Operator?

    Compound-assignment operators provide a shorter syntax for assigning the result of an arithmetic or bitwise operator.

  8. Assignment operators

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

  9. What are the compound assignment & identity operators in Python?

    The compound assignment operator performs the operation of the binary operator on both operands, and stores the result of that operation in the left operand (

  10. Compound Assignment Operators

    Compound Assignment Operators · fn main() { · let mut a = 2; · println!("a is {}", a); · a += 5; // Arithmetic addition and assignment, 2 + 5 = 7 · println!("1: a +=

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

  12. compound assignment operators · WebPlatform Docs

    compound assignment operators. Summary. The following table lists JavaScript compound assignment operators. Syntax. Assignment Operators. Operator, Symbol

  13. Coalescing operator and Compound assignment operator in C#

    The Compound assignment operator (??=) was introduced on C# 8.0 and has made our job easier. It simply reduces what we have to write and has the

  14. Guide to Compound Assignment Operators in JavaScript

    Now that we've talked about operators. Let's talk about something called the compound assignment operator and I'm going make one little change here in case