/ | ||||
(C++11) | ||||
(C++11) |
(C++11) | ||||
(C++20) | ||||
(C++20) |
(C++11) | ||||
expression |
pointer |
specifier | ||||
specifier (C++11) | ||||
specifier (C++11) |
(C++11) | ||||
(C++11) |
(C++11) | ||||
(C++11) |
General | ||||
(C++11) | ||||
(C++26) | ||||
(C++11) | ||||
(C++11) |
-expression | ||||
-expression | ||||
-expression |
(C++11) | ||||
(C++11) | ||||
(C++17) | ||||
(C++20) |
Assignment operators modify the value of the object.
Operator name | Syntax | Prototype examples (for class T) | ||
---|---|---|---|---|
Inside class definition | Outside class definition | |||
simple assignment | Yes | T& T::operator =(const T2& b); | ||
addition assignment | Yes | T& T::operator +=(const T2& b); | T& operator +=(T& a, const T2& b); | |
subtraction assignment | Yes | T& T::operator -=(const T2& b); | T& operator -=(T& a, const T2& b); | |
multiplication assignment | Yes | T& T::operator *=(const T2& b); | T& operator *=(T& a, const T2& b); | |
division assignment | Yes | T& T::operator /=(const T2& b); | T& operator /=(T& a, const T2& b); | |
remainder assignment | Yes | T& T::operator %=(const T2& b); | T& operator %=(T& a, const T2& b); | |
bitwise AND assignment | Yes | T& T::operator &=(const T2& b); | T& operator &=(T& a, const T2& b); | |
bitwise OR assignment | Yes | T& T::operator |=(const T2& b); | T& operator |=(T& a, const T2& b); | |
bitwise XOR assignment | Yes | T& T::operator ^=(const T2& b); | T& operator ^=(T& a, const T2& b); | |
bitwise left shift assignment | Yes | T& T::operator <<=(const T2& b); | T& operator <<=(T& a, const T2& b); | |
bitwise right shift assignment | Yes | T& T::operator >>=(const T2& b); | T& operator >>=(T& a, const T2& b); | |
this, and most also return *this so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including void). can be any type including . |
Definitions Assignment operator syntax Built-in simple assignment operator Assignment from an expression Assignment from a non-expression initializer clause Built-in compound assignment operator Example Defect reports See also |
Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .
replaces the contents of the object a with the contents of b, avoiding copying if possible (b may be modified). For class types, this is performed in a special member function, described in . | (since C++11) |
For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .
Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .
The assignment expressions have the form
target-expr new-value | (1) | ||||||||
target-expr op new-value | (2) | ||||||||
target-expr | - | the expression to be assigned to |
op | - | one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |= |
new-value | - | the expression (until C++11) (since C++11) to assign to the target |
If new-value is not an expression, the assignment expression will never match an overloaded compound assignment operator. | (since C++11) |
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.
If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.
If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).
If the type of target-expr is volatile-qualified, the assignment is deprecated, unless the (possibly parenthesized) assignment expression is a or an . | (since C++20) |
new-value is only allowed not to be an expression in following situations: is of a , and new-value is empty or has only one element. In this case, given an invented variable t declared and initialized as T t = new-value , the meaning of x = new-value is x = t. is of class type. In this case, new-value is passed as the argument to the assignment operator function selected by . <double> z; z = {1, 2}; // meaning z.operator=({1, 2}) z += {1, 2}; // meaning z.operator+=({1, 2}) int a, b; a = b = {1}; // meaning a = b = 1; a = {1} = b; // syntax error | (since C++11) |
In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:
& operator=(T*&, T*); | ||
volatile & operator=(T*volatile &, T*); | ||
For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:
operator=(T&, T); | ||
For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:
operator=(A1&, A2); | ||
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:
In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:
operator*=(A1&, A2); | ||
operator/=(A1&, A2); | ||
operator+=(A1&, A2); | ||
operator-=(A1&, A2); | ||
For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:
operator%=(I1&, I2); | ||
operator<<=(I1&, I2); | ||
operator>>=(I1&, I2); | ||
operator&=(I1&, I2); | ||
operator^=(I1&, I2); | ||
operator|=(I1&, I2); | ||
For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:
& operator+=(T*&, ); | ||
& operator-=(T*&, ); | ||
volatile & operator+=(T*volatile &, ); | ||
volatile & operator-=(T*volatile &, ); | ||
Possible output:
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
C++11 | for assignments to class type objects, the right operand could be an initializer list only when the assignment is defined by a user-defined assignment operator | removed user-defined assignment constraint | |
C++11 | E1 = {E2} was equivalent to E1 = T(E2) ( is the type of ), this introduced a C-style cast | it is equivalent to E1 = T{E2} | |
C++20 | compound assignment operators for volatile -qualified types were inconsistently deprecated | none of them is deprecated | |
C++11 | an assignment from a non-expression initializer clause to a scalar value would perform direct-list-initialization | performs copy-list- initialization instead | |
C++20 | bitwise compound assignment operators for volatile types were deprecated while being useful for some platforms | they are not deprecated |
Operator precedence
Operator overloading
Common operators | ||||||
---|---|---|---|---|---|---|
a = b | ++a | +a | !a | a == b | a[...] | function call |
a(...) | ||||||
comma | ||||||
a, b | ||||||
conditional | ||||||
a ? b : c | ||||||
Special operators | ||||||
converts one type to another related type |
for Assignment operators |
Advertisement
-= operator.
*= operator.
/= operator.
Please share this article -.
Please check our latest addition C#, PYTHON and DJANGO
Back to: C++ Tutorials For Beginners and Professionals
In this article, I am going to discuss Compound Assignment Operator in C++ with Examples. Please read our previous article where we discussed Programming Exercises in C++ . We have already created a few simple programs using formulas and expressions where we used use arithmetic operators. We have a lot of other operators to learn so slowly we’ll be learning about them. Now, we will learn about compound assignment operators.
Compound Assignment is there not only for arithmetic operators but it is there for other operators also. However, we will discuss compound assignment arithmetic operators later whenever we discuss those operators at that time, I will discuss the compound operators also.
These are related to arithmetic as well as other operators also. So let us understand what these are and when they are useful. We have listed the compound assignment operators:
You can see that the operators coming before the assignment. Usually, the expression or all the operators will be after the assignment but here it is coming before the assignment.
When it is useful let us see. For that I have taken one example here,
int x = 3, y = 15, z = 21;
int sum = 3;
We have some variables x, y, and the sum which are having some values. Now the first thing is we want to perform the addition between sum and a and store the result in sum itself. So let us see how we can do that.
We can write it as sum = sum + a;
This statement means we add sum and a, and store the result in sum. Now the sum becomes 6. These types of statements are commonly used in programming. Now we will see the same statement can be written using the Compound Assignment Operator. Let us see this.
sum = sum + a;
In the above expression, the sum is used on the right-hand side of the assignment as well as the left-hand side of the assignment. So, the same thing can be written as
So instead of writing sum 2 times, we can write it as above. Now, this is easily readable. For a beginner, it is not readable but when you are writing C++ programming you get used to it. Writing the above statement by using a compound assignment operator is faster than the previous method. Internally compiler will make it faster. So, this statement is faster.
Now we take another example: int x = 3, y = 4, z = 2; int p = 1;
In some program we have to perform many operations on a single variable, so at that time we can use compound assignment. p *= x; — (i) p *= y; — (ii) p -= x + y + z; — (iii)
Here In the 1 st statement, we are performing multiplication between p and x and then store the result in p itself. Here value of p will 1 * 3 = 3. When we execute the first statement, the value of p will 3.
Now the 2 nd statement, we are performing multiplication between p and y and store results in p. But here the value of p is 3 as evaluated from 1 st statement. Now the value of p will be 3 * 4 = 12. So, at this point, the p value will be 12.
In the 3 rd statement, we are performing subtraction between p and the result of the addition of x, y, and z. And store that in p. Here p = 12. So, at execution, it will be 12 – (3+4+2) = 3. Now p = 3
Here we modified ‘ p ’ with multiple values. So, in such situations, we use this type of operator. That is a compound assignment. It can be done for subtraction, multiplication, division, and all the other operators like bitwise operators. We will look at them in the coming articles. Let’s see the code part:
Compound assignment operator usually does the same thing that existing operators are doing but it gives more efficiency in compile time. To explain the compound assignment Operator let us take an example: I have a variable I want to repeat add another no to this variable. Currently, without a compound assignment operator, I am following this method. I am writing a pseudocode
int sum=0; Sum=sum+5; Sum=sum+8; Sum=sum+11; //here every time you are adding sum with other values and storing back it in sum only.
This has a disadvantage.
The Variable sum is evaluated in each instruction, which consumes more compile-time hence inefficient. To overcome this problem and also to increase program readability compound assignment operators or shorthand operators come into the picture. Now the same pseudo-code can be written as
int sum=0; Sum+=5; Sum+=8; Sum+=11; Let’s see how efficient it is by comparing the compile time for both.
Without shorthand operator/compound assignment operator Compile-time is 4.119 seconds
With shorthand operator/compound assignment operator Compile-time is only 1.788 seconds.
Note : Assignment and Compound Assignment Operators have the least precedence when compare to other arithmetic operators.
In the next article, I am going to discuss Increment Decrement Operator in C++ with Examples. Here, in this article, I try to explain Compound Assignment Operator in C++ with Examples and I hope you enjoy this Compound Assignment Operator in C++ with Examples article.
About the Author: Pranaya Rout
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.
you are one of the best teacher, I never saw this much nice explaination
Your email address will not be published. Required fields are marked *
Home » Learn C Programming from Scratch » C Assignment Operators
Summary : in this tutorial, you’ll learn about the C assignment operators and how to use them effectively.
An assignment operator assigns the vale of the right-hand operand to the left-hand operand. The following example uses the assignment operator (=) to assign 1 to the counter variable:
After the assignmment, the counter variable holds the number 1.
The following example adds 1 to the counter and assign the result to the counter:
The = assignment operator is called a simple assignment operator. It assigns the value of the left operand to the right operand.
Besides the simple assignment operator, C supports compound assignment operators. A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.
The following example uses a compound-assignment operator (+=):
The expression:
is equivalent to the following expression:
The following table illustrates the compound-assignment operators in C:
Operator | Operation Performed | Example | Equivalent expression |
---|---|---|---|
Multiplication assignment | x *= y | x = x * y | |
Division assignment | x /= y | x = x / y | |
Remainder assignment | x %= y | x = x % y | |
Addition assignment | x += y | x = x + y | |
Subtraction assignment | x -= y | x = x – y | |
Left-shift assignment | x <<= y | x = x <<=y | |
Right-shift assignment | x >>=y | x = x >>= y | |
Bitwise-AND assignment | x &= y | x = x & y | |
Bitwise-exclusive-OR assignment | x ^= y | x = x ^ y | |
Bitwise-inclusive-OR assignment | x |= y | x = x | y |
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++ −
Operators | Description |
---|---|
*= | Multiply the value of the first operand by the value of the second operand; store the result in the object specified by the first operand. |
/= | Divide the value of the first operand by the value of the second operand; store the result in the object specified by the first operand. |
%= | Take modulus of the first operand specified by the value of the second operand; store the result in the object specified by the first operand. |
+= | Add the value of the second operand to the value of the first operand; store the result in the object specified by the first operand. |
–= | Subtract the value of the second operand from the value of the first operand; store the result in the object specified by the first operand. |
<<= | Shift the value of the first operand left the number of bits specified by the value of the second operand; store the result in the object specified by the first operand. |
>>= | Shift the value of the first operand right the number of bits specified by the value of the second operand; store the result in the object specified by the first operand. |
&= | Obtain the bitwise AND of the first and second operands; store the result in the object specified by the first operand. |
^= | Obtain the bitwise exclusive OR of the first and second operands; store the result in the object specified by the first operand. |
|= | Obtain the bitwise inclusive OR of the first and second operands; store the result in the object specified by the first operand. |
Let's have a look at an example using some of these operators −
This will give the output −
Note that Compound assignment to an enumerated type generates an error message. If the left operand is of a pointer type, the right operand must be of a pointer type or it must be a constant expression that evaluates to 0. If the left operand is of an integral type, the right operand must not be of a pointer type.
Related Articles
Get certified by completing the course
To Continue Learning Please Login
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
I would like to know the execution flow of compound assignments in C++. I came across a CodeChef question , where I am calculating NCR mod p values and adding them together to get the final answer:
This is happening because of integer overflow.
So, what is the execution sequence of compound assignment?
Let's say, if we have an equation a+=b%c then what would be the execution sequence:
The compound assignment operators are in the second lowest precedence group of all in C++ (taking priority over only the comma operator). Thus, your a += b % c case would be equivalent to a += ( b % c ) , or a = a + ( b % c ) .
This explains why your two code snippets are different. The second:
is equivalent to:
Which is clearly different from the first (correct) expression:
This statement
is equivalent to the statement
As you can see it differs from the statement
From the C++ 14 Standard (5.18 Assignment and compound assignment operators)
7 The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once. In += and -=, E1 shall either have arithmetic type or be a pointer to a possibly cv-qualified completely-defined object type. In all other cases, E1 shall have arithmetic type.
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .
This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.
At a high level, an expression is a valid unit of code that resolves to a value. There are two types of expressions: those that have side effects (such as assigning values) and those that purely evaluate .
The expression x = 7 is an example of the first type. This expression uses the = operator to assign the value seven to the variable x . The expression itself evaluates to 7 .
The expression 3 + 4 is an example of the second type. This expression uses the + operator to add 3 and 4 together and produces a value, 7 . However, if it's not eventually part of a bigger construct (for example, a variable declaration like const z = 3 + 4 ), its result will be immediately discarded — this is usually a programmer mistake because the evaluation doesn't produce any effects.
As the examples above also illustrate, all complex expressions are joined by operators , such as = and + . In this section, we will introduce the following operators:
Comparison operators, arithmetic operators, bitwise operators, logical operators, bigint operators, string operators, conditional (ternary) operator, comma operator, unary operators, relational operators.
These operators join operands either formed by higher-precedence operators or one of the basic expressions . A complete and detailed list of operators and expressions is also available in the reference .
The precedence of operators determines the order they are applied when evaluating an expression. For example:
Despite * and + coming in different orders, both expressions would result in 7 because * has precedence over + , so the * -joined expression will always be evaluated first. You can override operator precedence by using parentheses (which creates a grouped expression — the basic expression). To see a complete table of operator precedence as well as various caveats, see the Operator Precedence Reference page.
JavaScript has both binary and unary operators, and one special ternary operator, the conditional operator. A binary operator requires two operands, one before the operator and one after the operator:
For example, 3 + 4 or x * y . This form is called an infix binary operator, because the operator is placed between two operands. All binary operators in JavaScript are infix.
A unary operator requires a single operand, either before or after the operator:
For example, x++ or ++x . The operator operand form is called a prefix unary operator, and the operand operator form is called a postfix unary operator. ++ and -- are the only postfix operators in JavaScript — all other operators, like ! , typeof , etc. are prefix.
An assignment operator assigns a value to its left operand based on the value of its right operand. The simple assignment operator is equal ( = ), which assigns the value of its right operand to its left operand. That is, x = f() is an assignment expression that assigns the value of f() to x .
There are also compound assignment operators that are shorthand for the operations listed in the following table:
Name | Shorthand operator | Meaning |
---|---|---|
If an expression evaluates to an object , then the left-hand side of an assignment expression may make assignments to properties of that expression. For example:
For more information about objects, read Working with Objects .
If an expression does not evaluate to an object, then assignments to properties of that expression do not assign:
In strict mode , the code above throws, because one cannot assign properties to primitives.
It is an error to assign values to unmodifiable properties or to properties of an expression without properties ( null or undefined ).
For more complex assignments, the destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects using a syntax that mirrors the construction of array and object literals.
Without destructuring, it takes multiple statements to extract values from arrays and objects:
With destructuring, you can extract multiple values into distinct variables using a single statement:
In general, assignments are used within a variable declaration (i.e., with const , let , or var ) or as standalone statements.
However, like other expressions, assignment expressions like x = f() evaluate into a result value. Although this result value is usually not used, it can then be used by another expression.
Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, some JavaScript style guides discourage chaining or nesting assignments . Nevertheless, assignment chaining and nesting may occur sometimes, so it is important to be able to understand how they work.
By chaining or nesting an assignment expression, its result can itself be assigned to another variable. It can be logged, it can be put inside an array literal or function call, and so on.
The evaluation result matches the expression to the right of the = sign in the "Meaning" column of the table above. That means that x = f() evaluates into whatever f() 's result is, x += f() evaluates into the resulting sum x + f() , x **= f() evaluates into the resulting power x ** f() , and so on.
In the case of logical assignments, x &&= f() , x ||= f() , and x ??= f() , the return value is that of the logical operation without the assignment, so x && f() , x || f() , and x ?? f() , respectively.
When chaining these expressions without parentheses or other grouping operators like array literals, the assignment expressions are grouped right to left (they are right-associative ), but they are evaluated left to right .
Note that, for all assignment operators other than = itself, the resulting values are always based on the operands' values before the operation.
For example, assume that the following functions f and g and the variables x and y have been declared:
Consider these three examples:
y = x = f() is equivalent to y = (x = f()) , because the assignment operator = is right-associative . However, it evaluates from left to right:
y = [ f(), x = g() ] also evaluates from left to right:
x[f()] = g() also evaluates from left to right. (This example assumes that x is already assigned to some object. For more information about objects, read Working with Objects .)
Chaining assignments or nesting assignments in other expressions can result in surprising behavior. For this reason, chaining assignments in the same statement is discouraged .
In particular, putting a variable chain in a const , let , or var statement often does not work. Only the outermost/leftmost variable would get declared; other variables within the assignment chain are not declared by the const / let / var statement. For example:
This statement seemingly declares the variables x , y , and z . However, it only actually declares the variable z . y and x are either invalid references to nonexistent variables (in strict mode ) or, worse, would implicitly create global variables for x and y in sloppy mode .
A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values. Strings are compared based on standard lexicographical ordering, using Unicode values. In most cases, if the two operands are not of the same type, JavaScript attempts to convert them to an appropriate type for the comparison. This behavior generally results in comparing the operands numerically. The sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. These operators do not attempt to convert the operands to compatible types before checking equality. The following table describes the comparison operators in terms of this sample code:
Operator | Description | Examples returning true |
---|---|---|
( ) | Returns if the operands are equal. |
|
( ) | Returns if the operands are not equal. | |
( ) | Returns if the operands are equal and of the same type. See also and . | |
( ) | Returns if the operands are of the same type but not equal, or are of different type. | |
( ) | Returns if the left operand is greater than the right operand. | |
( ) | Returns if the left operand is greater than or equal to the right operand. | |
( ) | Returns if the left operand is less than the right operand. | |
( ) | Returns if the left operand is less than or equal to the right operand. |
Note: => is not a comparison operator but rather is the notation for Arrow functions .
An arithmetic operator takes numerical values (either literals or variables) as their operands and returns a single numerical value. The standard arithmetic operators are addition ( + ), subtraction ( - ), multiplication ( * ), and division ( / ). These operators work as they do in most other programming languages when used with floating point numbers (in particular, note that division by zero produces Infinity ). For example:
In addition to the standard arithmetic operations ( + , - , * , / ), JavaScript provides the arithmetic operators listed in the following table:
Operator | Description | Example |
---|---|---|
( ) | Binary operator. Returns the integer remainder of dividing the two operands. | 12 % 5 returns 2. |
( ) | Unary operator. Adds one to its operand. If used as a prefix operator ( ), returns the value of its operand after adding one; if used as a postfix operator ( ), returns the value of its operand before adding one. | If is 3, then sets to 4 and returns 4, whereas returns 3 and, only then, sets to 4. |
( ) | Unary operator. Subtracts one from its operand. The return value is analogous to that for the increment operator. | If is 3, then sets to 2 and returns 2, whereas returns 3 and, only then, sets to 2. |
( ) | Unary operator. Returns the negation of its operand. | If is 3, then returns -3. |
( ) | Unary operator. Attempts to , if it is not already. | returns . returns . |
( ) | Calculates the to the power, that is, | returns . returns . |
A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather than as decimal, hexadecimal, or octal numbers. For example, the decimal number nine has a binary representation of 1001. Bitwise operators perform their operations on such binary representations, but they return standard JavaScript numerical values.
The following table summarizes JavaScript's bitwise operators.
Operator | Usage | Description |
---|---|---|
Returns a one in each bit position for which the corresponding bits of both operands are ones. | ||
Returns a zero in each bit position for which the corresponding bits of both operands are zeros. | ||
Returns a zero in each bit position for which the corresponding bits are the same. [Returns a one in each bit position for which the corresponding bits are different.] | ||
Inverts the bits of its operand. | ||
Shifts in binary representation bits to the left, shifting in zeros from the right. | ||
Shifts in binary representation bits to the right, discarding bits shifted off. | ||
Shifts in binary representation bits to the right, discarding bits shifted off, and shifting in zeros from the left. |
Conceptually, the bitwise logical operators work as follows:
For example, the binary representation of nine is 1001, and the binary representation of fifteen is 1111. So, when the bitwise operators are applied to these values, the results are as follows:
Expression | Result | Binary Description |
---|---|---|
Note that all 32 bits are inverted using the Bitwise NOT operator, and that values with the most significant (left-most) bit set to 1 represent negative numbers (two's-complement representation). ~x evaluates to the same value that -x - 1 evaluates to.
The bitwise shift operators take two operands: the first is a quantity to be shifted, and the second specifies the number of bit positions by which the first operand is to be shifted. The direction of the shift operation is controlled by the operator used.
Shift operators convert their operands to thirty-two-bit integers and return a result of either type Number or BigInt : specifically, if the type of the left operand is BigInt , they return BigInt ; otherwise, they return Number .
The shift operators are listed in the following table.
Operator | Description | Example |
---|---|---|
( ) | This operator shifts the first operand the specified number of bits to the left. Excess bits shifted off to the left are discarded. Zero bits are shifted in from the right. | yields 36, because 1001 shifted 2 bits to the left becomes 100100, which is 36. |
( ) | This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Copies of the leftmost bit are shifted in from the left. | yields 2, because 1001 shifted 2 bits to the right becomes 10, which is 2. Likewise, yields -3, because the sign is preserved. |
( ) | This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. | yields 4, because 10011 shifted 2 bits to the right becomes 100, which is 4. For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. |
Logical operators are typically used with Boolean (logical) values; when they are, they return a Boolean value. However, the && and || operators actually return the value of one of the specified operands, so if these operators are used with non-Boolean values, they may return a non-Boolean value. The logical operators are described in the following table.
Operator | Usage | Description |
---|---|---|
( ) | Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if both operands are true; otherwise, returns . | |
( ) | Returns if it can be converted to ; otherwise, returns . Thus, when used with Boolean values, returns if either operand is true; if both are false, returns . | |
( ) | Returns if its single operand that can be converted to ; otherwise, returns . |
Examples of expressions that can be converted to false are those that evaluate to null, 0, NaN, the empty string (""), or undefined.
The following code shows examples of the && (logical AND) operator.
The following code shows examples of the || (logical OR) operator.
The following code shows examples of the ! (logical NOT) operator.
As logical expressions are evaluated left to right, they are tested for possible "short-circuit" evaluation using the following rules:
The rules of logic guarantee that these evaluations are always correct. Note that the anything part of the above expressions is not evaluated, so any side effects of doing so do not take effect.
Note that for the second case, in modern code you can use the Nullish coalescing operator ( ?? ) that works like || , but it only returns the second expression, when the first one is " nullish ", i.e. null or undefined . It is thus the better alternative to provide defaults, when values like '' or 0 are valid values for the first expression, too.
Most operators that can be used between numbers can be used between BigInt values as well.
One exception is unsigned right shift ( >>> ) , which is not defined for BigInt values. This is because a BigInt does not have a fixed width, so technically it does not have a "highest bit".
BigInts and numbers are not mutually replaceable — you cannot mix them in calculations.
This is because BigInt is neither a subset nor a superset of numbers. BigInts have higher precision than numbers when representing large integers, but cannot represent decimals, so implicit conversion on either side might lose precision. Use explicit conversion to signal whether you wish the operation to be a number operation or a BigInt one.
You can compare BigInts with numbers.
In addition to the comparison operators, which can be used on string values, the concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.
For example,
The shorthand assignment operator += can also be used to concatenate strings.
The conditional operator is the only JavaScript operator that takes three operands. The operator can have one of two values based on a condition. The syntax is:
If condition is true, the operator has the value of val1 . Otherwise it has the value of val2 . You can use the conditional operator anywhere you would use a standard operator.
This statement assigns the value "adult" to the variable status if age is eighteen or more. Otherwise, it assigns the value "minor" to status .
The comma operator ( , ) evaluates both of its operands and returns the value of the last operand. This operator is primarily used inside a for loop, to allow multiple variables to be updated each time through the loop. It is regarded bad style to use it elsewhere, when it is not necessary. Often two separate statements can and should be used instead.
For example, if a is a 2-dimensional array with 10 elements on a side, the following code uses the comma operator to update two variables at once. The code prints the values of the diagonal elements in the array:
A unary operation is an operation with only one operand.
The delete operator deletes an object's property. The syntax is:
where object is the name of an object, property is an existing property, and propertyKey is a string or symbol referring to an existing property.
If the delete operator succeeds, it removes the property from the object. Trying to access it afterwards will yield undefined . The delete operator returns true if the operation is possible; it returns false if the operation is not possible.
Since arrays are just objects, it's technically possible to delete elements from them. This is, however, regarded as a bad practice — try to avoid it. When you delete an array property, the array length is not affected and other elements are not re-indexed. To achieve that behavior, it is much better to just overwrite the element with the value undefined . To actually manipulate the array, use the various array methods such as splice .
The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string, variable, keyword, or object for which the type is to be returned. The parentheses are optional.
Suppose you define the following variables:
The typeof operator returns the following results for these variables:
For the keywords true and null , the typeof operator returns the following results:
For a number or string, the typeof operator returns the following results:
For property values, the typeof operator returns the type of value the property contains:
For methods and functions, the typeof operator returns results as follows:
For predefined objects, the typeof operator returns results as follows:
The void operator specifies an expression to be evaluated without returning a value. expression is a JavaScript expression to evaluate. The parentheses surrounding the expression are optional, but it is good style to use them to avoid precedence issues.
A relational operator compares its operands and returns a Boolean value based on whether the comparison is true.
The in operator returns true if the specified property is in the specified object. The syntax is:
where propNameOrNumber is a string, numeric, or symbol expression representing a property name or array index, and objectName is the name of an object.
The following examples show some uses of the in operator.
The instanceof operator returns true if the specified object is of the specified object type. The syntax is:
where objectName is the name of the object to compare to objectType , and objectType is an object type, such as Date or Array .
Use instanceof when you need to confirm the type of an object at runtime. For example, when catching exceptions, you can branch to different exception-handling code depending on the type of exception thrown.
For example, the following code uses instanceof to determine whether theDay is a Date object. Because theDay is a Date object, the statements in the if statement execute.
All operators eventually operate on one or more basic expressions. These basic expressions include identifiers and literals , but there are a few other kinds as well. They are briefly introduced below, and their semantics are described in detail in their respective reference sections.
Use the this keyword to refer to the current object. In general, this refers to the calling object in a method. Use this either with the dot or the bracket notation:
Suppose a function called validate validates an object's value property, given the object and the high and low values:
You could call validate in each form element's onChange event handler, using this to pass it to the form element, as in the following example:
The grouping operator ( ) controls the precedence of evaluation in expressions. For example, you can override multiplication and division first, then addition and subtraction to evaluate addition first.
You can use the new operator to create an instance of a user-defined object type or of one of the built-in object types. Use new as follows:
The super keyword is used to call functions on an object's parent. It is useful with classes to call the parent constructor, for example.
When it comes to calculating interest, there are two basic choices: simple and compound. Simple interest simply means a set percentage of the principal amount every year.
For example, if you invest $1,000 at 5% simple interest for 10 years, you can expect to receive $50 in interest every year for the next decade. No more, no less. In the investment world, bonds are an example of an investment that typically pays simple interest.
On the other hand, compound interest is what you get when you reinvest your earnings, which then also earn interest. Compound interest essentially means "interest on the interest" and is why many investors are so successful.
Think of it this way. Let's say you invest $1,000 at 5% interest. After the first year, you receive a $50 interest payment, but instead of receiving it in cash, you reinvest the interest you earned at the same 5% rate. For the second year, your interest would be calculated on a $1,050 investment, which comes to $52.50. If you reinvest that, your third-year interest would be calculated on a $1,102.50 balance.
You get the idea. Compound interest means your principal gets larger over time and will generate larger and larger interest payments. The difference between simple and compound interest can be massive. Take a look at the difference on a $10,000 investment portfolio at 10% interest over time:
Time Period | Simple Interest at 10% | Compound Interest (annually at 10%) |
---|---|---|
Start | $10,000 | $10,000 |
1 year | $11,000 | $11,000 |
2 years | $12,000 | $12,100 |
5 years | $15,000 | $16,105 |
10 years | $20,000 | $25,937 |
20 years | $30,000 | $67,275 |
30 years | $40,000 | $174,494 |
Note that 10% is, roughly, the long-term annualized return of the S&P 500 . It was 9.65% for the 30-year period through 2022. Returns like this, compounded over long periods, can result in some pretty impressive performances.
It's also worth mentioning that there's a very similar concept known as cumulative interest. Cumulative interest refers to the sum of the interest payments made, but it typically refers to payments made on a loan. For example, the cumulative interest on a 30-year mortgage would be how much you paid toward interest over the 30-year loan term.
How compound interest is calculated.
Compound interest is calculated by applying an exponential growth factor to the interest rate or rate of return you're using. The good news is that there are plenty of excellent calculators that will do the math for you.
Below is a mathematical formula you could use for calculating compound interest over a certain period:
With "A" as the final amount, here's what all the other variables mean:
Compounding frequency and why it matters.
In the previous example, we used annual compounding, meaning the interest is calculated once per year. In practice, compound interest is often calculated more frequently. For example, your savings account may calculate interest monthly. Common compounding intervals are quarterly, monthly, and daily, but many other possible intervals could be used.
The compounding frequency makes a difference. All other factors being equal, more frequent compounding leads to faster growth. For instance, the table below shows the growth of $10,000 at 8% interest compounded at several frequencies:
Time | Annual Compounding | Quarterly | Monthly |
---|---|---|---|
1 year | $10,800 | $10,824 | $10,830 |
5 years | $14,693 | $14,859 | $14,898 |
10 years | $21,589 | $22,080 | $22,196 |
As a basic example, let's say you're investing $20,000 at 5% interest compounded quarterly for 20 years. In this case, "n" would be four, as quarterly compounding occurs four times per year.
Based on this information, we can calculate the investment's final value after 20 years like this:
You may hear the terms compound interest and compound earnings used interchangeably, especially when discussing investment returns. However, there's a subtle difference.
Specifically, compound earnings refers to the compounding effects of both interest payments and dividends, as well as appreciation in the value of the investment itself. In other words, it's more of an all-in-one term to describe investment returns that aren't entirely interest.
For example, if a stock investment paid you a 4% dividend yield and the stock itself increased in value by 5%, you'd have total earnings of 9% for the year. When these dividends and price gains compound over time, it is a form of compound earnings and not interest, as not all of the gains come from payments to you.
In a nutshell, long-term returns from stocks, exchange-traded funds (ETFs) , or mutual funds are technically called compound earnings. However, it can still be calculated in the same manner if you know your expected rate of return.
Accounts that earn compounding interest.
Interest compounds when interest payments also earn interest. Learn how to get compounding interest working for your portfolio.
You invest to get a return. So what makes a good ROI?
Municipalities issue bonds that could be a great investment. How do they work?
Why compound interest is such an important concept for investors.
Compound interest is the phenomenon that allows seemingly small amounts of money to grow into large amounts over time. To take full advantage of the power of compound interest, investments must be allowed to grow and compound for long periods.
Join over half a million premium members receiving….
Market beating stocks from our award-winning service
Investment news and high-quality insights delivered straight to your inbox
You can do it. Successful investing in just a few steps
Secrets and strategies for the post-work life you want.
Find the right brokerage account for you.
Hear our experts take on stocks, the market, and how to invest.
Invest better with The Motley Fool. Get stock recommendations, portfolio guidance, and more from The Motley Fool's premium services.
Senior Lecturer, Exercise Physiology. School of Health Sciences, UNSW Sydney
PhD Candidate in Exercise Physiology, UNSW Sydney
Mandy Hagstrom is affiliated with Sports Oracle, a company that delivers the IOC diploma in Strength and Conditioning.
Anurag Pandit is currently on a Research Training Program scholarship for his PhD at UNSW.
UNSW Sydney provides funding as a member of The Conversation AU.
View all partners
So you’ve got yourself a gym membership or bought a set of home weights. Now what? With the sheer amount of confusing exercise advice out there, it can be hard to decide what to include in a weights routine.
It can help to know there are broadly two types of movements in resistance training (lifting weights): compound exercises and isolation exercises.
So what’s the difference? And what’s all this got to do with strength, speed and healthy ageing?
Compound exercises involve multiple joints and muscle groups working together.
In a push up, for example, your shoulder and elbow joints are moving together. This targets the muscles in the chest, shoulder and triceps.
When you do a squat, you’re using your thigh and butt muscles, your back, and even the muscles in your core.
It can help to think about compound movements by grouping them by primary movement patterns.
For example, some lower body compound exercises follow a “squat pattern”. Examples include bodyweight squats, weighted squats, lunges and split squats.
We also have “hinge patterns”, where you hinge from a point on your body (such as the hips). Examples include deadlifts, hip thrusts and kettle bell swings.
Upper body compounded exercises can be grouped into “push patterns” (such as vertical barbell lifts) or “pull patterns” (such as weighted rows, chin ups or lat pull downs, which is where you use a pulley system machine to lift weights by pulling a bar downwards).
In contrast, isolation exercises are movements that occur at a single joint.
For instance, bicep curls only require movement at the elbow joint and work your bicep muscles. Tricep extensions and lateral raises are other examples of isolation exercises.
Many compound exercises mimic movements we do every day.
Hinge patterns mimic picking something off the floor. A vertical press mimics putting a heavy box on a high shelf. A squat mimics standing up from the couch or getting on and off the toilet.
That might sound ridiculous to a young, fit person (“why would I need to practise getting on and off a toilet?”).
Unfortunately, we lose strength and muscle mass as we age. Men lose about 5% of their muscle mass per decade, while for women the figure is about 4% per decade.
When this decline begins can vary widely. However, approximately 30% of an adult’s peak muscle mass is lost by the time they are 80.
The good news is resistance training can counteract these age-related changes in muscle size and strength.
So building strength through compound exercise movements may help make daily life feel a bit easier. In fact, our ability to perform compound movements are a good indicator how well we can function as we age .
Compound exercises use multiple joints, so you can generally lift heavier weights than you could with isolation exercises. Lifting a heavier weight means you can build muscle strength more efficiently.
One study divided a group of 36 people into two. Three times a week, one group performed isolation exercises, while the other group did compound exercises.
After eight weeks, both groups had lost fat. But the compound exercises group saw much better results on measures of cardiovascular fitness, bench press strength, knee extension strength, and squat strength.
If you play a sport, compound movements can also help boost athletic ability.
Squat patterns require your hip, knee, and ankle to extend at the same time (also known as triple extension).
Our bodies use this triple extension trick when we run, sprint, jump or change direction quickly. In fact, research has found squat strength is strongly linked to being able to sprint faster and jump higher .
What if you’re unable to do compound movements, or you just don’t want to?
Don’t worry, you’ll still build strength and muscle with isolation exercises.
Isolation exercises are also typically easier to learn as there is no skill required. They are an easy and low risk way to add extra exercise at the end of the workout, where you might otherwise be too tired to do more compound exercises safely and with correct form.
In fact, both isolation and compound exercises seem to be equally effective in helping us lose body fat and increase fat-free muscle mass when total intensity and volume of exercises are otherwise equal.
Some people also do isolation exercises when they want to build up a particular muscle group for a certain sport or for a bodybuilding competition, for example.
Considering the above factors, you could consider prioritising compound exercises if you’re:
keen to lift heavier weights
looking for an efficient way to train many muscles in the one workout
interested in healthy ageing.
That said, most well designed workout programs will include both compound and isolation movements.
Correction: This article has been amended to reflect the fact a weighted row is a pull pattern, not a push pattern.
Official websites use .gov
A .gov website belongs to an official government organization in the United States.
Secure .gov websites use HTTPS
A lock ( ) or https:// means you've safely connected to the .gov website. Share sensitive information only on official, secure websites.
Infectious disease outbreaks currently being reported on by CDC. Listings include those outbreaks for which content is currently published on the CDC website.
Recent investigations reported on CDC.gov
Please see the Travelers’ Health site for a complete list.
In the last two years, CDC has sent scientists and doctors out more than 750 times to respond to health threats. Learn more below.
COMMENTS
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 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.
Compound Assignment Operators. An assignment operator is a binary operator that assigns the result of the right-hand side to the variable on the left-hand side. ... For example, the following two multiplication statements are equivalent, ...
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 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.
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 ...
The compound assignment operators are: += -= *= /= %= Consider variable k: int k= 5; Each of the following two lines contains equivalent assignment statements, so it looks like the compound assignment operators simply provide syntactic sugar:
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.
️ Open Sans AaBbCc 123 PreTeXt; Roboto Serif AaBbCc 123 PreTeXt; Adjust font
The "*= 2" is an example of a compound assignment operator, which multiplies the current value of integerOne by 2 and sets that as the new value of integerOne. Other arithmetic operators also have compound assignment operators as well, with addition, subtraction, division, ...
1.5. Compound Assignment Operators ¶. Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to x and assigns the sum to x. It is the same as x = x + 1. This pattern is possible with any operator put in front of the = sign, as seen below. + shortcuts. - shortcuts.
Compound operators, also called combined assignment operators, are a shorthand way to update the value of a variableThey are+= (addition)-= (subtraction)*= (...
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.
For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment.. Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b. [] Assignment operator syntaThe assignment expressions have the form
There are four compound assignment operators in C language, such as +=, -= , *=, /=. Let's example each of these and their use with simple code examples.
In this article, I am going to discuss Compound Assignment Operator in C++ with Examples. We will learn about compound assignment operators
A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand. The following example uses a compound-assignment operator (+=):
The 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:
What is the real advantage of using compound assignment in C/C++ (or may be applicable to many other programming languages as well)? #include <stdio.h> int main() { int exp1=20; int...
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 ...
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 chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more.
Compound interest is the phenomenon that allows seemingly small amounts of money to grow into large amounts over time. Compound interest essentially means "interest on the interest" and is the ...
You could consider prioritising compound exercises if you're time poor, interested in healthy ageing and looking for an efficient way to train many muscles and joints in the one workout.
Multistate Foodborne Outbreaks - Foodborne outbreaks listed by year; Hepatitis A Outbreaks - Hepatitis A outbreak investigations since 2013 where CDC supported or led the investigation.; US Outbreaks Linked to Contact with Animals or Animal Products; Health Alert Network - Health alerts, health advisories, updates, and info service messages. Designed for public health and medical ...