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

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

example of compound assignment

Termos de uso

Política de Privacidade

example of compound assignment

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

cppreference.com

Assignment operators.

Assignment operators modify the value of the object.

[ edit ] Definitions

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

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

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

[ edit ] Assignment operator syntax

The assignment expressions have the form

  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

[ edit ] Built-in simple assignment operator

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

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

[ edit ] Assignment from an expression

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

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

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

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

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

[ edit ] Built-in compound assignment operator

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

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

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

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

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

[ edit ] Example

Possible output:

[ edit ] Defect reports

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

[ edit ] See also

Operator precedence

Operator overloading

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 25 January 2024, at 22:41.
  • This page has been accessed 410,142 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

example of compound assignment

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

Time estimate: 45 min.

1.5. Compound Assignment Operators ¶

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

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

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

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

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

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.

Using Compound Assignment Operators in C: A Beginner's Guide

An assignment operator is used for assigning a value to a variable. The most common assignment operator is = (equal). The left side operand of the assignment operator is a variable and 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 variable on the left side otherwise the compiler will raise an error.

The code is a C program that demonstrates the use of compound assignment operators in C. Here is an explanation of each line of the code:

  • int a=10,b=5; declares two variables a and b of type int and assigns them the values 10 and 5 respectively.
  • a+=b; is the compound assignment operator +=, it performs a+b and assigns the value to a. It is equivalent to a=a+b.
  • printf("A : %d",a); prints the value of a which is 15, this is the result after using += operator.
  • a-=10; is the compound assignment operator -=, it performs a-10 and assigns the value to a. It is equivalent to a=a-10.
  • printf("\nA : %d",a); prints the value of a which is 5, this is the result after using -= operator.
  • return 0; The return 0; statement is used to indicate that the main function has completed successfully. The value 0 is returned as the exit status of the program, which indicates a successful execution.

When you run this code, it will perform the compound assignment operation on variables and print the results in the console.

Source Code

List of programs.

  • C Introduction
  • Hello World
  • Basic Addition
  • Data Types in C
  • Variables and Literals in C
  • Arithmetic Operator in C
  • Example for Arithmetic Operator in C
  • Assignment Operators in C Program
  • Relational Operators in C Program
  • Logical Operators in C Program
  • Increment and Decrement Operators in C Program
  • Bitwise Operators in C Program
  • if Statement in C Program
  • if else Statement in C Program
  • else if Statement in C Program
  • Nested if Statement in C Program
  • Switch Statement in C Program
  • Conditional Operator Statement in C Program
  • School Management in C Program
  • Library Management in C Program
  • Find the given number is odd or even in C Program
  • Check the given number is vowels or not in C Program
  • Check the given number is Armstrong or not in C Program
  • Hotel Management in C Program
  • Goto Statement in C Program
  • Hotel Management using goto in C Program
  • While Loop in C Program
  • Do while Loop in C Program
  • For Loop in C Program
  • Nested For Loop in C Program
  • Break and Continue Statement in C Program
  • ASCII Values in C Program
  • Single Dimensional Array in C Program
  • 2D Array in C Program
  • String Function in C Program
  • Math Function in C Program
  • Function in C Program
  • No Return Without Argument Function in C Program
  • No Return With Argument Function in C Program
  • Return Without Argument Function in C Program
  • Return With Argument Function in C Program
  • Recursion Function in C Program
  • Call by Reference Function in C Program
  • Local Variable in C Program
  • Global Variable in C Program
  • Static Variable in C Program
  • Enumeration or enum in C Program
  • Single pointer in C Program
  • Double & Triple pointer in C Program
  • Pointer Arithmetic in C Program
  • Pointer Handle Array Values in C Program
  • Void * Pointer in C Program
  • Malloc Function in C Program
  • Calloc Function in C Program
  • Realloc Function in C Program
  • Free Function in C Program
  • Dangling Pointer in C Program
  • Using Const in Pointer in C Program
  • Structure in C Program
  • Local and Global Structure in C Program
  • Typedef in C Program
  • Initializing & Accessing the Structure Members in C Program
  • Access members of structure using pointer in C Program
  • Structure as function arguments in C Program
  • Array of Objects Structure in C Program
  • Union in C Program
  • Shop Management using Structure and Union in C Program
  • Input and output functions in C Program
  • Preprocessor Directives in C Program
  • Read File in C Program
  • Write File in C Program
  • Multiplication tables in C Program
  • Total no of even and odd numbers in an array in C Program
  • Count Alphabets Digits and Special Characters in a String in C Program
  • Convert string to uppercase in C Program
  • Convert string to lowercase in C Program
  • Display Fibonacci Sequence in C Program
  • Greatest of n numbers in an array in C Program

