/ | ||||
(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 |
Time estimate: 45 min.
Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x . It is the same as x = x + 1 . This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound operators are written like += or =+ , just remember that the operation ( + ) is done first to produce the new value which is then assigned ( = ) back to the variable. So it’s operator then equal sign: += .
Since changing the value of a variable by one is especially common, there are two extra concise operators ++ and -- , also called the plus-plus or increment operator and minus-minus or decrement operator that set a variable to one greater or less than its current value.
Thus x++ is even more concise way to write x = x + 1 than the compound operator x += 1 . You’ll see this shortcut used a lot in loops when we get to them in Unit 4. Similarly, y-- is a more concise way to write y = y - 1 . These shortcuts only exist for + and - as they don’t really make sense for other operators.
If you’ve heard of the programming language C++, the name is an inside joke that C, an earlier language which C++ is based on, had been incremented or improved to create C++.
Here’s a table of all the compound arithmetic operators and the extra concise incremend and decrement operators and how they relate to fully written out assignment expressions. You can run the code below the table to see these shortcut operators in action!
Operator |
|
|
|
|
|
---|---|---|---|---|---|
Written out | = x + 1 | = x - 1 | = x * 2 | = x / 2 | = x % 2 |
Compound | += 1 | -= 1 | *= 2 | /= 2 | %= 2 |
Extra concise |
|
| |||
Run the code below to see what the ++ and shorcut operators do. Click on the Show Code Lens button to trace through the code and the variable values change in the visualizer. Try creating more compound assignment statements with shortcut operators and work with a partner to guess what they would print out before running the code.
If you look at real-world Java code, you may occassionally see the ++ and -- operators used before the name of the variable, like ++x rather than x++ . That is legal but not something that you will see on the AP exam.
Putting the operator before or after the variable only changes the value of the expression itself. If x is 10 and we write, System.out.println(x++) it will print 10 but aftewards x will be 11. On the other hand if we write, System.out.println(++x) , it will print 11 and afterwards the value will be 11.
In other words, with the operator after the variable name, (called the postfix operator) the value of the variable is changed after evaluating the variable to get its value. And with the operator before the variable (the prefix operator) the value of the variable in incremented before the variable is evaluated to get the value of the expression.
But the value of x after the expression is evaluated is the same in either case: one greater than what it was before. The -- operator works similarly.
The AP exam will never use the prefix form of these operators nor will it use the postfix operators in a context where the value of the expression matters.
1-5-2: What are the values of x, y, and z after the following code executes?
1-5-3: What are the values of x, y, and z after the following code executes?
Use paper and pencil or the question response area below to trace through the following program to determine the values of the variables at the end.
Code Tracing is a technique used to simulate a dry run through the code or pseudocode line by line by hand as if you are the computer executing the code. Tracing can be used for debugging or proving that your program runs correctly or for figuring out what the code actually does.
Trace tables can be used to track the values of variables as they change throughout a program. To trace through code, write down a variable in each column or row in a table and keep track of its value throughout the program. Some trace tables also keep track of the output and the line number you are currently tracing.
Trace through the following code:
1-5-4: Write your trace table for x, y, and z here showing their results after each line of code.
After doing this challenge, play the Operators Maze game . See if you and your partner can get the highest score!
Compound assignment operators ( += , -= , *= , /= , %= ) can be used in place of the assignment operator.
The increment operator ( ++ ) and decrement operator ( -- ) are used to add 1 or subtract 1 from the stored value of a variable. The new value is assigned to the variable.
The use of increment and decrement operators in prefix form (e.g., ++x ) and inside other expressions (i.e., arr[x++] ) is outside the scope of this course and the AP Exam.
Basics of c++.
std; main () { a, b; a = 10; b = 4; a = b; b = 7; cout << ; cout << a; cout << ; cout << b; } |
operator | description |
---|---|
addition | |
subtraction | |
multiplication | |
division | |
modulo |
expression | equivalent to... |
---|---|
std; main () { a, b=3; a = b; a+=2; cout << a; } |
Example 1 | Example 2 |
---|---|
operator | description |
---|---|
Equal to | |
Not equal to | |
Less than | |
Greater than | |
Less than or equal to | |
Greater than or equal to |
(5 > 4) (3 != 2) (6 >= 6) (5 < 5) |
(a*b >= c) (b+4 > a*c) ((b=2) == a) |
!(6 <= 4) ! ! |
&& OPERATOR (and) | ||
---|---|---|
|| OPERATOR (or) | ||
---|---|---|
( (5 == 5) || (3 > 6) ) |
operator | short-circuit |
---|---|
if the left-hand side expression is , the combined result is (the right-hand side expression is never evaluated). | |
if the left-hand side expression is , the combined result is (the right-hand side expression is never evaluated). |
( (i<10) && (++i<n) ) { } |
7==5+2 ? 4 : 3 5>3 ? a : b a>b ? a : b |
std; main () { a,b,c; a=2; b=7; c = (a>b) ? a : b; cout << c << ; } |
Bitwise operators ( &, |, ^, ~, <<, >> ).
operator | asm equivalent | description |
---|---|---|
Bitwise AND | ||
Bitwise inclusive OR | ||
Bitwise exclusive OR | ||
Unary complement (bit inversion) | ||
Shift bits left | ||
Shift bits right |
i; f = 3.14; i = ( ) f; |
(f); |
( ); |
Precedence of operators.
x = (5 + 7) % 2; |
Level | Precedence group | Operator | Description | Grouping |
---|---|---|---|---|
1 | Scope | scope qualifier | Left-to-right | |
2 | Postfix (unary) | postfix increment / decrement | Left-to-right | |
functional forms | ||||
subscript | ||||
member access | ||||
3 | Prefix (unary) | prefix increment / decrement | Right-to-left | |
bitwise NOT / logical NOT | ||||
unary prefix | ||||
reference / dereference | ||||
allocation / deallocation | ||||
parameter pack | ||||
) | C-style type-casting | |||
4 | Pointer-to-member | access pointer | Left-to-right | |
5 | Arithmetic: scaling | multiply, divide, modulo | Left-to-right | |
6 | Arithmetic: addition | addition, subtraction | Left-to-right | |
7 | Bitwise shift | shift left, shift right | Left-to-right | |
8 | Relational | comparison operators | Left-to-right | |
9 | Equality | equality / inequality | Left-to-right | |
10 | And | bitwise AND | Left-to-right | |
11 | Exclusive or | bitwise XOR | Left-to-right | |
12 | Inclusive or | bitwise OR | Left-to-right | |
13 | Conjunction | logical AND | Left-to-right | |
14 | Disjunction | logical OR | Left-to-right | |
15 | Assignment-level expressions | assignment / compound assignment | Right-to-left | |
conditional operator | ||||
16 | Sequencing | comma separator | Left-to-right |
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
In the realm of computer programming , specifically in the C programming language, understanding and utilising assignment operators effectively is essential for developing efficient and well-organised code. The assignment operator in C plays a fundamental role in assigning values to variables, and this introductory piece will elaborate on its definition, usage and importance. Gain insights on different types of assignment operators, such as compound assignment operators and the assignment operator for strings in C. As you delve deeper, practical examples of the assignment operator in C will be provided, enabling you to gain a firm grasp on the concept and apply this knowledge for successful programming endeavours.
The assignment operator in C is denoted with an equal sign (=) and is used to assign a value to a variable. The left operand is the variable, and the right operand is the value or expression to be assigned to that variable.
int main() { int x; x = 5; printf("The value of x is: %d", x); return 0; } ``` In this example, the assignment operator (=) assigns the value 5 to the variable x, which is then printed using the `printf()` function.
It is essential to understand basic usage and functionality of the assignment operator in C: - Variables must be declared before they can be assigned a value. - The data type on the right-hand side of the operator must be compatible with the data type of the variable on the left-hand side. Here are some more examples of using the assignment operator in C:
int a = 10; // Declare and assign in a single line float b = 3.14; char c = 'A';
Additionally, you can use the assignment operator with various arithmetic, relational, and logical operators:
`+=`: Add and assign
`-=`: Subtract and assign
`*=`: Multiply and assign
`/=`: Divide and assign
For example: int x = 5; x += 2; // Equivalent to x = x + 2; The value of x becomes 7
The assignment operator in C plays a crucial role in computer programming. Its significance includes:
- Initialization of variables: The assignment operator is used to give an initial value to a variable, as demonstrated in the earlier examples.
- Modification of variable values: It allows you to change the value of a variable throughout the program. For example, you can use the assignment operator to increment the value of a counter variable in a loop.
- Expressions: The assignment operator is often used in expressions, such as calculating and storing the result of an arithmetic operation.
Example: Using the assignment operator with arithmetic operations:
#include int main() { int a = 10, b = 20, sum; sum = a + b; printf("The sum of a and b is: %d", sum); return 0; }
In this example, the assignment operator is used to store the result of the arithmetic operation `a + b` in the variable `sum`.
In conclusion, the assignment operator in C is an essential tool for computer programming. Understanding its definition, usage, and importance will significantly improve your programming skills and enable you to create more efficient and effective code.
Compound assignment operators in c.
Compound assignment operators in C combine arithmetic, bit manipulation, or other operations with the basic assignment operator. This enables you to perform certain calculations and assignments of new values to variables in a single statement. Compound assignment operators are efficient, as they perform the operation and the assignment in one step rather than two separate steps. Let's examine the various compound assignment operators in C.
The addition assignment operator (+=) in C combines the addition operation with the assignment operator, allowing you to increment the value of a variable by a specified amount. It essentially means "add the value of the right-hand side of the operator to the value of the variable on the left-hand side and then assign the new value to the variable". The general syntax for the addition assignment operator in C is: variable += value;
Using the addition assignment operator has some advantages:
- Reduces the amount of code you need: It is more concise and easier to read.
- Increases efficiency: It is faster because it performs the operation and assignment in one step.
Here's an example of the addition assignment operator in C: #include int main() { int a = 5; a += 3; // Equivalent to a = a + 3; The value of a becomes 8 printf("The value of a after addition assignment: %d, a); return 0; }
Compound assignment operators also include subtraction (-=), multiplication (*=), division (/=), modulo (%=), and bitwise operations like AND (&=), OR (|=), and XOR (^=). Their usage is similar to the addition assignment operator in C.
In C programming, strings are arrays of characters, and dealing with strings requires a careful approach. Direct assignment of a string using the assignment operator (=) is not possible, because arrays cannot be assigned using this operator. To assign a string to a character array, you need to use specific functions provided by the C language or develop your own custom function. Here are two commonly used methods for assigning a string to a character array:
1. Using the `strcpy()` function:
In this example, the `strcpy()` function from the `string.h` library is used to copy the contents of the `source` string into the `destination` character array.
2. Custom assignment function:
In this example, a custom function called `assignString()` is created to assign strings. It iterates through the characters of the `source` string, assigns each character to the corresponding element in the `destination` character array, and stops when it encounters the null character ('\0') at the end of the source string. Understanding assignment operators in C and the various types of assignment operators can help you write more efficient and effective code. It also enables you to work effectively with different data types, including strings and arrays of characters, which are essential for creating powerful and dynamic software applications.
In this section, we will explore some practical examples of the assignment operator in C. Examples will cover simple assignments and discuss usage scenarios for compound assignment operators, as well as demonstrating the implementation of the assignment operator for strings in C.
Simple assignment operations in C involve assigning a single value to a variable. Here are some examples of simple assignment operations:
1. Assigning an integer value to a variable: int age = 25;
2. Assigning a floating-point value to a variable: float salary = 50000.75;
3. Assigning a character value to a variable: char grade = 'A';
4. Swapping the values of two variables:
In this swapping example, the assignment operator is used to temporarily store the value of one variable and then exchange the values of two variables.
Compound assignment operators in C provide shorthand ways of updating the values of variables with arithmetic, bitwise, or other operations. Here are some common usage scenarios for compound assignment operators:
1. Incrementing a counter variable in a loop: for(int i = 0; i < 10; i += 2) { printf("%d ", i); } Here, the addition assignment operator (+=) is used within a `for` loop to increment the counter variable `i` by 2 at each iteration.
2. Accumulating the sum of elements in an array: #include int main() { int array[] = {1, 2, 3, 4, 5}; int sum = 0; for (int i = 0; i < 5; i++) { sum += array[i]; // Equivalent to sum = sum + array[i]; } printf("Sum of array elements: %d", sum); return 0; } In this example, the addition assignment operator (+=) is used to accumulate the sum of the array elements.
3. Calculating the product of two numbers using bitwise operations:
I n this example, the bitwise AND operation is combined with the addition assignment operator (+=) along with bitwise shift and compound assignment operators to perform multiplication without using the arithmetic `*` operator.
As discussed earlier, assigning strings in C requires a different approach, as the assignment operator (=) cannot be used directly. Here are some practical examples that demonstrate how to implement the assignment operator for strings in C:
1. Using the `strcpy()` function from the `string.h` library:
2. Defining a custom function to assign strings, which takes two character pointers as arguments:
These examples showcase the implementation of the assignment operator for strings in C, enabling you to effectively manipulate and work with strings in your C programs. By using built-in C functions or defining your own custom functions, you can assign strings to character arrays, which allow you to perform various operations on strings, such as concatenation, comparison, substring search, and more.
Assignment Operator in C: represented by the equal sign (=), assigns a value to a variable
Compound assignment operators in C: combine arithmetic or bitwise operations with the assignment operator, such as +=, -=, and *=
Addition assignment operator in C: represented by (+=), adds a value to an existing variable and assigns the new value
Assignment operator for string in C : requires specific functions like strcpy() or custom functions, as direct assignment with = is not possible
Assignment Operator in C example: int x = 5; assigns the value 5 to the variable x
What symbol is used as the assignment operator in C programming?
An equal sign (=)
What is the syntax for the addition assignment operator in C?
variable += value;
What is the compound assignment operator for multiplication in C?
Why is direct assignment of a string using the assignment operator (=) not possible in C?
Arrays cannot be assigned using the assignment operator.
How can a string be assigned to a character array using the `strcpy()` function in C?
GetString(destination, source);
Which function or method can be used to assign a string to a character array in C programming?
Using the `strcpy()` function or a custom assignment function.
We have 14,000 flashcards about Dynamic Landscapes.
Already have an account? Log in
Test your knowledge with multiple choice flashcards.
Keep learning, you are doing great.
StudySmarter is a globally recognized educational technology company, offering a holistic learning platform designed for students of all ages and educational levels. Our platform provides learning support for a wide range of subjects, including STEM, Social Sciences, and Languages and also helps students to successfully master various tests and exams worldwide, such as GCSE, A Level, SAT, ACT, Abitur, and more. We offer an extensive library of learning materials, including interactive flashcards, comprehensive textbook solutions, and detailed explanations. The cutting-edge technology and tools we provide help students create their own learning materials. StudySmarter’s content is not only expert-verified but also regularly updated to ensure accuracy and relevance.
Team Assignment Operator in C Teachers
Create a free account to save this explanation..
Save explanations to your personalised space and access them anytime, anywhere!
By signing up, you agree to the Terms and Conditions and the Privacy Policy of StudySmarter.
Sign up to highlight and take notes. It’s 100% free.
The first learning app that truly has everything you need to ace your exams in one place
This chapter documents all the JavaScript language operators, expressions and keywords.
For an alphabetical listing see the sidebar on the left.
Basic keywords and general expressions in JavaScript. These expressions have the highest precedence (higher than operators ).
The this keyword refers to a special property of an execution context.
Basic null , boolean, number, and string literals.
Array initializer/literal syntax.
Object initializer/literal syntax.
The function keyword defines a function expression.
The class keyword defines a class expression.
The function* keyword defines a generator function expression.
The async function defines an async function expression.
The async function* keywords define an async generator function expression.
Regular expression literal syntax.
Template literal syntax.
Grouping operator.
Left values are the destination of an assignment.
Member operators provide access to a property or method of an object ( object.property and object["property"] ).
The optional chaining operator returns undefined instead of causing an error if a reference is nullish ( null or undefined ).
The new operator creates an instance of a constructor.
In constructors, new.target refers to the constructor that was invoked by new .
An object exposing context-specific metadata to a JavaScript module.
The super keyword calls the parent constructor or allows accessing properties of the parent object.
The import() syntax allows loading a module asynchronously and dynamically into a potentially non-module environment.
Postfix/prefix increment and postfix/prefix decrement operators.
Postfix increment operator.
Postfix decrement operator.
Prefix increment operator.
Prefix decrement operator.
A unary operation is an operation with only one operand.
The delete operator deletes a property from an object.
The void operator evaluates an expression and discards its return value.
The typeof operator determines the type of a given object.
The unary plus operator converts its operand to Number type.
The unary negation operator converts its operand to Number type and then negates it.
Bitwise NOT operator.
Logical NOT operator.
Pause and resume an async function and wait for the promise's fulfillment/rejection.
Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.
Exponentiation operator.
Multiplication operator.
Division operator.
Remainder operator.
Addition operator.
Subtraction operator.
A comparison operator compares its operands and returns a boolean value based on whether the comparison is true.
Less than operator.
Greater than operator.
Less than or equal operator.
Greater than or equal operator.
The instanceof operator determines whether an object is an instance of another object.
The in operator determines whether an object has a given property.
Note: => is not an operator, but the notation for Arrow functions .
The result of evaluating an equality operator is always of type boolean based on whether the comparison is true.
Equality operator.
Inequality operator.
Strict equality operator.
Strict inequality operator.
Operations to shift all bits of the operand.
Bitwise left shift operator.
Bitwise right shift operator.
Bitwise unsigned right shift operator.
Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.
Bitwise AND.
Bitwise OR.
Bitwise XOR.
Logical operators implement boolean (logical) values and have short-circuiting behavior.
Logical AND.
Logical OR.
Nullish Coalescing Operator.
The conditional operator returns one of two values based on the logical value of the condition.
An assignment operator assigns a value to its left operand based on the value of its right operand.
Assignment operator.
Multiplication assignment.
Division assignment.
Remainder assignment.
Addition assignment.
Subtraction assignment
Left shift assignment.
Right shift assignment.
Unsigned right shift assignment.
Bitwise AND assignment.
Bitwise XOR assignment.
Bitwise OR assignment.
Exponentiation assignment.
Logical AND assignment.
Logical OR assignment.
Nullish coalescing assignment.
Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.
Pause and resume a generator function.
Delegate to another generator function or iterable object.
Spread syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. In an object literal, the spread syntax enumerates the properties of an object and adds the key-value pairs to the object being created.
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
Specification |
---|
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
Learn C++ practically and Get Certified .
Popular examples, reference materials, learn c++ interactively, introduction to c++.
C++ Relational and Logical Operators
C++ Ternary Operator
C++ Bitwise Operators
C++ Operator Precedence and Associativity
Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction.
Operators in C++ can be classified into 6 types:
Arithmetic operators are used to perform arithmetic operations on variables and data. For example,
Here, the + operator is used to add two variables a and b . Similarly there are various other arithmetic operators in C++.
Operator | Operation |
---|---|
Addition | |
Subtraction | |
Multiplication | |
Division | |
Modulo Operation (Remainder after division) |
Here, the operators + , - and * compute addition, subtraction, and multiplication respectively as we might have expected.
/ Division Operator
Note the operation (a / b) in our program. The / operator is the division operator.
As we can see from the above example, if an integer is divided by another integer, we will get the quotient. However, if either divisor or dividend is a floating-point number, we will get the result in decimals.
% Modulo Operator
The modulo operator % computes the remainder. When a = 9 is divided by b = 4 , the remainder is 1 .
Note: The % operator can only be used with integers.
C++ also provides increment and decrement operators: ++ and -- respectively.
For example,
Here, the code ++num; increases the value of num by 1 .
In the above program, we have used the ++ and -- operators as prefixes (++a and --b) . However, we can also use these operators as postfix (a++ and b--) .
To learn more, visit increment and decrement operators .
In C++, assignment operators are used to assign values to variables. For example,
Here, we have assigned a value of 5 to the variable a .
Operator | Example | Equivalent to |
---|---|---|
3. c++ relational operators.
A relational operator is used to check the relationship between two operands. For example,
Here, > is a relational operator. It checks if a is greater than b or not.
If the relation is true , it returns 1 whereas if the relation is false , it returns 0 .
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 : Relational operators are used in decision-making and loops.
Logical operators are used to check whether an expression is true or false . If the expression is true , it returns 1 whereas if the expression is false , it returns 0 .
Operator | Example | Meaning |
---|---|---|
expression1 expression2 | Logical AND. True only if all the operands are true. | |
expression1 expression2 | Logical OR. True if at least one of the operands is true. | |
expression | Logical NOT. True only if the operand is false. |
In C++, logical operators are commonly used in decision making. To further understand the logical operators, let's see the following examples,
Explanation of logical operator program
In C++, bitwise operators are used to perform operations on individual bits. They can only be used alongside char and int data types.
Operator | Description |
---|---|
Binary AND | |
Binary OR | |
Binary XOR | |
Binary One's Complement | |
Binary Shift Left | |
Binary Shift Right |
To learn more, visit C++ bitwise operators .
Here's a list of some other common operators available in C++. We will learn about them in later tutorials.
Operator | Description | Example |
---|---|---|
returns the size of data type | ||
returns value based on the condition | ||
represents memory address of the operand | ||
accesses members of struct variables or class objects | ||
used with pointers to access the class or struct variables | ||
prints the output value | ||
gets the input value |
Sorry about that.
C++ Tutorial
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.
Precedence and associativity of operators in python.
Assignment operators in python.
In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators.
Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication , and division .
In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.
Operator | Description | Syntax |
---|---|---|
+ | Addition: adds two operands | x + y |
– | Subtraction: subtracts two operands | x – y |
* | Multiplication: multiplies two operands | x * y |
/ | Division (float): divides the first operand by the second | x / y |
// | Division (floor): divides the first operand by the second | x // y |
% | Modulus: returns the remainder when the first operand is divided by the second | x % y |
** | Power: Returns first raised to power second | x ** y |
Division operators.
In Python programming language Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient.
There are two types of division operators:
The quotient returned by this operator is always a float number, no matter if two numbers are integers. For example:
Example: The code performs division operations and prints the results. It demonstrates that both integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’ , and ‘-10/2’ results in ‘-5.0’ .
The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example:
Example: The code demonstrates integer (floor) division operations using the // in Python operators . It provides results as follows: ’10//3′ equals ‘3’ , ‘-5//2’ equals ‘-3’ , ‘ 5.0//2′ equals ‘2.0’ , and ‘-5.0//2’ equals ‘-3.0’ . Integer division returns the largest integer less than or equal to the division result.
The precedence of Arithmetic Operators in Python is as follows:
The modulus of Python operators helps us extract the last digit/s of a number. For example:
Here is an example showing how different Arithmetic Operators in Python work:
Example: The code performs basic arithmetic operations with the values of ‘a’ and ‘b’ . It adds (‘+’) , subtracts (‘-‘) , multiplies (‘*’) , computes the remainder (‘%’) , and raises a to the power of ‘b (**)’ . The results of these operations are printed.
Note: Refer to Differences between / and // for some interesting facts about these two Python operators.
In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.
Operator | Description | Syntax |
---|---|---|
> | Greater than: True if the left operand is greater than the right | x > y |
< | Less than: True if the left operand is less than the right | x < y |
== | Equal to: True if both operands are equal | x == y |
!= | Not equal to – True if operands are not equal | x != y |
>= | Greater than or equal to True if the left operand is greater than or equal to the right | x >= y |
<= | Less than or equal to True if the left operand is less than or equal to the right | x <= y |
= is an assignment operator and == comparison operator.
In Python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have the same precedence order.
Let’s see an example of Comparison Operators in Python.
Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python operators and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to, greater than, or equal to, and less than or equal to ‘b’ .
Python Logical operators perform Logical AND , Logical OR , and Logical NOT operations. It is used to combine conditional statements.
Operator | Description | Syntax |
---|---|---|
and | Logical AND: True if both the operands are true | x and y |
or | Logical OR: True if either of the operands is true | x or y |
not | Logical NOT: True if the operand is false | not x |
The precedence of Logical Operators in Python is as follows:
The following code shows how to implement Logical Operators in Python:
Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and ‘b’ are true ( ‘and’ ), if at least one of them is true ( ‘or’ ), and negates the value of ‘a’ using ‘not’ . The results are printed accordingly.
Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.
Operator | Description | Syntax |
---|---|---|
& | Bitwise AND | x & y |
| | Bitwise OR | x | y |
~ | Bitwise NOT | ~x |
^ | Bitwise XOR | x ^ y |
>> | Bitwise right shift | x>> |
<< | Bitwise left shift | x<< |
The precedence of Bitwise Operators in Python is as follows:
Here is an example showing how Bitwise Operators in Python work:
Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’ . It performs bitwise AND (&) , OR (|) , NOT (~) , XOR (^) , right shift (>>) , and left shift (<<) operations and prints the results. These operations manipulate the binary representations of the numbers.
Python Assignment operators are used to assign values to the variables.
Operator | Description | Syntax |
---|---|---|
= | Assign the value of the right side of the expression to the left side operand | x = y + z |
+= | Add AND: Add right-side operand with left-side operand and then assign to left operand | a+=b a=a+b |
-= | Subtract AND: Subtract right operand from left operand and then assign to left operand | a-=b a=a-b |
*= | Multiply AND: Multiply right operand with left operand and then assign to left operand | a*=b a=a*b |
/= | Divide AND: Divide left operand with right operand and then assign to left operand | a/=b a=a/b |
%= | Modulus AND: Takes modulus using left and right operands and assign the result to left operand | a%=b a=a%b |
//= | Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left operand | a//=b a=a//b |
**= | Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operand | a**=b a=a**b |
&= | Performs Bitwise AND on operands and assign value to left operand | a&=b a=a&b |
|= | Performs Bitwise OR on operands and assign value to left operand | a|=b a=a|b |
^= | Performs Bitwise xOR on operands and assign value to left operand | a^=b a=a^b |
>>= | Performs Bitwise right shift on operands and assign value to left operand | a>>=b a=a>>b |
<<= | Performs Bitwise left shift on operands and assign value to left operand | a <<= b a= a << b |
Let’s see an example of Assignment Operators in Python.
Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on ‘b’ . The results of each operation are printed, showing the impact of these operations on the value of ‘b’ .
In Python, is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical.
Let’s see an example of Identity Operators in Python.
Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’ ).
In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.
The following code shows how to implement Membership Operators in Python:
Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or not each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the printed messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.
in Python, Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5.
It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.
Syntax : [on_true] if [expression] else [on_false]
The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then uses a conditional assignment to determine the smaller of the two values and assigns it to the variable ‘min’ . Finally, it prints the value of ‘min’ , which is 10 in this case.
In Python, Operator precedence and associativity determine the priorities of the operator.
This is used in an expression with more than one operator with different precedence to determine which operation to perform first.
Let’s see an example of how Operator Precedence in Python works:
Example: The code first calculates and prints the value of the expression 10 + 20 * 30 , which is 610. Then, it checks a condition based on the values of the ‘name’ and ‘age’ variables. Since the name is “ Alex” and the condition is satisfied using the or operator, it prints “Hello! Welcome.”
If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.
The following code shows how Operator Associativity in Python works:
Example: The code showcases various mathematical operations. It calculates and prints the results of division and multiplication, addition and subtraction, subtraction within parentheses, and exponentiation. The code illustrates different mathematical calculations and their outcomes.
To try your knowledge of Python Operators, you can take out the quiz on Operators in Python .
Below are two Exercise Questions on Python Operators. We have covered arithmetic operators and comparison operators in these exercise questions. For more exercises on Python Operators visit the page mentioned below.
Q1. Code to implement basic arithmetic operations on integers
Q2. Code to implement Comparison operations on integers
Explore more Exercises: Practice Exercise on Operators in Python
Similar reads.
IMAGES
VIDEO
COMMENTS
The result of a compound-assignment operation has the value and type of the left operand. #define MASK 0xff00 n &= MASK; In this example, a bitwise-inclusive-AND operation is performed on n and MASK, and the result is assigned to n. The manifest constant MASK is defined with a #define preprocessor directive. See also. C Assignment Operators
Different types of assignment operators are shown below: 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 ...
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. -=.
Examples of compound assignment operators are: (Example: + =, - =, * =, / =,% =, & =, ^ =) Look at these two statements: x = 100; x = x + 5; Here in this example, adding 5 to the x variable in the second statement is again being assigned to the x variable. Compound Assignment Operators provide us with the C language to perform such operation ...
C supports a short variant of assignment operator called compound assignment or shorthand assignment. Shorthand assignment operator combines one of the arithmetic or bitwise operators with assignment operator. For example, consider following C statements. The above expression a = a + 2 is equivalent to a += 2.
Assignment and compound assignment operators are binary operators that modify the variable to their left using the value to their right. Operator Operator name Example Description Equivalent of = basic assignment a = b: a becomes equal to b: ... In C++, assignment operators are lvalue expressions, not so in C.
A special case scenario for all the compound assigned operators. int i= 2 ; i+= 2 * 2 ; //equals to, i = i+(2*2); In all the compound assignment operators, the expression on the right side of = is always calculated first and then the compound assignment operator will start its functioning. Hence in the last code, statement i+=2*2; is equal to i ...
Here are some more examples of using the assignment operator in C: int a = 10; // Declare and assign in a single line float b = 3.14; char c = 'A'; Additionally, you can use the assignment operator with various arithmetic, relational, and logical operators: `+=`: Add and assign. `-=`: Subtract and assign.
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 (+=): int x = 5; x += 10; Code language: C++ (cpp) The ...
Assignment Operators in C are used to assign values to the variables. The left side operand is called a variable and the right side operand is the value. The value on the right side of the "=" is assigned to the variable on the left side of "=". In this C tutorial, we'll understand the types of C programming assignment operators with examples.
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 ...
What your ancient compiler is doing is correctly following the C grammar rules and is grouping the expression as. a += (a += (a += 2)) But grouping is not the same as sequencing. From this point the behaviour is undefined. Your compiler appears to evaluate the above to. a += (a += 7) followed by. a += 14.
20. In modern C, or even moderately ancient C, += is a compound assignment operator, and =+ is parsed as two separate tokens. = and +. Punctuation tokens are allowed to be adjacent. So if you write: x += y; it's equivalent to. x = x + y; except that x is only evaluated once (which can matter if it's a more complicated expression).
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. it is equivalent to E1 = T{E2}
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:
1.5. Compound Assignment Operators¶. Compound assignment operators are shortcuts that do a math operation and assignment in one step. For example, x += 1 adds 1 to the current value of x and assigns the result back to x.It is the same as x = x + 1.This pattern is possible with any operator put in front of the = sign, as seen below. If you need a mnemonic to remember whether the compound ...
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.
Compound assignment operators modify the current value of a variable by performing an operation on it. They are equivalent to assigning the result of an operation to the first operand: ... Two expressions can be compared using relational and equality operators. For example, to know if two values are equal or if one is greater than the other ...
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 ...
In this video we are going to study about.. Assignment Operator in C Assignment Operator Example Use of Assignment Operator in CCompound Assignment Operato...
This is a list of operators in the C and C++ programming languages.All the operators (except typeof) listed exist in C++; the column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading.. When not overloaded, for the operators &&, ||, and , (the comma operator), there is a sequence point after the evaluation of the first operand.
Here are some more examples of using the assignment operator in C: int a = 10; // Declare and assign in a single line float b = 3.14; char c = 'A'; Additionally, you can use the assignment operator with various arithmetic, relational, and logical operators: `+=`: Add and assign. `-=`: Subtract and assign.
Basic keywords and general expressions in JavaScript. These expressions have the highest precedence (higher than operators ). The this keyword refers to a special property of an execution context. Basic null, boolean, number, and string literals. Array initializer/literal syntax. Object initializer/literal syntax.
C++ Operators. Operators are symbols that perform operations on variables and values. For example, + is an operator used for addition, while - is an operator used for subtraction. Operators in C++ can be classified into 6 types: Arithmetic Operators. Assignment Operators.
Level 1 - Oropouche Fever in the Americas June 2024. Level 2 - Chikungunya in Maldives May 2024. Level 1 - Global Measles May 2024. Level 2 - Global Polio May 2024. Level 1 - Meningococcal Disease in Saudi Arabia - Vaccine Requirements for Travel During the Hajj and Umrah Pilgrimages May 2024.
Assignment Operators in Python. Let's see an example of Assignment Operators in Python. Example: The code starts with 'a' and 'b' both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on 'b'.