/ | ||||
(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 |
Home » Learn C Programming from Scratch » C Assignment Operators
Summary : in this tutorial, you’ll learn about the C assignment operators and how to use them effectively.
An assignment operator assigns the vale of the right-hand operand to the left-hand operand. The following example uses the assignment operator (=) to assign 1 to the counter variable:
After the assignmment, the counter variable holds the number 1.
The following example adds 1 to the counter and assign the result to the counter:
The = assignment operator is called a simple assignment operator. It assigns the value of the left operand to the right operand.
Besides the simple assignment operator, C supports compound assignment operators. A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.
The following example uses a compound-assignment operator (+=):
The expression:
is equivalent to the following expression:
The following table illustrates the compound-assignment operators in C:
Operator | Operation Performed | Example | Equivalent expression |
---|---|---|---|
Multiplication assignment | x *= y | x = x * y | |
Division assignment | x /= y | x = x / y | |
Remainder assignment | x %= y | x = x % y | |
Addition assignment | x += y | x = x + y | |
Subtraction assignment | x -= y | x = x – y | |
Left-shift assignment | x <<= y | x = x <<=y | |
Right-shift assignment | x >>=y | x = x >>= y | |
Bitwise-AND assignment | x &= y | x = x & y | |
Bitwise-exclusive-OR assignment | x ^= y | x = x ^ y | |
Bitwise-inclusive-OR assignment | x |= y | x = x | y |
Last updated on July 27, 2020
We have already used the assignment operator ( = ) several times before. Let's discuss it here in detail. The assignment operator ( = ) is used to assign a value to the variable. Its general format is as follows:
The operand on the left side of the assignment operator must be a variable and operand on the right-hand side must be a constant, variable or expression. Here are some examples:
x = 18 // right operand is a constant y = x // right operand is a variable z = 1 * 12 + x // right operand is an expression |
The precedence of the assignment operator is lower than all the operators we have discussed so far and it associates from right to left.
We can also assign the same value to multiple variables at once.
here x , y and z are initialized to 100 .
Since the associativity of the assignment operator ( = ) is from right to left. The above expression is equivalent to the following:
Note that expressions like:
x = 18 y = x z = 1 * 12 + x |
are called assignment expression. If we put a semicolon( ; ) at the end of the expression like this:
x = 18; y = x; z = 1 * 12 + x; |
then the assignment expression becomes assignment statement.
Assignment operations that use the old value of a variable to compute its new value are called Compound Assignment.
Consider the following two statements:
x = 100; x = x + 5; |
Here the second statement adds 5 to the existing value of x . This value is then assigned back to x . Now, the new value of x is 105 .
To handle such operations more succinctly, C provides a special operator called Compound Assignment operator.
The general format of compound assignment operator is as follows:
where op can be any of the arithmetic operators ( + , - , * , / , % ). The above statement is functionally equivalent to the following:
Note : In addition to arithmetic operators, op can also be >> (right shift), << (left shift), | (Bitwise OR), & (Bitwise AND), ^ (Bitwise XOR). We haven't discussed these operators yet.
After evaluating the expression, the op operator is then applied to the result of the expression and the current value of the variable (on the RHS). The result of this operation is then assigned back to the variable (on the LHS). Let's take some examples: The statement:
is equivalent to x = x + 5; or x = x + (5); .
Similarly, the statement:
is equivalent to x = x * 2; or x = x * (2); .
Since, expression on the right side of op operator is evaluated first, the statement:
is equivalent to x = x * (y + 1) .
The precedence of compound assignment operators are same and they associate from right to left (see the precedence table ).
The following table lists some Compound assignment operators:
Operator | Description |
---|---|
equivalent to | |
equivalent to | |
equivalent to | |
equivalent to |
The following program demonstrates Compound assignment operators in action:
#include<stdio.h> int main(void) { int i = 10; char a = 'd'; printf("ASCII value of %c is %d\n", a, a); // print ASCII value of d a += 10; // increment a by 10; printf("ASCII value of %c is %d\n", a, a); // print ASCII value of n a *= 5; // multiple a by 5; printf("a = %d\n", a); a /= 4; // divide a by 4; printf("a = %d\n", a); a %= 2; // remainder of a % 2; printf("a = %d\n", a); a *= a + i; // is equivalent to a = a * (a + i) printf("a = %d\n", a); return 0; // return 0 to operating system } |
Expected Output:
ASCII value of d is 100 ASCII value of n is 110 a = 38 a = 9 a = 1 a = 11 |
Load Comments
Programtopia
In this Section, you will learn about Operators in C Programming (all valid operators available in C), expressions (combination of operators, variables and constants) and precedence of operators (which operator has higher priority and which operator has lower priority).
Operators are the symbols which tell the computer to execute certain mathematical or logical operations. A mathematical or logical expression is generally formed with the help of an operator. C programming offers a number of operators which are classified into 8 categories viz.
C programming language provides all basic arithmetic operators: +, -, *, / and %.
Note: ‘/’ is integer division which only gives integer part as result after division. ‘%’ is modulo division which gives the remainder of integer division as result.
Some examples of arithmetic operators are:
In these examples, a and b are variables and are called operands.
Note: ‘%’ cannot be used on floating data type.
Relational operators are used when we have to make comparisons. C programming offers 6 relational operators.
Relational expression is an expression which contains the relational operator. Relational operators are most commonly used in decision statements like if , while , etc. Some simple relational expressions are:
Note: Arithmetic operators have higher priority than relational operators meaning that if arithmetic expressions are present on two sides of a relational operator then arithmetic expressions will be calculated first and then the result will be compared.
Logical operators are used when more than one conditions are to be tested and based on that result, decisions have to be made. C programming offers three logical operators. They are:
For example:
An expression which combines two or more relational expressions is known as logical expression.
Note: Relative precedence of relational and logical operators are as follows
Highest precedence | ! |
> >= < <= | |
== != | |
&& | |
Lowest precedence | || |
Assignment operators are used to assign result of an expression to a variable. ‘=’ is the assignment operator in C. Furthermore, C also allows the use of shorthand assignment operators. Shorthand operators take the form:
where var is a variable, op is arithmetic operator, exp is an expression. In this case, ‘op=’ is known as shorthand assignment operator.
The above assignment
is the same as the assignment
Consider an example:
Here, the above statement means the same as
Note: Shorthand assignment can be used with all arithmetic operators.
C programming allows the use of ++ and – operators which are increment and decrement operators respectively. Both the increment and decrement operators are unary operators. The increment operator ++ adds 1 to the operand and the decrement operator – subtracts 1 from the operand. The general syntax of these operators are:
Increment Operator: m++ or ++m ;
Decrement Operator: m–or –m ;
In the example above, m++ simply means m=m+1; and m– simply means m=m-1;
Increment and decrement operators are mostly used in for and while loops.
++m and m++ performs the same operation when they form statements independently but they function differently when they are used in right hand side of an expression.
++m is known as prefix operator and m++ is known as postfix operator. A prefix operator firstly adds 1 to the operand and then the result is assigned to the variable on the left whereas a postfix operator firstly assigns value to the variable on the left and then increases the operand by 1. Same is in the case of decrement operator.
For example,
X=10; Y=++X;
In this case, the value of X and Y will be 6.
In this case, the value of Y will be 10 and the value of X will be 11.
The operator pair “?” and “:” is known as conditional operator. These pair of operators are ternary operators. The general syntax of conditional operator is:
This syntax can be understood as a substitute of if else statement.
Consider an if else statement as:
Now, this if else statement can be written by using conditional operator as:
In C programming, bitwise operators are used for testing the bits or shifting them left or right. The bitwise operators available in C are:
C programming supports special operators like comma operator, sizeof operator, pointer operators (& and *) and member selection operators (. and ->). The comma operator and sizeof operator are discussed in this section whereas the pointer and member selection operators are discussed in later sections.
The comma operator can be used to link the related expressions together. A comma linked expression is evaluated from left to right and the value of the right most expression is the value of the combined expression.
In this example, the expression is evaluated from left to right. So at first, variable a is assigned value 2, then variable b is assigned value 4 and then value 6 is assigned to the variable x. Comma operators are commonly used in for loops, while loops, while exchanging values, etc.
The sizeof operator is usually used with an operand which may be variable, constant or a data type qualifier. This operator returns the number of bytes the operand occupies. Sizeof operator is a compile time operator. Some examples of use of sizeof operator are:
The sizeof operator is usually used to determine the length of arrays and structures when their sizes are not known. It is also used in dynamic memory allocation.
Arithmetic expression in C is a combination of variables, constants and operators written in a proper syntax. C can easily handle any complex mathematical expressions but these mathematical expressions have to be written in a proper syntax. Some examples of mathematical expressions written in proper syntax of C are:
Note: C does not have any operator for exponentiation.
At first, the expressions within parenthesis are evaluated. If no parenthesis is present, then the arithmetic expression is evaluated from left to right. There are two priority levels of operators in C.
High priority: * / % Low priority: + –
The evaluation procedure of an arithmetic expression includes two left to right passes through the entire expression. In the first pass, the high priority operators are applied as they are encountered and in the second pass, low priority operations are applied as they are encountered.
Suppose, we have an arithmetic expression as:
This expression is evaluated in two left to right passes as:
But when parenthesis is used in the same expression, the order of evaluation gets changed.
When parentheses are present then the expression inside the parenthesis are evaluated first from left to right. The expression is now evaluated in three passes as:
Second Pass
There may even arise a case where nested parentheses are present (i.e. parenthesis inside parenthesis). In such case, the expression inside the innermost set of parentheses is evaluated first and then the outer parentheses are evaluated.
For example, we have an expression as:
The expression is now evaluated as:
First Pass:
Note: The number of evaluation steps is equal to the number of operators in the arithmetic expression.
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 .
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .
Submit and view feedback for
Next: if Statement , Up: Statements [ Contents ][ Index ]
The most common kind of statement in C is an expression statement . It consists of an expression followed by a semicolon. The expression’s value is discarded, so the expressions that are useful are those that have side effects: assignment expressions, increment and decrement expressions, and function calls. Here are examples of expression statements:
In very unusual circumstances we use an expression statement whose purpose is to get a fault if an address is invalid:
If the target of p is not declared volatile , the compiler might optimize away the memory access, since it knows that the value isn’t really used. See volatile .
C operators.
C control statements decision-making.
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples.
An operator in C can be defined as the symbol that helps us to perform some specific mathematical, relational, bitwise, conditional, or logical computations on values and variables. The values and variables used with operators are called operands. So we can say that the operators are the symbols that perform operations on operands.
For example,
Here, ‘+’ is the operator known as the addition operator, and ‘a’ and ‘b’ are operands. The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.
C language provides a wide range of operators that can be classified into 6 types based on their functionality:
The arithmetic operators are used to perform arithmetic/mathematical operations on operands. There are 9 arithmetic operators in C language:
S. No. | Symbol | Description | Syntax | |
---|---|---|---|---|
1 |
|
| Adds two numeric values. |
|
2 |
|
| Subtracts right operand from left operand. |
|
3 |
|
| Multiply two numeric values. |
|
4 |
|
| Divide two numeric values. |
|
5 |
|
| Returns the remainder after diving the left operand with the right operand. |
|
6 |
|
| Used to specify the positive values. |
|
7 |
|
| Flips the sign of the value. |
|
8 |
|
| Increases the value of the operand by 1. | a++ |
9 |
|
| Decreases the value of the operand by 1. | a– |
2. relational operators in c.
The relational operators in C are used for the comparison of the two operands. All these operators are binary operators that return true or false values as the result of comparison.
These are a total of 6 relational operators in C:
S. No. | Symbol | Description | Syntax | |
---|---|---|---|---|
1 |
| Returns true if the left operand is less than the right operand. Else false | ||
2 |
| Returns true if the left operand is greater than the right operand. Else false | ||
3 |
| Returns true if the left operand is less than or equal to the right operand. Else false | ||
4 |
| Returns true if the left operand is greater than or equal to right operand. Else false | ||
5 |
| Returns true if both the operands are equal. | ||
6 |
| Returns true if both the operands are NOT equal. |
Here, 0 means false and 1 means true.
Logical Operators are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. The result of the operation of a logical operator is a Boolean value either true or false .
S. No. | Symbol | Description | Syntax | |
---|---|---|---|---|
1 |
| Returns true if both the operands are true. |
| |
2 |
| Returns true if both or any of the operand is true. |
| |
3 |
| Returns true if the operand is false. |
|
4. bitwise operators in c.
The Bitwise operators are used to perform bit-level operations on the operands. The operators are first converted to bit-level and then the calculation is performed on the operands. Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at the bit level for faster processing.
There are 6 bitwise operators in C:
S. No. | Symbol | Description | Syntax | |
---|---|---|---|---|
1 |
| Performs bit-by-bit AND operation and returns the result. | ||
2 |
| Performs bit-by-bit OR operation and returns the result. | ||
3 |
| Performs bit-by-bit XOR operation and returns the result. | ||
4 |
| Flips all the set and unset bits on the number. | ||
5 |
| Shifts the number in binary form by one place in the operation and returns the result. | ||
6 |
| Shifts the number in binary form by one place in the operation and returns the result. |
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 an error.
The assignment operators can be combined with some other operators in C to provide multiple operations using single operator. These operators are called compound operators.
In C, there are 11 assignment operators :
S. No. | Symbol | Description | Syntax | |
---|---|---|---|---|
1 |
| Assign the value of the right operand to the left operand. |
| |
2 |
| Add the right operand and left operand and assign this value to the left operand. |
| |
3 |
| Subtract the right operand and left operand and assign this value to the left operand. |
| |
4 |
| Multiply the right operand and left operand and assign this value to the left operand. |
| |
5 |
| Divide the left operand with the right operand and assign this value to the left operand. |
| |
6 |
| Assign the remainder in the division of left operand with the right operand to the left operand. |
| |
7 |
| Performs bitwise AND and assigns this value to the left operand. |
| |
8 |
| Performs bitwise OR and assigns this value to the left operand. |
| |
9 |
| Performs bitwise XOR and assigns this value to the left operand. |
| |
10 |
| Performs bitwise Rightshift and assign this value to the left operand. |
| |
11 |
| Performs bitwise Leftshift and assign this value to the left operand. |
|
6. other operators.
Apart from the above operators, there are some other operators available in C used to perform some specific tasks. Some of them are discussed here:
To know more about the topic refer to this article.
To know more about dot operators refer to this article and to know more about arrow(->) operators refer to this article.
Unary, binary and ternary operators in c.
Operators can also be classified into three types on the basis of the number of operands they work on:
In C, it is very common for an expression or statement to have multiple operators and in these expression, there should be a fixed order or priority of operator evaluation to avoid ambiguity.
Operator Precedence and Associativity is the concept that decides which operator will be evaluated first in the case when there are multiple operators present in an expression.
The below table describes the precedence order and associativity of operators in C. The precedence of the operator decreases from top to bottom.
Precedence | Operator | Description | Associativity |
---|---|---|---|
1 |
| Parentheses (function call) | left-to-right |
| Brackets (array subscript) | left-to-right | |
| Member selection via object name | left-to-right | |
| Member selection via a pointer | left-to-right | |
| Postfix increment/decrement (a is a variable) | left-to-right | |
2 |
| Prefix increment/decrement (a is a variable) | right-to-left |
| Unary plus/minus | right-to-left | |
| Logical negation/bitwise complement | right-to-left | |
| Cast (convert value to temporary value of type) | right-to-left | |
| Dereference | right-to-left | |
| Address (of operand) | right-to-left | |
| Determine size in bytes on this implementation | right-to-left | |
3 |
| Multiplication/division/modulus | left-to-right |
4 |
| Addition/subtraction | left-to-right |
5 |
| Bitwise shift left, Bitwise shift right | left-to-right |
6 |
| Relational less than/less than or equal to | left-to-right |
| Relational greater than/greater than or equal to | left-to-right | |
7 |
| Relational is equal to/is not equal to | left-to-right |
8 |
| Bitwise AND | left-to-right |
9 |
| Bitwise XOR | left-to-right |
10 |
| Bitwise OR | left-to-right |
11 |
| Logical AND | left-to-right |
12 |
| Logical OR | left-to-right |
13 |
| Ternary conditional | right-to-left |
14 |
| Assignment | right-to-left |
| Addition/subtraction assignment | right-to-left | |
| Multiplication/division assignment | right-to-left | |
| Modulus/bitwise AND assignment | right-to-left | |
| Bitwise exclusive/inclusive OR assignment | right-to-left | |
| Bitwise shift left/right assignment | right-to-left | |
15 |
| expression separator | left-to-right |
To know more about operator precedence and associativity, refer to this article – Operator Precedence and Associativity in C
In this article, the points we learned about the operator are as follows:
Q1. what are operators in c.
Operators in C are certain symbols in C used for performing certain mathematical, relational, bitwise, conditional, or logical operations for the user.
There are 7 types of operators in C as mentioned below: Unary operator Arithmetic operator Relational operator Logical operator Bitwise operator Assignment operator Conditional operator
‘=’ is a type of assignment operator that places the value in right to the variable on left, Whereas ‘==’ is a type of relational operator that is used to compare two elements if the elements are equal or not.
In prefix operations, the value of a variable is incremented/decremented first and then the new value is used in the operation, whereas, in postfix operations first the value of the variable is used in the operation and then the value is incremented/decremented. Example: b=c=10; a=b++; // a==10 a=++c; // a==11
The Modulo operator(%) is used to find the remainder if one element is divided by another. Example: a % b (a divided by b) 5 % 2 == 1
Similar reads.
What is an assignment operator in c.
Assignment Operators in C are used to assign values to the variables. They come under the category of binary operators as they require two operands to operate upon. 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 "=". The value on the right side must be of the same data type as the variable on the left side. Hence, the associativity is from right to left.
In this C tutorial , we'll understand the types of C programming assignment operators with examples. To delve deeper you can enroll in our C Programming Course .
Before going in-depth about assignment operators you must know about operators in C. If you haven't visited the Operators in C tutorial, refer to Operators in C: Types of Operators .
There are two types of assignment operators in C:
+= | addition assignment | It adds the right operand to the left operand and assigns the result to the left operand. |
-= | subtraction assignment | It subtracts the right operand from the left operand and assigns the result to the left operand. |
*= | multiplication assignment | It multiplies the right operand with the left operand and assigns the result to the left operand |
/= | division assignment | It divides the left operand with the right operand and assigns the result to the left operand. |
%= | modulo assignment | It takes modulus using two operands and assigns the result to the left operand. |
There can be five combinations of bitwise operators with the assignment operator, "=". Let's look at them one by one.
&= | bitwise AND assignment | It performs the bitwise AND operation on the variable with the value on the right |
|= | bitwise OR assignment | It performs the bitwise OR operation on the variable with the value on the right |
^= | bitwise XOR assignment | It performs the bitwise XOR operation on the variable with the value on the right |
<<= | bitwise left shift assignment | Shifts the bits of the variable to the left by the value on the right |
>>= | bitwise right shift assignment | Shifts the bits of the variable to the right by the value on the right |
Practice problems on assignment operators in c, 1. what will the value of "x" be after the execution of the following code.
The correct answer is 52. x starts at 50, increases by 5 to 55, then decreases by 3 to 52.
The correct answer is 144. After right-shifting 73 (binary 1001001) by one and then left-shifting the result by two, the value becomes 144 (binary 10010000).
While performing arithmetic operations with the same variable, use compound assignment operators
When mixing assignments with other operations, use parentheses to ensure the correct order of evaluation.
Angular Certification Course | Jun 16 | SAT, SUN | Filling Fast | ||
Advanced Full-Stack .NET Developer Certification Training | Jun 17 | MON, WED, FRI | Filling Fast | ||
ASP.NET Core Certification Training | Jun 17 | MON, WED, FRI | Filling Fast | ||
.NET Microservices Certification Training | Jun 23 | SAT, SUN | Filling Fast | ||
ASP.NET Core (Project) | Jun 23 | SAT, SUN | Filling Fast | ||
Azure Developer Certification Training | Jun 23 | SAT, SUN | Filling Fast | ||
React JS Certification Training | Best React Training Course | Jun 30 | SAT, SUN | Filling Fast | ||
ASP.NET Core Certification Training | Jun 30 | SAT, SUN | Filling Fast | ||
Advanced Full-Stack .NET Developer Certification Training | Jun 30 | SAT, SUN | Filling Fast | ||
Generative AI For Software Developers | Jul 14 | SAT, SUN | Filling Fast |
Can't find convenient schedule? Let us know
We use cookies to make interactions with our websites and services easy and meaningful. Please read our Privacy Policy for more details.
Learn C practically and Get Certified .
Popular examples, reference materials, learn c interactively, c introduction.
C flow control.
C if...else Statement
C Precedence And Associativity Of Operators
Bitwise Operators in C Programming
An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition.
C has a wide range of operators to perform various operations.
An arithmetic operator performs mathematical operations such as addition, subtraction, multiplication, division etc on numerical values (constants and variables).
Operator | Meaning of Operator |
---|---|
+ | addition or unary plus |
- | subtraction or unary minus |
* | multiplication |
/ | division |
% | remainder after division (modulo division) |
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 program.
It is because both the variables a and b are integers. Hence, the output is also an integer. The compiler neglects the term after the decimal point and shows answer 2 instead of 2.25 .
The modulo operator % computes the remainder. When a=9 is divided by b=4 , the remainder is 1 . The % operator can only be used with integers.
Suppose a = 5.0 , b = 2.0 , c = 5 and d = 2 . Then in C programming,
C programming has two operators increment ++ and decrement -- to change the value of an operand (constant or variable) by 1.
Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1. These two operators are unary operators, meaning they only operate on a single operand.
Here, the operators ++ and -- are used as prefixes. These two operators can also be used as postfixes like a++ and a-- . Visit this page to learn more about how increment and decrement operators work when used as postfix .
An assignment operator is used for assigning a value to a variable. The most common assignment operator is =
Operator | Example | Same as |
---|---|---|
= | a = b | a = b |
+= | a += b | a = a+b |
-= | a -= b | a = a-b |
*= | a *= b | a = a*b |
/= | a /= b | a = a/b |
%= | a %= b | a = a%b |
C relational operators.
A relational operator checks the relationship between two operands. If the relation is true, it returns 1; if the relation is false, it returns value 0.
Relational operators are used in decision making and loops .
Operator | Meaning of Operator | Example |
---|---|---|
== | Equal to | is evaluated to 0 |
> | Greater than | is evaluated to 1 |
< | Less than | is evaluated to 0 |
!= | Not equal to | is evaluated to 1 |
>= | Greater than or equal to | is evaluated to 1 |
<= | Less than or equal to | is evaluated to 0 |
C logical operators.
An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming .
Operator | Meaning | Example |
---|---|---|
&& | Logical AND. True only if all operands are true | If c = 5 and d = 2 then, expression equals to 0. |
|| | Logical OR. True only if either one operand is true | If c = 5 and d = 2 then, expression equals to 1. |
! | Logical NOT. True only if the operand is 0 | If c = 5 then, expression equals to 0. |
Explanation of logical operator program
During computation, mathematical operations like: addition, subtraction, multiplication, division, etc are converted to bit-level which makes processing faster and saves power.
Bitwise operators are used in C programming to perform bit-level operations.
Operators | Meaning of operators |
---|---|
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise exclusive OR |
~ | Bitwise complement |
<< | Shift left |
>> | Shift right |
Visit bitwise operator in C to learn more.
Comma operator.
Comma operators are used to link related expressions together. For example:
The sizeof is a unary operator that returns the size of data (constants, variables, array, structure, etc).
Other operators such as ternary operator ?: , reference operator & , dereference operator * and member selection operator -> will be discussed in later tutorials.
Sorry about that.
How to assign values to the variables? C provides an assignment operator for this purpose, assigning the value to a variable using assignment operator is known as an assignment statement in C.
The function of this operator is to assign the values or values in variables on right hand side of an expression to variables on the left hand side.
Variable = constant / variable/ expression;
The data type of the variable on left hand side should match the data type of constant/variable/expression on right hand side with a few exceptions where automatic type conversions are possible.
Examples of assignment statements,
b = c ; /* b is assigned the value of c */ a = 9 ; /* a is assigned the value 9*/ b = c+5; /* b is assigned the value of expr c+5 */
The expression on the right hand side of the assignment statement can be:
An arithmetic expression; A relational expression; A logical expression; A mixed expression.
The above mentioned expressions are different in terms of the type of operators connecting the variables and constants on the right hand side of the variable. Arithmetic operators, relational
Arithmetic operators, relational operators and logical operators are discussed in the following sections.
For example, int a; float b,c ,avg, t; avg = (b+c) / 2; /*arithmetic expression */ a = b && c; /*logical expression*/ a = (b+c) && (b<c); /* mixed expression*/
Your email address will not be published. Required fields are marked *
Save my name, email, and website in this browser for the next time I comment.
Notify me of follow-up comments by email.
Notify me of new posts by email.
This site uses Akismet to reduce spam. Learn how your comment data is processed .
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.
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.
The above code shows compiler error:
Whereas the below code works fine.
Both look identical to me. What am I missing here?
They are not identical.
First of all, it makes zero sense to initialize an int array with a string literal, and in worst case, it may invoke undefined behavior , as pointer to integer conversion and the validity of the converted result thereafter is highly platform-specific behaviour. In this regard, both the snippets are invalid.
Then, correcting the data type, considering the char array is used,
In the first case,
is an assignment , which is not allowed with an array type as LHS of assignment.
is an initialization statement, which is perfectly valid statement.
Don't know how your second code is working (its not working in my case PLEASE TELL ME WHAT CAN BE THE REASON) it is saying: array of inappropriate type (int) initialized with string constant
Since you can't just assign a whole string to a integer variable. but you can assign a single character to a int variable like: int a[5]={'a','b','c','d','d'}
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 .
IMAGES
VIDEO
COMMENTS
1. This is an infinite loop. It first assign 10 to c, then compare it with c > 0, then again loop starts, assign 10 to c, compare it with c>0 and so on. Loop never ends. This is equivalent to the following: while(c=10); /* Because c assign a garbage value, but not true for all cases maybe it assign 0 */. while(c);
7 Assignment Expressions. As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues) because they are locations that hold a value. An assignment in C is an expression because it has a value; we call it an assignment expression.
An assignment expression has the value of the left operand after the assignment. It's to allow things like this: a = b = c; (although there's some debate as to whether code like that is a good thing or not.) Incidentally, this behaviour is replicated in Java (and I would bet that it's the same in C# too). edited Feb 20, 2017 at 8:59.
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 ...
The assignment operators in C can both transform and assign values in a single operation. C provides the following assignment operators: | =. In assignment, the type of the right-hand value is converted to the type of the left-hand value, and the value is stored in the left operand after the assignment has taken place.
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 ...
Assignment Operators in C - In C language, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable, or an expression. ... In C, the expressions that refer to a memory location are called "lvalue" expressions. A lvalue may appear as ...
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}
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 ...
Let's discuss it here in detail. The assignment operator ( = ) is used to assign a value to the variable. Its general format is as follows: variable = right_side. The operand on the left side of the assignment operator must be a variable and operand on the right-hand side must be a constant, variable or expression.
In C, the order of computing parts of an expression is not fixed. Aside from a few special cases, the operations can be computed in any order. If one part of the expression has an assignment to x and another part of the expression uses x, the result is unpredictable because that use might be computed before or after the assignment.
Assignment operators are used to assign result of an expression to a variable. '=' is the assignment operator in C. Furthermore, C also allows the use of shorthand assignment operators. Shorthand operators take the form: ... C Expressions. Arithmetic expression in C is a combination of variables, constants and operators written in a proper ...
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 ...
19.1 Expression Statement. The most common kind of statement in C is an expression statement.It consists of an expression followed by a semicolon. The expression's value is discarded, so the expressions that are useful are those that have side effects: assignment expressions, increment and decrement expressions, and function calls.
Operators are symbols used for performing some kind of operation in C. There are six types of operators, Arithmetic Operators, Relational Operators, Logical Operators, Bitwise Operators, Assignment Operators, and Miscellaneous Operators. Operators can also be of type unary, binary, and ternary according to the number of operators they are using.
0. Roughly speaking, in C; A statement is a section of code that produces an observable effect; An expression is a code construct which accesses at least one data item, performs some operation of the result of that access (or those accesses), and produces at least one result. An expression may be composed of (smaller) expressions.
There are two types of assignment operators in C: 1. Simple Assignment Operator (=) This assigns the value on the right-hand side (RHS) to the variable on the left-hand side (LHS). You can use a literal, another variable, or an expression in the assignment statement.
An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition. In this tutorial, you will learn about different C operators such as arithmetic, increment, assignment, relational, logical, etc. with the help of examples.
All assignment expressions exist in C and C++ and can be overloaded in C++. For the given operators the semantic of the built-in combined assignment expression a ⊚= b is equivalent to a = a ⊚ b, except that a is evaluated only once. Operator name Syntax C++ prototype examples As member of K
C provides an assignment operator for this purpose, assigning the value to a variable using assignment operator is known as an assignment statement in C. The function of this operator is to assign the values or values in variables on right hand side of an expression to variables on the left hand side. The syntax of the assignment expression
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.
It modifies the length of the value stored. With %f you are attempting to store a 32-bit floating point number in a 64-bit variable. Since the sign-bit, biased exponent and mantissa are encoded in different bits depending on the size, using %f to attempt to store a double always fails` (e.g. the sign-bit is still the MSB for both, but e.g. a float has an 8-bit exponent, while a double has 11 ...
Microsoft Forms is a web-based application that allows you to: Create and share online surveys, quizzes, polls, and forms. Collect feedback, measure satisfaction, test knowledge, and more. Easily design your forms with various question types, themes, and branching logic. Analyze your results with built-in charts and reports, or export them to ...
Then, correcting the data type, considering the char array is used, In the first case, arr = "Hello"; is an assignment, which is not allowed with an array type as LHS of assignment. OTOH, char arr[10] = "Hello"; is an initialization statement, which is perfectly valid statement. edited Oct 28, 2022 at 14:48. knittl.