Sample Programs

Switch case in c.

  • Present Elevator Position
  • Check Vowel or Consonent
  • Hotel Management using Swtich Case

Conditional Operators in C

  • Find Greatest Number
  • Check Find Smallest Number
  • Check Number Equal or Not
  • Check Char. Vowel or Consonent
  • Check Character Capital or Small

Goto Statement in C

  • Consecutive Numbers
  • Print Text Using Goto
  • Print Odd Numbers
  • Printing Tables
  • Printing Sum of Values
  • Printing Reverse Table
  • Print Factorial in C

While Loop Example Programs

  • Print numbers using While Loop
  • Armstrong Number using While Loop
  • Print Odd and Even numbers
  • Print Positive and Negative numbers
  • Print Prime or Composite Number Upto Limit
  • Print Prime or Composite Number
  • Reverse table using While Loop
  • Print table using While Loop
  • Covert Decimal to Binary using While Loop

Looping Statements in C

For loop example programs.

  • Print Value upto limit
  • Print Number upto limit
  • Armstrong Number using For Loop
  • Square Pattern using For Loop
  • Flag Pattern using For Loop
  • Diamond Pattern using For Loop
  • Triangle Facing Downward using For Loop
  • Triangle Facing upside using For Loop
  • Right Angle Triangle facing left
  • Right Angle Triangle facing right
  • Reverse Number using For Loop
  • Prime Number using For Loop
  • Print Number divisible by 7
  • Print tables using For Loop
  • Reverse tables using For Loop
  • Separate odd and even numbers
  • Check prime or composite number
  • Separate positive and negative number
  • For Loop Patterns
  • Square Pattern Outline using For Loop
  • Triangle Outline Pattern
  • Diamond Pattern Outline

Array Examples in C

One dimensional array.

  • Add Elements to the Array
  • Arrange array elements in Ascending
  • Arrange array elements in Descending
  • Insert an element using Array
  • Update an element using Array
  • Delete an element using Array
  • Interchange an element using Array
  • Reverse an element using Array
  • Odd or Even Number using Array
  • Positive and Negative Numbers using Array
  • Armstrong Number 100 to 999
  • Greatest Number using Array
  • Smallest Number using Array
  • Print values divisible by 7 using Array
  • Convert binary to decimal using Array
  • Convert decimal to binary using Array
  • Convert decimal to octal using Array

Two Dimensional Array in C

  • Print Two Dimensional Array
  • Array Addition in Two-Dimenional Array
  • Array Subtraction in Two-Dimensional Array
  • Array Multiplication using Array
  • Lower Triangular Matrix using Array
  • Upper Triangluar Matrix using Array
  • Print Unit Matrix using Array
  • Check and Print Unit Matrix

String Example Programs in C

  • Print text using String
  • String Example
  • String Comparison in C
  • String Concatenation in C
  • String Copy Example in C
  • Convert Uppercase to Lowercase
  • Remove Duplicate String
  • Reverse text using String
  • Toggle Case using String
  • Conver text into Capital or Small
  • Convert Lowercase to Uppercase
  • Convert text into Ascending Order using
  • Capitalising the first letter
  • Check given strings Equal or Not
  • Copy String using Predefined Function
  • String Length using Predefined Function
  • String Length without Predefined Function
  • Uppercase to Lowercase using Predefined Function
  • Check Palindrome or Not

Functions Example Programs in C

  • Addition using return type and arguments
  • Print marks using return type & arguments
  • Function with no return and with arguments in c
  • Print tables without arguments

Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions

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

  • Read Tutorial
  • Watch Guide Video
  • Complete the Exercise

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

large

So just a little bit more room now.

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

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

And that is assignment the equals represents assignment.

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

And now let's create some grades.

I'm going to say var gradeOne = 100.

and then var gradeTwo = 80.

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

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

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

Now you can see that sum is equal to 100.

Then if I do

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

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

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

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

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

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

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

  • Documentation for Compound Assignment Operators
  • Source code

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

example of compound assignment

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

Advertisement

+= operator

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

