/ | ||||
(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++20) | ||||
(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 |
Prec/Ass | Operator | Description | Pattern |
---|---|---|---|
1 L->R | :: :: | Global scope (unary) Namespace scope (binary) | ::name class_name::member_name |
2 L->R | () () type() type{} [] . -> ++ –– typeid const_cast dynamic_cast reinterpret_cast static_cast sizeof… noexcept alignof | Parentheses Function call Functional cast List init temporary object (C++11) Array subscript Member access from object Member access from object ptr Post-increment Post-decrement Run-time type information Cast away const Run-time type-checked cast Cast one type to another Compile-time type-checked cast Get parameter pack size Compile-time exception check Get type alignment | (expression) function_name(arguments) type(expression) type{expression} pointer[expression] object.member_name object_pointer->member_name lvalue++ lvalue–– typeid(type) or typeid(expression) const_cast<type>(expression) dynamic_cast<type>(expression) reinterpret_cast<type>(expression) static_cast<type>(expression) sizeof…(expression) noexcept(expression) alignof(type) |
3 R->L | + - ++ –– ! not ~ (type) sizeof co_await & * new new[] delete delete[] | Unary plus Unary minus Pre-increment Pre-decrement Logical NOT Logical NOT Bitwise NOT C-style cast Size in bytes Await asynchronous call Address of Dereference Dynamic memory allocation Dynamic array allocation Dynamic memory deletion Dynamic array deletion | +expression -expression ++lvalue ––lvalue !expression not expression ~expression (new_type)expression sizeof(type) or sizeof(expression) co_await expression (C++20) &lvalue *expression new type new type[expression] delete pointer delete[] pointer |
4 L->R | ->* .* | Member pointer selector Member object selector | object_pointer->*pointer_to_member object.*pointer_to_member |
5 L->R | * / % | Multiplication Division Remainder | expression * expression expression / expression expression % expression |
6 L->R | + - | Addition Subtraction | expression + expression expression - expression |
7 L->R | << >> | Bitwise shift left / Insertion Bitwise shift right / Extraction | expression << expression expression >> expression |
8 L->R | <=> | Three-way comparison (C++20) | expression <=> expression |
9 L->R | < <= > >= | Comparison less than Comparison less than or equals Comparison greater than Comparison greater than or equals | expression < expression expression <= expression expression > expression expression >= expression |
10 L->R | == != | Equality Inequality | expression == expression expression != expression |
11 L->R | & | Bitwise AND | expression & expression |
12 L->R | ^ | Bitwise XOR | expression ^ expression |
13 L->R | | | Bitwise OR | expression | expression |
14 L->R | && and | Logical AND Logical AND | expression && expression expression and expression |
15 L->R | || or | Logical OR Logical OR | expression || expression expression or expression |
16 R->L | throw co_yield ?: = *= /= %= += -= <<= >>= &= |= ^= | Throw expression Yield expression (C++20) Conditional Assignment Multiplication assignment Division assignment Remainder assignment Addition assignment Subtraction assignment Bitwise shift left assignment Bitwise shift right assignment Bitwise AND assignment Bitwise OR assignment Bitwise XOR assignment | throw expression co_yield expression expression ? expression : expression lvalue = expression lvalue *= expression lvalue /= expression lvalue %= expression lvalue += expression lvalue -= expression lvalue <<= expression lvalue >>= expression lvalue &= expression lvalue |= expression lvalue ^= expression |
17 L->R | , | Comma operator | expression, expression |
Best practice
Value computation (of operations)
We know from the precedence and associativity rules above that this expression will be grouped as if we had typed:
Sample problem: x = 2 + 3 % 4 Binary operator has higher precedence than operator or operator , so it gets evaluated first: x = 2 + (3 % 4) Binary operator has a higher precedence than operator , so it gets evaluated next: Final answer: x = (2 + (3 % 4)) We now no longer need the table above to understand how this expression will evaluate. |
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.
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++:
Lets see each of them in detail.
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:
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.
In C++, the multiplication assignment operator (*=) is used to update the value of the variable by multiplying it with another value.
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.
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.
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.
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.
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.
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.
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.
Similar reads.
“For this patrol, our mission was to intercept drugs from smuggling vessels in the Caribbean. We left Virginia on May 28th and made four port calls along the way: Key West, Puerto Rico, Columbia, and Cuba,” said Bucki.
Bucki witnessed, first-hand, the training that goes into cutter operations to prep for a mission. She and the crew simulated a “fast cruise” which is a simulated underway day, which allowed the crew to conduct various trainings before the patrol begins. FORWARD also did a “shakedown cruise” where the crew trains in their actual roles while the ship is underway. The shakedown cruise is vital for crewmembers to familiarize themselves with shipboard functions at sea.
“There are many different training scenarios for responding to various casualties aboard. I participated in simulated progressive flooding and crankcase explosion casualty,” said Bucki. “During the shakedown cruise the day was jam-packed with training. We simulated a man overboard, practiced dropping anchor, and ensured that everyone knew their assigned role for getting underway.”
Bucki also became qualified in flight operations tasks, which involve the many aspects that go into a helicopter returning to and taking off from the ship. She learned and demonstrated her skills in hose handling, personal protective equipment (PPE), and basic firefighting. She also familiarized herself with the engineering aspects during this patrol, memorizing many parameters (pressure, temperature, etc.) and functions of engine room and auxiliary systems.
Bucki’s action and adventure packed time on USCGC FORWARD led to the building of Coast Guard bonds with crew members, more confidence in her forthcoming role as ensign and a newfound awareness of her own leadership style.
“I am first generation military, so I am not as familiar with the Coast Guard compared to others. This experience helped me explore some possible career paths and understand the life of a junior officer. I came to realize that there are many factors that influence one’s experience as an ensign. Although location and platform are the main components taken into consideration for billet picks, there are many other things that influence what life will be like on a ship. This includes command climate, status of the ship’s equipment, and collateral duties,” said Bucki.
Bucki would like to receive a Buoy Tender or Fast Response Cutter as her first assignment upon graduation.
Thank you for submitting your application to be part of the Sponsor Family Program. Your application will be processed in the upcoming week. Coast Guard Academy’s policy on background screening now requires all adults (everyone 18 and older living in the home) who volunteer to mentor, teach, coach or sponsor cadets, whether on or off Coast Guard Academy grounds, to be screened every 5 years. They are required to provide personal information (name, birth date and social security number) for the purpose of conducting a criminal background check.
The Security Officer at the Coast Guard Academy, CWO2 Gina Polkowski, is overseeing this process. Her email is: [email protected].
Sponsor Family designations fall into several different categories. Below are the guidelines to help you determine how best to meet the background screening requirement:
After you complete your application, please e-mail the Sponsor Family Program Coordinator at [email protected] . In your e-mail, you must include the e-mail address and phone number of every adult living in the home. The Sponsor Family Coordinator will then initiate the background check process and you will receive an email with further instructions.
Important things to note:
There is a Sponsor Family Training that is a one-hour training which we ask sponsors to attend once every four years. This training is designed to give you an overview of the program, what is expected of you as a sponsor, and what you can expect from your cadets. This training will also help familiarize you with the cadet regulations onboard CGA. You will be notified via e-mail once the training is scheduled.
The matching process of swabs to families will occur during July and August. Please bear with us and remain flexible through this process. There will be a meet and greet scheduled on Campus, typically in late August. This will give families an opportunity to formally meet their cadet if they have not already done so. Details on this will also be via email.
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.
Why do we get different results for the two follow statements:
the output is 26; whereas the next example returns 30, though they are same?!
These both exhibit undefined behaviour in both C++03 and C++11. In C++11 terminology, you can't have two unsequenced modifications of the same scalar or a modification and a value computation using the same scalar, otherwise you have undefined behaviour.
In this case, incrementing x (a modification) is unsequenced with the other two value computation of x .
In this case, incrementing x is unsequenced with the value computation of x on the left.
For the meaning of undefined behaviour, see C++11 §1.3.24:
undefined behavior behavior for which this International Standard imposes no requirements
Assigning a ++'d value to the original value is undefined behavior. So it makes sense that assigning a ++'d then multiplied value is also undefined.
IMAGES
VIDEO
COMMENTS
The syntax of Multiplication Operator with two operands is. operand1 * operand2. When this operator is given with operands of different numeric datatypes, the lower datatype is promoted to higher datatype. Examples. In the following program, we take two integers in a, b, and find their product using Multiplication Operator. main.c
Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs . Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non ...
Multiplication: Multiplies two values: ... Decreases the value of a variable by 1--x: Try it » Assignment Operators. Assignment operators are used to assign values to variables. In the example below, we use the assignment operator (=) to assign the value 10 to a variable called x: Example. int x = 10;
They are derived from the grammar. In C++, the conditional operator has the same precedence as assignment operators, and prefix ++ and -- and assignment operators don't have the restrictions about their operands. Associativity specification is redundant for unary operators and is only shown for completeness: unary prefix operators always ...
The operators +, -and * computes addition, subtraction, and multiplication respectively as you might have expected. In normal calculation, 9/4 = 2.25. However, the output is 2 in the ... C Assignment Operators. An assignment operator is used for assigning a value to a variable. The most common assignment operator is = Operator Example Same as ...
Prerequisite: Operator Overloading The assignment operator,"=", is the operator used for Assignment. It copies the right value into the left value. Assignment Operators are predefined to operate only on built-in Data types. Assignment operator overloading is binary operator overloading.Overloading assignment operator in C++ copies all values of one
Assignment operators are used in programming to assign values to variables. We use an assignment operator to store and update data within a program. They enable programmers to store data in variables and manipulate that data. The most common assignment operator is the equals sign (=), which assigns the value on the right side of the operator to ...
Code language:C++(cpp) 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 ...
5. Assignment Operators in C. Assignment operators are used to assign value to a variable. The left side operand of the assignment operator is a variable and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type as the variable on the left side otherwise the compiler will raise ...
Simple assignment operator. Assigns values from right side operands to left side operand. C = A + B will assign the value of A + B to C. +=. Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A. -=.
C can assign values to variables and perform basic mathematical operations using shorthand operators: Assignment: = Addition then assignment: += Subtraction then assignment: -= Multiplication then assignment: *= Division then assignment: /= Modulo then assignment: %=
In C++, Multiplication Assignment Operator is used to find the product of the value (right operand) and this variable (left operand) and assign the result back to this variable (left operand). The syntax to find the product of a value 2 with variable x and assign the result to x using Multiplication Assignment Operator is. x *= 2.
1. If your language allows multiplication between a boolean and a number, then yes, that is faster than a conditional. Conditionals require branching, which can invalidate the CPU's pipeline. Also if the branch is big enough, it can even cause a cache miss in the instructions, though that's unlikely in your small example.
Output. Here, the user input is stored in the int variable n. Then, we use a for loop to print the multiplication table up to 10. printf("%d * %d = %d \n", n, i, n * i); The loop runs from i = 1 to i = 10. In each iteration of the loop, n * i is printed. Here's a little modification of the above program to generate the multiplication table up ...
Usual arithmetic conversions are performed on both operands. In the remaining description in this section, "operand (s)", lhs and rhs refer to the converted operand (s). 1) The result of built-in multiplication is the product of the operands. Multiplication of a NaN by any number gives NaN.
These are as follows: 1. Binary Arithmetic Operators in C. The C binary arithmetic operators operate or work on two operands. C provides 5 Binary Arithmetic Operators for performing arithmetic functions which are as follows: Add two operands. Subtract the second operand from the first operand. Multiply two operands.
Correct behavior. CWG 1527. 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. CWG 1538. C++11. E1 ={E2} was equivalent to E1 = T(E2) (T is the type of E1), this introduced a C-style cast.
Chapter introduction. This chapter builds on top of the concepts from lesson 1.9 -- Introduction to literals and operators.A quick review follows: An operation is a mathematical process involving zero or more input values (called operands) that produces a new value (called an output value).The specific operation to be performed is denoted by a construct (typically a symbol or pair of symbols ...
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. Syntax. variable += value; This above expression is equivalent to the expression: variable = variable + value; Example.
When it came to her summer assignment, 1/c Mackenzie Bucki got the opposite of what she requested. Instead of a small, patrol boat in the Pacific, she got a 270-foot ship in the Atlantic. The USCGC FORWARD, based in Norfolk, VA, is a medium endurance cutter focusing on migrant and drug interdiction. "For this patrol, […]
Assignment by product (multiplication assignment) with increment or decrement in C++? [duplicate] Ask Question Asked 10 years, 8 months ago. Modified 10 years, 8 months ago. Viewed 3k times -1 This question ... These both exhibit undefined behaviour in both C++03 and C++11. In C++11 terminology, you can't have two unsequenced modifications of ...