a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b
++a
--a
a++
a--
+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b
!a
a && b
a || b
a == b
a != b
a < b
a > b
a <= b
a >= b
a[b]
*a
&a
a->b
a.b
a(...)
a, b
(type) a
a ? b : c
sizeof
_Alignof
(since C11)
for Assignment operators |
C++ functions, c++ classes, c++ data s tructures, c++ reference, c++ examples, c++ assignment operators, 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 :
The addition assignment operator ( += ) adds a value to a variable:
A list of all assignment operators:
Operator | Example | Same As | Try it |
---|---|---|---|
= | x = 5 | x = 5 | |
+= | x += 3 | x = x + 3 | |
-= | x -= 3 | x = x - 3 | |
*= | x *= 3 | x = x * 3 | |
/= | x /= 3 | x = x / 3 | |
%= | x %= 3 | x = x % 3 | |
&= | x &= 3 | x = x & 3 | |
|= | x |= 3 | x = x | 3 | |
^= | x ^= 3 | x = x ^ 3 | |
>>= | x >>= 3 | x = x >> 3 | |
<<= | x <<= 3 | x = x << 3 |
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]
If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]
Top references, top examples, get certified.
Learn Python practically and Get Certified .
Popular examples, reference materials, learn python interactively, python introduction.
Python flow control.
Python if...else Statement
Python Operator Overloading
Precedence and Associativity of Operators in Python
Python 3 Tutorial
Operators are special symbols that perform operations on variables and values. For example,
Here, + is an operator that adds two numbers: 5 and 6 .
Here's a list of different types of Python operators that we will learn in this tutorial.
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, etc. For example,
Here, - is an arithmetic operator that subtracts two values or variables.
Operator | Operation | Example |
---|---|---|
Addition | ||
Subtraction | ||
Multiplication | ||
Division | ||
Floor Division | ||
Modulo | ||
Power |
In the above example, we have used multiple arithmetic operators,
Assignment operators are used to assign values to variables. For example,
Here, = is an assignment operator that assigns 5 to x .
Here's a list of different assignment operators available in Python.
Operator | Name | Example |
---|---|---|
Assignment Operator | ||
Addition Assignment | ||
Subtraction Assignment | ||
Multiplication Assignment | ||
Division Assignment | ||
Remainder Assignment | ||
Exponent Assignment |
Here, we have used the += operator to assign the sum of a and b to a .
Similarly, we can use any other assignment operators as per our needs.
Comparison operators compare two values/variables and return a boolean result: True or False . For example,
Here, the > comparison operator is used to compare whether a is greater than b or not.
Operator | Meaning | Example |
---|---|---|
Is Equal To | gives us | |
Not Equal To | gives us | |
Greater Than | gives us | |
Less Than | gives us | |
Greater Than or Equal To | give us | |
Less Than or Equal To | gives us |
Note: Comparison operators are used in decision-making and loops . We'll discuss more of the comparison operator and decision-making in later tutorials.
Logical operators are used to check whether an expression is True or False . They are used in decision-making. For example,
Here, and is the logical operator AND . Since both a > 2 and b >= 6 are True , the result is True .
Operator | Example | Meaning |
---|---|---|
a b | : only if both the operands are | |
a b | : if at least one of the operands is | |
a | : if the operand is and vice-versa. |
Note : Here is the truth table for these logical operators.
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.
For example, 2 is 10 in binary, and 7 is 111 .
In the table below: Let x = 10 ( 0000 1010 in binary) and y = 4 ( 0000 0100 in binary)
Operator | Meaning | Example |
---|---|---|
Bitwise AND | x & y = 0 ( ) | |
Bitwise OR | x | y = 14 ( ) | |
Bitwise NOT | ~x = -11 ( ) | |
Bitwise XOR | x ^ y = 14 ( ) | |
Bitwise right shift | x >> 2 = 2 ( ) | |
Bitwise left shift | x 0010 1000) |
Python language offers some special types of operators like the identity operator and the membership operator. They are described below with examples.
In Python, is and is not are used to check if two values are located at the same memory location.
It's important to note that having two variables with equal values doesn't necessarily mean they are identical.
Operator | Meaning | Example |
---|---|---|
if the operands are identical (refer to the same object) | ||
if the operands are not identical (do not refer to the same object) |
Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. The same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them separately in memory, although they are equal.
In Python, in and not in are the membership operators. They are used to test whether a value or variable is found in a sequence ( string , list , tuple , set and dictionary ).
In a dictionary, we can only test for the presence of a key, not the value.
Operator | Meaning | Example |
---|---|---|
if value/variable is in the sequence | ||
if value/variable is in the sequence |
Here, 'H' is in message , but 'hello' is not present in message (remember, Python is case-sensitive).
Similarly, 1 is key, and 'a' is the value in dictionary dict1 . Hence, 'a' in y returns False .
Before we wrap up, let’s put your knowledge of Python operators to the test! Can you solve the following challenge?
Write a function to split the restaurant bill among friends.
Sorry about that.
Our premium learning platform, created with over a decade of experience and thousands of feedbacks .
Learn and improve your coding skills like never before.
Python Tutorial
The assignment ( = ) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.
A valid assignment target, including an identifier or a property accessor . It can also be a destructuring assignment pattern .
An expression specifying the value to be assigned to x .
The value of y .
Thrown in strict mode if assigning to an identifier that is not declared in the scope.
Thrown in strict mode if assigning to a property that is not modifiable .
The assignment operator is completely different from the equals ( = ) sign used as syntactic separators in other locations, which include:
All these places accept an assignment expression on the right-hand side of the = , so if you have multiple equals signs chained together:
This is equivalent to:
Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5 , and x is initialized with the value of the y = 5 expression, which is also 5 . If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode , or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:
Value of assignment expressions.
The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.
The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global. .
Because the global object has a String property ( Object.hasOwn(globalThis, "String") ), you can use the following code:
So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String ; you can just type the unqualified String . To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.
In strict mode , assignment to an unqualified identifier in strict mode will result in a ReferenceError , to avoid the accidental creation of properties on the global object.
Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.
The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.
For more information, see Destructuring assignment .
Specification |
---|
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
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 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.
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.
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.
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.
For more information, see the Assignment operators section of the C# language specification .
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'm trying to understand the purpose of overloading some operators in C++. Conceptually, an assignment statement can be easily implemented via:
In fact, often, the copy-and-swap implementation is the implementation of assignment in real code.
Why, then, does C++ allow the programmer to overload the assignment operator, instead of just performing the above?
Was it intended to allow a scenario in which assignment is faster than destruction + construction? If so, when does that happen? And if not, then what use case was it intended to support?
1) Reference counting
Suppose you have a resource that is ref-counted and it is wrapped in objects.
2) Or you just want to copy the fields without fancy semantics.
In both cases the code runs much faster. In the second case the effect is similar.
3) Also what about types... Use the operator to handle assigning other types to your type.
first, note that "Destruction of the old object followed by copy construction of the new object" is not exception safe.
but re "Copy construction of the new object, followed by a swap with the old object, followed by destruction of the old object", that's the swap idiom for implementing an assignment operator, and it's exception safe if done correctly.
in some cases a custom assignment operator can be faster than the swap idiom. for example, direct arrays of POD type can't really be swapped except by way of lower level assignments. so there for the swap idiom you can expect an overhead proportional to the array size.
however, historically there wasn't much focus on swapping and exception safety.
bjarne wanted exceptions originally (if i recall correctly), but they didn't get into the language until 1989 or thereabouts. so the original c++ way of programming was more focused on assignments. to the degree that a failing constructor signalled its failure by assigning 0 to this … i think , that in those days your question would not have made sense. it was just assignments all over.
typewise, some objects have identity, and others have value. it makes sense to assign to value objects, but for identity objects one typically wants to limit the ways that the object can be modified. while this doesn't require the ability to customize copy assignment (only to make it unavailable), with that ability one doesn't need any other language support.
and i think likewise for any other specific reasons one can think of: probably no such reason really requires the general ability, but the general ability is sufficient to cover it all, so it lowers the overall language complexity.
a good source to get more definitive answer than my hunches, recollections and gut feelings, is bjarne's "the design and evolution of c++" book.
probably the question has a definitive answer there.
Destruction of the old object, followed by copy construction of the new, will not usually work. And the swap idiom is guaranteed not to work unless the class provides a special swap function— std::swap uses assignment in its unspecialized implementation, and using it directly in the assignment operator will lead to endless recursion.
And of course, the user may want to do something special, e.g. make the assignment operator private, for example.
And finally, what is almost certainly an overruling reason: the default assignment operator has to be compatible with C.
Actually, after seeing juanchopanza's answer (which was deleted), I think I ended up figuring it out myself.
Copy-assignment operators allow classes like basic_string to avoid allocating resources unnecessarily when they can re-use them (in this case, memory).
So when you assign to a basic_string , an overloaded copy assignment operator would avoid allocating memory, and would just copy the string data directly to the existing buffer.
If the object had to be destroyed and constructed again, the buffer would have to be reallocated, which would be potentially much more costly for a small string.
(Note that vector could benefit from this too, but only if it knew that the elements' copy constructors would never throw exceptions. Otherwise it would need to maintain its exception safety and actually perform a copy-and-swap.)
It allows you to use assignment of other types as well. You could have a class Person with an assignment operator that assigns an ID.
But besides that, you don't always want to copy all the members as they are.
The default assignment only does a shallow copy. For example, if the class contains pointers, or locks, you dont always want to copy them from the other object. Usually when you have pointers you want to use a deep copy, and maybe create a copy of the object that the pointers are pointed to. And if you have locks, you want them to be specific to the object, and you don't want to copy their state from the other object.
It is actually a common practice to provide your own copy constructor and assignment operator if your class holds pointers as members.
I have used it often as a conversion constructor but with already existing objects. i.e assigning member variable type, etc to an object.
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 .
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.
In C++, the compiler automatically provides a default assignment operator for classes. This operator performs a shallow copy of each member of the class from one object to another. This means that if we don’t explicitly overload the assignment operator, the compiler will still allow us to assign one object to another using the assignment operator ( = ), and it won’t generate an error.
So, when we should perform assignment operator overloading? when our class involves dynamic memory allocation (e.g., pointers) and we need to perform a deep copy to prevent issues like double deletion or data corruption.
here, a and b are of type integer, which is a built-in data type. Assignment Operator can be used directly on built-in data types.
c1 and c2 are variables of type “class C”.
The above example can be done by implementing methods or functions inside the class, but we choose operator overloading instead. The reason for this is, operator overloading gives the functionality to use the operator directly which makes code easy to understand, and even code size decreases because of it. Also, operator overloading does not affect the normal working of the operator but provides extra functionality to it.
Now, if the user wants to use the assignment operator “=” to assign the value of the class variable to another class variable then the user has to redefine the meaning of the assignment operator “=”. Redefining the meaning of operators really does not change their original meaning, instead, they have been given additional meaning along with their existing ones.
Also, always check if the object is not being assigned to itself (e.g., if (this != &other)), as assigning an object to itself does not make sense and may cause runtime issues.
While managing dynamic resources, the above approach of assignment overloading have few flaws and there is more efficient approach that is recommended. See this article for more info – Copy-and-Swap Idiom in C++
COMMENTS
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 ...
1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators. This operator first adds the current value of the variable on left to the value on the right and ...
The central component of an assignment statement is the assignment operator. This operator is represented by the = symbol, which separates two operands: ... Unlike expressions, assignment statements don't have a return value because their purpose is to make the association between the variable and its value.
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 ...
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.
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. -=.
The purpose of the assignment operator is to take the value from the right hand side of the operator ( the RHS value ), and store it in the variable on the left hand side ( the LHS ). Note the following examples: X = Y + 7; - Valid: The sum of Y plus 7 will be stored in the variable X.
An operator that changes the value of a modifiable data object. This page titled 4.5: Assignment Operator is shared under a license and was authored, remixed, and/or curated by () . The assignment operator allows us to change the value of a modifiable data object (for beginning programmers this typically means a variable).
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 ...
Python Assignment Operators. Assignment operators are used to assign values to variables: Operator. Example. Same As. Try it. =. x = 5. x = 5.
An assignment operator is the operator used to assign a new value to a variable, property, event or indexer element in C# programming language. Assignment operators can also be used for logical operations such as bitwise logical operations or operations on integral operands and Boolean operands. Unlike in C++, assignment operators in C# cannot ...
An assignment operator is used to replace the data of a previously initialized object with some other object's data. A& operator=(const A& rhs) {data_ = rhs.data_; return *this;} For example: A aa; A a; a = aa; // assignment operator You could replace copy construction by default construction plus assignment, but that would be less efficient.
Assignment Operator. Assignment Operators are used to assign values to variables. This operator is used to assign the value of the right side of the expression to the left side operand. Python. # Assigning values using # Assignment Operator a = 3 b = 5 c = a + b # Output print(c) Output. 8.
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;
Example 2: Assignment Operators # assign 10 to a a = 10 # assign 5 to b b = 5 # assign the sum of a and b to a a += b # a = a + b print(a) # Output: 15. Here, we have used the += operator to assign the sum of a and b to a. Similarly, we can use any other assignment operators as per our needs.
The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...
The assignment operator is to deal with an already existing object. The assignment operator is used to change an existing instance to have the same values as the rvalue, which means that the instance has to be destroyed and re-initialized if it has internal dynamic memory. Useful link : Copy Constructors, Assignment Operators, and More
In this article. 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.
21.12 — Overloading the assignment operator. Alex July 22, 2024. The copy assignment operator (operator=) is used to copy values from one object to another already existing object. As of C++11, C++ also supports "Move assignment". We discuss move assignment in lesson 22.3 -- Move constructors and move assignment.
Note: The compound assignment operator in Java performs implicit type casting. Let's consider a scenario where x is an int variable with a value of 5. int x = 5; If you want to add the double value 4.5 to the integer variable x and print its value, there are two methods to achieve this: Method 1: x = x + 4.5. Method 2: x += 4.5.
I'm trying to understand the purpose of overloading some operators in C++. Conceptually, an assignment statement can be easily implemented via: Destruction of the old object followed by copy construction of the new object. Copy construction of the new object, followed by a swap with the old object, followed by destruction of the old object.
Assignment operators are fundamental for updating variable values, especially in loops and mathematical computations, contributing to the dynamic nature of programming. ... The basic purpose of a Class is to identify the common attributes and behaviours and group them as an entity that can be reused again an. 2 min read. If-Then-___ Trio in ...
Overloading assignment operator in C++ copies all values of one object to another object. Only a non-static member function should be used to overload the assignment operator. In C++, the compiler automatically provides a default assignment operator for classes. This operator performs a shallow copy of each member of the class from one object ...