Example with += operator

-= operator.

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

Example with -= operator

*= operator.

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

Example with *= operator

/= operator.

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

Example with /= operator

Please share this article -.

Facebook

Please Subscribe

Decodejava Facebook Page

Notifications

Please check our latest addition C#, PYTHON and DJANGO

Trending Articles on Technical and Non Technical topics

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

Compound Assignment Operators in C++

The compound assignment operators are specified in the form e1 op= e2, where e1 is a modifiable l-value not of const type and e2 is one of the following −

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

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

The following are the compound assignment operators in C++ −

Let's have a look at an example using some of these operators −

This will give the output −

Note that Compound assignment to an enumerated type generates an error message. If the left operand is of a pointer type, the right operand must be of a pointer type or it must be a constant expression that evaluates to 0. If the left operand is of an integral type, the right operand must not be of a pointer type.

Govinda Sai

Related Articles

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

Kickstart Your Career

Get certified by completing the course

This browser is no longer supported.

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

Assignment operators (C# reference)

  • 11 contributors

The assignment operator = assigns the value of its right-hand operand to a variable, a property , or an indexer element given by its left-hand operand. The result of an assignment expression is the value assigned to the left-hand operand. The type of the right-hand operand must be the same as the type of the left-hand operand or implicitly convertible to it.

The assignment operator = is right-associative, that is, an expression of the form

is evaluated as

The following example demonstrates the usage of the assignment operator with a local variable, a property, and an indexer element as its left-hand operand:

The left-hand operand of an assignment receives the value of the right-hand operand. When the operands are of value types , assignment copies the contents of the right-hand operand. When the operands are of reference types , assignment copies the reference to the object.

This is called value assignment : the value is assigned.

ref assignment

Ref assignment = ref makes its left-hand operand an alias to the right-hand operand, as the following example demonstrates:

In the preceding example, the local reference variable arrayElement is initialized as an alias to the first array element. Then, it's ref reassigned to refer to the last array element. As it's an alias, when you update its value with an ordinary assignment operator = , the corresponding array element is also updated.

The left-hand operand of ref assignment can be a local reference variable , a ref field , and a ref , out , or in method parameter. Both operands must be of the same type.

Compound assignment

For a binary operator op , a compound assignment expression of the form

is equivalent to

except that x is only evaluated once.

Compound assignment is supported by arithmetic , Boolean logical , and bitwise logical and shift operators.

Null-coalescing assignment

You can use the null-coalescing assignment operator ??= to assign the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null . For more information, see the ?? and ??= operators article.

Operator overloadability

A user-defined type can't overload the assignment operator. However, a user-defined type can define an implicit conversion to another type. That way, the value of a user-defined type can be assigned to a variable, a property, or an indexer element of another type. For more information, see User-defined conversion operators .

A user-defined type can't explicitly overload a compound assignment operator. However, if a user-defined type overloads a binary operator op , the op= operator, if it exists, is also implicitly overloaded.

C# language specification

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

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

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
  • Compound Statements in C++
  • Rethrowing an Exception in C++
  • Variable Shadowing in C++
  • Condition Variables in C++ Multithreading
  • C++23 <print> Header
  • Literals In C++
  • How to Define Constants in C++?
  • C++ Variable Templates
  • Introduction to GUI Programming in C++
  • Concurrency in C++
  • Hybrid Inheritance In C++
  • Dereference Pointer in C
  • shared_ptr in C++
  • Nested Inline Namespaces In C++20
  • C++20 std::basic_syncbuf
  • std::shared_mutex in C++
  • Partial Template Specialization in C++
  • Pass By Reference In C
  • Address Operator & in C

Assignment Operators In C++

In C++, the assignment operator forms the backbone of many algorithms and computational processes by performing a simple operation like assigning a value to a variable. It is denoted by equal sign ( = ) and provides one of the most basic operations in any programming language that is used to assign some value to the variables in C++ or in other words, it is used to store some kind of information.

The right-hand side value will be assigned to the variable on the left-hand side. The variable and the value should be of the same data type.

The value can be a literal or another variable of the same data type.

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 ( += )
  • Subtraction Assignment Operator ( -= )
  • Multiplication Assignment Operator ( *= )
  • Division Assignment Operator ( /= )
  • Modulus Assignment Operator ( %= )
  • Bitwise AND Assignment Operator ( &= )
  • Bitwise OR Assignment Operator ( |= )
  • Bitwise XOR Assignment Operator ( ^= )
  • Left Shift Assignment Operator ( <<= )
  • Right Shift Assignment Operator ( >>= )

Lets see each of them in detail.

1. Addition Assignment Operator (+=)

In C++, the addition assignment operator (+=) combines the addition operation with the variable assignment allowing you to increment the value of variable by a specified expression in a concise and efficient way.

This above expression is equivalent to the expression:

2. Subtraction Assignment Operator (-=)

The subtraction assignment operator (-=) in C++ enables you to update the value of the variable by subtracting another value from it. This operator is especially useful when you need to perform subtraction and store the result back in the same variable.

3. Multiplication Assignment Operator (*=)

In C++, the multiplication assignment operator (*=) is used to update the value of the variable by multiplying it with another value.

4. Division Assignment Operator (/=)

The division assignment operator divides the variable on the left by the value on the right and assigns the result to the variable on the left.

5. Modulus Assignment Operator (%=)

The modulus assignment operator calculates the remainder when the variable on the left is divided by the value or variable on the right and assigns the result to the variable on the left.

6. Bitwise AND Assignment Operator (&=)

This operator performs a bitwise AND between the variable on the left and the value on the right and assigns the result to the variable on the left.

7. Bitwise OR Assignment Operator (|=)

The bitwise OR assignment operator performs a bitwise OR between the variable on the left and the value or variable on the right and assigns the result to the variable on the left.

8. Bitwise XOR Assignment Operator (^=)

The bitwise XOR assignment operator performs a bitwise XOR between the variable on the left and the value or variable on the right and assigns the result to the variable on the left.

9. Left Shift Assignment Operator (<<=)

The left shift assignment operator shifts the bits of the variable on the left to left by the number of positions specified on the right and assigns the result to the variable on the left.

10. Right Shift Assignment Operator (>>=)

The right shift assignment operator shifts the bits of the variable on the left to the right by a number of positions specified on the right and assigns the result to the variable on the left.

Also, it is important to note that all of the above operators can be overloaded for custom operations with user-defined data types to perform the operations we want.

Please Login to comment...

Similar reads.

  • Geeks Premier League 2023
  • Geeks Premier League

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Approach English Grammar CBSE ICSE ISE WBBSE

Compound Complex Sentence examples with answers

example of compound assignment

Looking for compound-complex sentence examples with answers? Explore this comprehensive guide filled with diverse examples to enhance your understanding.

Welcome to our in-depth guide on compound-complex sentences. In this article, we’ll dive into the world of sentence structures, focusing on 100 compound complex sentence examples with answers. 

Understanding Compound Complex Sentence Examples

Before we delve into the examples, let’s clarify what a compound-complex sentence is .

A compound-complex sentence combines elements of both compound and complex sentences. 

It consists of two or more independent clauses ( compound) and one or more dependent clauses ( complex ). These sentences offer a rich and varied way to express ideas, making your writing more engaging and sophisticated.

The Structure of Compound Complex Sentence Examples

You need to understand their structure to create effective compound complex sentence examples with independent and dependent clauses. In essence, they consist of:

  • Independent Clause: This part of the sentence can stand alone as a complete thought.
  • Dependent Clause : This part cannot stand alone and relies on the independent clause for meaning.

Examples of Independent Clauses

In this section, we’ll explore some examples of independent clauses. These are the building blocks of compound-complex sentences:

  • She walked to the store.
  • The sun was shining brightly.
  • They played a beautiful melody.

Examples of Dependent Clauses

Now, let’s look at examples of dependent clauses, which complement independent clauses:

  • After she finished her work, she went for a walk.
  • Because it was raining, they decided to stay indoors.
  • Although he studied hard, he didn’t perform well in the exam.

People also ask

Creating Compound Complex Sentence for Examples

To craft compound complex sentence examples independent and dependent clause effectively, you need to combine independent and dependent clauses. Here are some examples :

1. Although it was raining, she decided to go for a walk because she needed some fresh air.

2. He studied hard, so he was well-prepared, but he still felt nervous.

3. Although it rained heavily last night, we still managed to have a great picnic in the park because we had brought along a large canopy for shelter.

4. While he studied diligently for the exam, his friends spent the evening watching movies, and they regretted it later when they received their scores.

5. Even though the concert tickets were expensive, they decided to splurge on them because it was their favorite band performing.

6. After the meeting, he rushed to catch his train, but he missed it because of heavy traffic, causing him to arrive late for the conference.

7. Despite her busy schedule, she managed to complete all her assignments, and her dedication earned her top grades in every subject.

These examples showcase how independent and dependent clauses can be combined to create c ompound complex sentences that add depth and detail to your writing.

Analysis of the Compound Complex Sentence Examples

1. Although it rained heavily last night, we still managed to have a great picnic in the park because we had brought along a large canopy for shelter.

  • Independent clause: “We still managed to have a great picnic in the park.”
  • Dependent clause: “Although it rained heavily last night” and “because we had brought along a large canopy for shelter.”

2. After finishing her homework, she decided to go for a jog, but she changed her mind when she realized it was pouring outside.

  • Independent clause: “She decided to go for a jog” and “she changed her mind.”
  • Dependent clause: “After finishing her homework” and “when she realized it was pouring outside.”

3. While he studied diligently for the exam, his friends spent the evening watching movies, and they regretted it later when they received their scores.

  • Independent clause: “His friends spent the evening watching movies” and “they regretted it later when they received their scores.”
  • Dependent clause: “While he studied diligently for the exam.”

4. Because the traffic was unbearable, she left for work an hour earlier than usual, and she reached the office feeling more relaxed than ever.

  • Independent clause: “She left for work an hour earlier than usual” and “she reached the office feeling more relaxed than ever.”
  • Dependent clause: “Because the traffic was unbearable.”
  • Independent clause: “They decided to splurge on them” and “it was their favorite band performing.”
  • Dependent clause: “Even though the concert tickets were expensive.”

6. While I was baking a cake for the party, my brother was decorating the house with colorful balloons, and our guests were bringing gifts and snacks.

  • Independent clause: “My brother was decorating the house with colorful balloons” and “our guests were bringing gifts and snacks.”
  • Dependent clause: “While I was baking a cake for the party.”

7. Although the storm was approaching, they decided to continue their hike because they were determined to reach the summit before sunset.

  • Independent clause: “They decided to continue their hike” and “they were determined to reach the summit before sunset.”
  • Dependent clause: “Although the storm was approaching.”

8. After the meeting, he rushed to catch his train, but he missed it because of heavy traffic, causing him to arrive late for the conference.

  • Independent clause: “He missed it because of heavy traffic” and “causing him to arrive late for the conference.”
  • Dependent clause: “After the meeting.”

9. While the chef prepared the main course, the sous chef and pastry chef collaborated on creating exquisite desserts that would delight the diners.

  • Independent clause: “The sous chef and pastry chef collaborated on creating exquisite desserts that would delight the diners.”
  • Dependent clause: “While the chef prepared the main course.”

10. Despite her busy schedule, she managed to complete all her assignments, and her dedication earned her top grades in every subject.

  • Independent clause: “She managed to complete all her assignments” and “her dedication earned her top grades in every subject.”
  • Dependent clause: “Despite her busy schedule.”

11. Because the museum was hosting a special exhibit, they decided to visit it during the weekend, and they were amazed by the stunning art pieces on display.

  • Independent clause: “They decided to visit it during the weekend” and “they were amazed by the stunning art pieces on display.”
  • Dependent clause: “Because the museum was hosting a special exhibit.”

12. While the orchestra played a mesmerizing symphony, the dancers gracefully moved to the music, creating a breathtaking performance that left the audience in awe.

  • Independent clause: “The dancers gracefully moved to the music, creating a breathtaking performance that left the audience in awe.”
  • Dependent clause: “While the orchestra played a mesmerizing symphony.”

These examples illustrate how compound complex sentences can convey intricate relationships between ideas, making your writing more engaging and informative.

20 Compound Complex Sentence Examples with Answers

While I was studying for my exam, my brother played his guitar.

This sentence contains two independent clauses: “While I was studying for my exam” and “my brother played his guitar.” The dependent clause, “While I was studying for my exam,” adds context to the action in the second clause.

Although it rained heavily, the picnic went on as planned.

Here, “Although it rained heavily” is the dependent clause, and “the picnic went on as planned” is the independent clause. The dependent clause provides contrasting information.

She enjoyed the movie, but she found the ending disappointing.

This compound-complex sentence combines two independent clauses, “She enjoyed the movie” and “she found the ending disappointing,” using the coordinating conjunction “but.”

Because I was running late, I missed the bus, so I had to take a taxi.

In this sentence, you have two independent clauses, “I missed the bus” and “I had to take a taxi,” connected by the coordinating conjunction “so.” The dependent clause, “Because I was running late,” explains the reason for the actions.

After finishing his work, John decided to go for a walk.

“After finishing his work” is the dependent clause, and “John decided to go for a walk” is the independent clause. This example showcases the use of subordinating conjunctions to link the clauses.

Maria couldn’t attend the party since she had a prior commitment.

Here, “since she had a prior commitment” functions as the dependent clause, while “Maria couldn’t attend the party” serves as the independent clause. The sentence explains the reason for Maria’s absence.

Although the restaurant was busy, the service was impeccable, and the food was delicious.

This compound-complex sentence features three independent clauses linked by the coordinating conjunction “and.” It highlights the balance and contrast between different elements.

As I was about to leave, my friend called and invited me to stay.

“As I was about to leave” is the dependent clause, and “my friend called and invited me to stay” is the independent clause. The sentence portrays a change in plans.

While she was driving to work, she noticed a beautiful sunrise.

This sentence contains two independent clauses, “she noticed a beautiful sunrise” and “While she was driving to work,” joined by the subordinating conjunction “While.”

Despite her busy schedule, Lisa always finds time to exercise.

“Despite her busy schedule” is the dependent clause, and “Lisa always finds time to exercise” is the independent clause. The sentence highlights Lisa’s commitment to staying active.

Even though it was raining cats and dogs, Sarah decided to go for a run, and she returned completely soaked.

In this sentence, “Even though it was raining cats and dogs” serves as the dependent clause, while “Sarah decided to go for a run” and “she returned completely soaked” are independent clauses. It illustrates Sarah’s determination despite adverse weather conditions.

As the sun set, the campers gathered around the campfire, and they shared stories of their adventures.

Here, “As the sun set” is the dependent clause, and “the campers gathered around the campfire” and “they shared stories of their adventures” are independent clauses. The sentence sets a tranquil scene and highlights the camaraderie among campers.

Although the book was lengthy, she finished it in just two days, and she couldn’t put it down.

“Although the book was lengthy” functions as the dependent clause, while “she finished it in just two days” and “she couldn’t put it down” are independent clauses. This example shows the reader’s enthusiasm for the book.

Despite facing numerous challenges, the team persevered, and they ultimately achieved their goal.

“Despite facing numerous challenges” is the dependent clause, and “the team persevered” and “they ultimately achieved their goal” are independent clauses. It demonstrates the team’s determination and success in the face of adversity.

While she was on vacation, Emily discovered a hidden gem of a restaurant, and she made it her mission to visit it every day.

This sentence contains two independent clauses, “Emily discovered a hidden gem of a restaurant” and “she made it her mission to visit it every day,” connected by the subordinating conjunction “While.”

Although he had never been to a cooking class, Tom decided to enter the chili cook-off competition, and he ended up winning first place.

In this example, “Although he had never been to a cooking class” serves as the dependent clause, while “Tom decided to enter the chili cook-off competition” and “he ended up winning first place” are independent clauses. It highlights Tom’s unexpected success.

As the clock struck midnight, the New Year’s fireworks lit up the sky, and people cheered in celebration.

“As the clock struck midnight” is the dependent clause, and “the New Year’s fireworks lit up the sky” and “people cheered in celebration” are independent clauses. This sentence captures the excitement of a New Year’s Eve celebration.

Despite being a novice, he tackled the advanced math problems with confidence, and he solved them correctly.

Here, “Despite being a novice” functions as the dependent clause, while “he tackled the advanced math problems with confidence” and “he solved them correctly” are independent clauses. It showcases the individual’s determination to excel in math.

While the storm raged outside, they cozied up by the fireplace, and they shared stories from their childhood.

This compound complex sentence features two independent clauses, “they cozied up by the fireplace” and “they shared stories from their childhood,” connected by the subordinating conjunction “While.” It paints a warm and comforting picture.

Although he was exhausted from work, he stayed up late to finish reading the thrilling novel, and he couldn’t wait to discuss it with his friends.

In this sentence, “Although he was exhausted from work” is the dependent clause, while “he stayed up late to finish reading the thrilling novel” and “he couldn’t wait to discuss it with his friends” are independent clauses. It reflects the reader’s enthusiasm for the book.

Punctuation Rules with Compound Complex Sentence examples

Punctuation plays a crucial role in compound complex sentences. Learn how to use commas, semicolons, and conjunctions correctly to ensure your sentences are clear and concise.

While the rain poured down , I stayed indoors, but my brother insisted on playing soccer in the mud.

This sentence uses the subordinating conjunction “While” to introduce the dependent clause “the rain poured down.” It includes two independent clauses, “I stayed indoors” and “my brother insisted on playing soccer in the mud,” separated by a comma and the coordinating conjunction “but.”

Although she had never baked a cake before , she decided to try, and it turned out delicious.

Here, “Although” introduces the dependent clause “she had never baked a cake before.” The sentence combines two independent clauses, “she decided to try” and “it turned out delicious,” using a comma and the coordinating conjunction “and.”

After he finished his homework, he went to the park , where he met his friends.

This compound complex sentence features three clauses. “After” introduces the dependent clause “he finished his homework,” and “where” introduces the relative clause “where he met his friends.” The two independent clauses, “he went to the park” and “he met his friends,” are connected by a comma.

Because it was her birthday, she treated herself to a spa day, and she felt completely relaxed afterward.

In this sentence, “Because” introduces the dependent clause “it was her birthday.” It combines two independent clauses, “she treated herself to a spa day” and “she felt completely relaxed afterward,” using a comma and the coordinating conjunction “and.”

While we waited for the bus, it started to rain, so we decided to take a taxi instead.

“While” introduces the dependent clause “we waited for the bus.” The sentence contains two independent clauses, “it started to rain” and “we decided to take a taxi instead,” separated by a comma and the coordinating conjunction “so.”

Although he had never been to Paris, he dreamed of visiting the Eiffel Tower, which he had seen in pictures.

Here, “Although” introduces the dependent clause “he had never been to Paris.” “Which” introduces the relative clause “which he had seen in pictures.” The two independent clauses, “he dreamed of visiting the Eiffel Tower” and “he had seen in pictures,” are connected by a comma.

As the sun set, the sky turned shades of orange and pink, and the stars began to twinkle.

“As” introduces the dependent clause “the sun set.” The sentence combines two independent clauses, “the sky turned shades of orange and pink” and “the stars began to twinkle,” using a comma and the coordinating conjunction “and.”

Although it was a long journey, they enjoyed the scenic route, and they made wonderful memories.

In this sentence, “Although” introduces the dependent clause “it was a long journey.” It includes two independent clauses, “they enjoyed the scenic route” and “they made wonderful memories,” separated by a comma and the coordinating conjunction “and.”

After she finished her painting, she carefully cleaned her brushes, and she stored them in a neat case.

“After” introduces the dependent clause “she finished her painting.” The sentence combines two independent clauses, “she carefully cleaned her brushes” and “she stored them in a neat case,” using a comma and the coordinating conjunction “and.”

Despite t he challenges they faced, they never gave up, for they believed in their mission.

Here, “Despite” introduces the dependent clause “the challenges they faced.” The sentence includes two independent clauses, “they never gave up” and “they believed in their mission,” separated by a comma and the coordinating conjunction “for.”

These examples illustrate how to use punctuation rules effectively in compound complex sentences to convey complex ideas clearly and accurately.

Frequently Asked Questions (FAQs)

1. what is a compound complex sentence .

A compound complex sentence is a sentence structure that combines elements of both compound and complex sentences. It includes two or more independent clauses and one or more dependent clauses.

2. Why should I use compound complex sentences in my writing? 

Compound complex sentences add depth and variety to your writing. They allow you to express complex ideas and relationships between clauses, making your writing more engaging.

3. Are there any specific rules for punctuating compound complex sentences? 

Yes, compound complex sentences require proper punctuation. Use commas, semicolons, and conjunctions to connect clauses appropriately.

4. Can you provide tips for using compound complex sentences effectively? 

Certainly! To use compound complex sentences effectively, ensure that the clauses are related and contribute to the overall message. Use subordinating and coordinating conjunctions appropriately.

5. Is it possible to overuse compound complex sentences in writing? 

Yes, like any sentence structure, overusing compound complex sentences can make your writing overly complex. It’s essential to strike a balance and use them when they enhance clarity and meaning.

In this comprehensive guide, we’ve explored 100 compound complex sentence examples with answers. We’ve covered a wide range of scenarios and sentence structures to help you master this essential skill. Remember, using compound complex sentences can elevate your writing and convey your ideas more effectively. Practice is key, so don’t hesitate to experiment with different sentence structures in your writing.

Related posts:

Direct Indirect Speech Exercises Answers

IMAGES

  1. Answered: Pick out the compound assignment…

    example of compound assignment

  2. PPT

    example of compound assignment

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

    example of compound assignment

  4. SQL SERVER

    example of compound assignment

  5. PPT

    example of compound assignment

  6. PPT

    example of compound assignment

VIDEO

  1. Lecture 5 :Chapter2 Basic Element (Part4)

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

  3. GROUP ASSIGNMENT MAT112 (COMPOUND INTEREST & ANNUITY)

  4. 1.5 Compound Assignment Operators

  5. Compound Assignment Operators in C language

  6. ASSIGNMENT 1

COMMENTS

  1. What Is a Compound-Assignment Operator?

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

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

  3. 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. ... Explanation: In the above example, we are using compound assignment operator. Here we are assigning an int (b+1=20) value to ...

  4. Java Compound Operators

    For example, the following two multiplication statements are equivalent, meaning a and b will have the same value: int a = 3, b = 3, c = -2; a = a * c; // Simple assignment operator b *= c; // Compound assignment operator. It's important to note that the variable on the left-hand of a compound assignment operator must be already declared.

  5. Java Compound Assignment Operators (With Examples)

    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.

  6. Compound assignment operators

    Compound assignment operators represent the 5th category of programming operators and, in summary, provide a shorter way to perform some arithmetic operations. Just for example, see the code below. Note that, in line 2, the value assigned to variable x is 15. (10 + 5). Therefore, the command on line 3 prints the value 15 on the screen.

  7. PDF Compound assignment operators

    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. We note two important points: The expression is cast to the type of E1 before the assignment is made (the cast is in red above) E1 ...

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

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

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

  11. Using Compound Assignment Operators in C: A Beginner's Guide

    The code is a C program that demonstrates the use of compound assignment operators in C. Here is an explanation of each line of the code: int a=10,b=5; declares two variables a and b of type int and assigns them the values 10 and 5 respectively. a+=b; is the compound assignment operator +=, it performs a+b and assigns the value to a. It is equivalent to a=a+b.

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

  13. Guide to Compound Assignment Operators in JavaScript

    And so that's what a compound assignment operator can do. Let's use one of the more basic ones which is to have the addition assignment. sum += gradeOne; // 100. Now you can see that sum is equal to 100. Then if I do. sum += gradeTwo; // 180. If we had 100 grades we could simply add them just like that.

  14. C

    In all the compound assignment operators, the expression on the right side of = is always calculated first and then the compound assignment operator will start its functioning. Hence in the last code, statement i+=2*2; is equal to i=i+(2*2), which results in i=i+4, and finally it returns 6 to i. Example with += operator

  15. Compound Assignment Operators in C++

    The compound assignment operators are specified in the form e1 op= e2, where e1 is a modifiable l-value not of const type and e2 is one of the following −. The e1 op= e2 form behaves as e1 = e1 op e2, but e1 is evaluated only once. The following are the compound assignment operators in C++ −. Multiply the value of the first operand by the ...

  16. Assignment operators

    The left-hand operand of ref assignment can be a local reference variable, a ref field, and a ref, out, or in method parameter. Both operands must be of the same type. Compound assignment. For a binary operator op, a compound assignment expression of the form. x op= y is equivalent to. x = x op y except that x is only evaluated once.

  17. 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. ... Example. C++. #include <iostream> using namespace std; int main() { int x = 7 ...

  18. Compound assignment operators

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

  19. c

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

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

  21. Compound assignment statements

    In a compound assignment, any subscripts or locator expressions specified in the target variable are evaluated only once. If f is a function and X is an array, the following statements are not equivalent: X (f ()) += 1. is not equivalent to. X (f ()) = X (f ())+1. The function f is called only once.

  22. IBM Documentation

    IBM Documentation.

  23. Compound Complex Sentence examples with answers

    Analysis of the Compound Complex Sentence Examples. 1. Although it rained heavily last night, we still managed to have a great picnic in the park because we had brought along a large canopy for shelter. Independent clause: "We still managed to have a great picnic in the park.". Dependent clause: "Although it rained heavily last night ...