This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

C++ built-in operators, precedence, and associativity

  • 8 contributors

The C++ language includes all C operators and adds several new operators. Operators specify an evaluation to be performed on one or more operands.

Precedence and associativity

Operator precedence specifies the order of operations in expressions that contain more than one operator. Operator associativity specifies whether, in an expression that contains multiple operators with the same precedence, an operand is grouped with the one on its left or the one on its right.

Alternative spellings

C++ specifies alternative spellings for some operators. In C, the alternative spellings are provided as macros in the <iso646.h> header. In C++, these alternatives are keywords, and use of <iso646.h> or the C++ equivalent <ciso646> is deprecated. In Microsoft C++, the /permissive- or /Za compiler option is required to enable the alternative spellings.

C++ operator precedence and associativity table

The following table shows the precedence and associativity of C++ operators (from highest to lowest precedence). Operators with the same precedence number have equal precedence unless another relationship is explicitly forced by parentheses.

Operator Description Operator Alternative
or
or

Operator overloading

Was this page helpful?

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

Additional resources

Learn C++ practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c++ interactively, introduction to c++.

  • Getting Started With C++
  • Your First C++ Program
  • C++ Comments

C++ Fundamentals

  • C++ Keywords and Identifiers
  • C++ Variables, Literals and Constants
  • C++ Data Types
  • C++ Type Modifiers
  • C++ Constants
  • C++ Basic Input/Output

C++ Operators

Flow Control

C++ Relational and Logical Operators

  • C++ if, if...else and Nested if...else
  • C++ for Loop
  • C++ while and do...while Loop
  • C++ break Statement
  • C++ continue Statement
  • C++ goto Statement
  • C++ switch..case Statement
  • C++ Ternary Operator
  • C++ Functions
  • C++ Programming Default Arguments
  • C++ Function Overloading
  • C++ Inline Functions
  • C++ Recursion

Arrays and Strings

  • C++ Array to Function
  • C++ Multidimensional Arrays
  • C++ String Class

Pointers and References

  • C++ Pointers
  • C++ Pointers and Arrays
  • C++ References: Using Pointers
  • C++ Call by Reference: Using pointers
  • C++ Memory Management: new and delete

Structures and Enumerations

  • C++ Structures
  • C++ Structure and Function

C++ Pointers to Structure

  • C++ Enumeration

Object Oriented Programming

  • C++ Classes and Objects
  • C++ Constructors
  • C++ Constructor Overloading
  • C++ Destructors
  • C++ Access Modifiers
  • C++ Encapsulation
  • C++ friend Function and friend Classes

Inheritance & Polymorphism

  • C++ Inheritance
  • C++ Public, Protected and Private Inheritance
  • C++ Multiple, Multilevel and Hierarchical Inheritance
  • C++ Function Overriding
  • C++ Virtual Functions
  • C++ Abstract Class and Pure Virtual Function

STL - Vector, Queue & Stack

  • C++ Standard Template Library
  • C++ STL Containers
  • C++ std::array
  • C++ Vectors
  • C++ Forward List
  • C++ Priority Queue

STL - Map & Set

  • C++ Multimap
  • C++ Multiset
  • C++ Unordered Map
  • C++ Unordered Set
  • C++ Unordered Multiset
  • C++ Unordered Multimap

STL - Iterators & Algorithms

  • C++ Iterators
  • C++ Algorithm
  • C++ Functor

Additional Topics

  • C++ Exceptions Handling
  • C++ File Handling
  • C++ Ranged for Loop
  • C++ Nested Loop
  • C++ Function Template
  • C++ Class Templates
  • C++ Type Conversion
  • C++ Type Conversion Operators
  • C++ Operator Overloading

Advanced Topics

  • C++ Namespaces
  • C++ Preprocessors and Macros
  • C++ Storage Class

C++ Bitwise Operators

  • C++ Buffers
  • C++ istream
  • C++ ostream

C++ Tutorials

C++ operator precedence and associativity.

  • C++ Operators Precedence

If there are multiple operators in a single expression, the operations are not evaluated simultaneously. Rather, operators with higher precedence have their operations evaluated first.

Let us consider an example:

Here, the multiplication operator * is of higher level precedence than the subtraction operator - . Hence, 17 * 6 is evaluated first.

As a result, the above expression is equivalent to

If we wish to evaluate 5 - 17 first, then we must enclose them within parentheses :

Example 1: Operators Precedence

Note: Because there are a lot of operators in C++ with multiple levels of precedence, it is highly recommended that we use parentheses to make our code more readable.

C++ Operators Precedence Table

The following table (taken from cppreference.com ) shows the precedence of C++ operators. Precedence Level 1 signifies operators of highest priority, while Precedence Level 17 signifies operators of the lowest priority.

The property of associativity will be discussed shortly.

Precedence Operator Description Associativity
1 :: Scope Resolution Left to Right
2 a++
a--
type( )
type{ }
a( )
a[ ]
.
->
Suffix/postfix increment
Suffix/postfix decrement
Function cast
Function cast
Function call
Subscript
Member access from an object
Member access from object ptr
Left to Right
3 ++a
--a
+a
-a
!
~
(type)
*a
&a
sizeof
co_await
new new[ ]
delete delete[]
Prefix increment
Prefix decrement
Unary plus
Unary minus
Logical NOT
Bitwise NOT
C style cast
Indirection (dereference)
Address-of
Size-of
await-expression
Dynamic memory allocation
Dynamic memory deallocation
Right to Left
4 .*
->*
Member object selector
Member pointer selector
Left to Right
5 a * b
a / b
a % b
Multiplication
Division
Modulus
Left to Right
6 a + b
a - b
Addition
Subtraction
Left to Right
7 <<
>>
Bitwise left shift
Bitwise right shift
Left to Right
8 <=< Three-way comparison operator Left to Right
9 <
<=
>
>=
Less than
Less than or equal to
Greater than
Greater than or equal to
Left to Right
10 ==
!=
Equal to
Not equal to
Left to Right
11 & Bitwise AND Left to Right
12 ^ Bitwise XOR Left to Right
13 | Bitwise OR Left to Right
14 && Logical AND Left to Right
15 || Logical OR Left to Right
16 a ? b : c
throw
co_yield
=
+=
-=
*=
/=
%=
<<=
>>=
&=
^=
|=
Ternary Conditional
throw operator
yield expression (C++ 20)
Assignment
Addition Assignment
Subtraction Assignment
Multiplication Assignment
Division Assignment
Modulus Assignment
Bitwise Shift Left Assignment
Bitwise Shift Right Assignment
Bitwise AND Assignment
Bitwise XOR Assignment
Bitwise OR Assignment
Right to Left
17 , Comma operator Left to Right
  • C++ Operators Associativity

Operator associativity is the direction from which an expression is evaluated. For example,

Take a look at a = 4; statement. The associativity of the = operator is from right to left. Hence, the value of b is assigned to a , and not in the other direction.

Also, multiple operators can have the same level of precedence (as we can see from the above table). When multiple operators of the same precedence level are used in an expression, they are evaluated according to their associativity .

Both operators += and -= operators have the same precedence. Since the associativity of these operators is from right to left, here is how the last statement is evaluated.

  • a -= 6 is evaluated first. Hence, a will be -5
  • Then, b += -5 will be evaluated. Hence, b will be -1

Example 2: Operators Associativity

Table of contents.

  • Example: Operators Precedence
  • C++ Operators Precedence List
  • Example: Operators Associativity

Sorry about that.

Related Tutorials

C++ Tutorial

  • RecentChanges

Operator precedence determines how operators are parsed concerning each other. Operators with higher precedence become the operands of operators with lower precedence.

Precedence And Associativity

Consider an expression describable by the representation below, where both OP1 and OP2 are fill-in-the-blanks for OPerators.

The combination above has two possible interpretations:

Which one the language decides to adopt depends on the identity of OP1 and OP2 .

If OP1 and OP2 have different precedence levels (see the table below), the operator with the higher precedence goes first and associativity does not matter. Observe how multiplication has higher precedence than addition and executed first, even though addition is written first in the code.

Within operators of the same precedence, the language groups them by associativity . Left-associativity (left-to-right) means that it is interpreted as (a OP1 b) OP2 c , while right-associativity (right-to-left) means it is interpreted as a OP1 (b OP2 c) . Assignment operators are right-associative, so you can write:

with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5 — the return value of b = 5 , a.k.a. right operand of the assignment.

As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity.

Operators are first grouped by precedence, and then, for adjacent operators that have the same precedence, by associativity. So, when mixing division and exponentiation, the exponentiation always comes before the division. For example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2) .

For prefix unary operators, suppose we have the following pattern:

where OP1 is a prefix unary operator and OP2 is a binary operator. If OP1 has higher precedence than OP2 , then it would be grouped as (OP1 a) OP2 b ; otherwise, it would be OP1 (a OP2 b) .

If the unary operator is on the second operand:

Then the binary operator OP2 must have lower precedence than the unary operator OP1 for it to be grouped as a OP2 (OP1 b) . For example, the following is invalid:

Because + has higher precedence than yield , this would become (a + yield) 1 — but because yield is a reserved word in generator functions, this would be a syntax error. Luckily, most unary operators have higher precedence than binary operators and do not suffer from this pitfall.

If we have two prefix unary operators:

Then the unary operator closer to the operand, OP2 , must have higher precedence than OP1 for it to be grouped as OP1 (OP2 a) . It's possible to get it the other way and end up with (OP1 OP2) a :

Because await has higher precedence than yield , this would become (await yield) 1 , which is awaiting an identifier called yield , and a syntax error. Similarly, if you have new !A; , because ! has lower precedence than new , this would become (new !) A , which is obviously invalid. (This code looks nonsensical to write anyway, since !A always produces a boolean, not a constructor function.)

For postfix unary operators (namely, ++ and -- ), the same rules apply. Luckily, both operators have higher precedence than any binary operator, so the grouping is always what you would expect. Moreover, because ++ evaluates to a value , not a reference , you can't chain multiple increments together either, as you may do in C.

Operator precedence will be handled recursively . For example, consider this expression:

First, we group operators with different precedence by decreasing levels of precedence.

  • The ** operator has the highest precedence, so it's grouped first.
  • Looking around the ** expression, it has * on the right and + on the left. * has higher precedence, so it's grouped first. * and / have the same precedence, so we group them together for now.
  • Looking around the * / / expression grouped in 2, because + has higher precedence than >> , the former is grouped.

Within the * / / group, because they are both left-associative, the left operand would be grouped.

Note that operator precedence and associativity only affect the order of evaluation of operators (the implicit grouping), but not the order of evaluation of operands . The operands are always evaluated from left-to-right. The higher-precedence expressions are always evaluated first, and their results are then composed according to the order of operator precedence.

If you are familiar with binary trees, think about it as a post-order traversal .

After all operators have been properly grouped, the binary operators would form a binary tree. Evaluation starts from the outermost group — which is the operator with the lowest precedence ( / in this case). The left operand of this operator is first evaluated, which may be composed of higher-precedence operators (such as a call expression echo("left", 4) ). After the left operand has been evaluated, the right operand is evaluated in the same fashion. Therefore, all leaf nodes — the echo() calls — would be visited left-to-right, regardless of the precedence of operators joining them.

Short-circuiting

In the previous section, we said "the higher-precedence expressions are always evaluated first" — this is generally true, but it has to be amended with the acknowledgement of short-circuiting , in which case an operand may not be evaluated at all.

Short-circuiting is jargon for conditional evaluation. For example, in the expression a && (b + c) , if a is , then the sub-expression (b + c) will not even get evaluated, even if it is grouped and therefore has higher precedence than && . We could say that the logical AND operator ( && ) is "short-circuited". Along with logical AND, other short-circuited operators include logical OR ( || ), nullish coalescing ( ?? ), and optional chaining ( ?. ).

When evaluating a short-circuited operator, the left operand is always evaluated. The right operand will only be evaluated if the left operand cannot determine the result of the operation.

Note: The behavior of short-circuiting is baked in these operators. Other operators would always evaluate both operands, regardless if that's actually useful — for example, NaN * foo() will always call foo , even when the result would never be something other than NaN .

The previous model of a post-order traversal still stands. However, after the left subtree of a short-circuiting operator has been visited, the language will decide if the right operand needs to be evaluated. If not (for example, because the left operand of || is already truthy), the result is directly returned without visiting the right subtree.

Consider this case:

Only C() is evaluated, despite && having higher precedence. This does not mean that || has higher precedence in this case — it's exactly because (B() && A()) has higher precedence that causes it to be neglected as a whole. If it's re-arranged as:

Then the short-circuiting effect of && would only prevent C() from being evaluated, but because A() && C() as a whole is false , B() would still be evaluated.

However, note that short-circuiting does not change the final evaluation outcome. It only affects the evaluation of operands , not how operators are grouped — if evaluation of operands doesn't have side effects (for example, logging to the console, assigning to variables, throwing an error), short-circuiting would not be observable at all.

The assignment counterparts of these operators ( &&= , ||= , ??= ) are short-circuited as well. They are short-circuited in a way that the assignment does not happen at all.

The following table lists operators in order from highest precedence (18) to lowest precedence (1).

Several notes about the table:

  • Not all syntax included here are "operators" in the strict sense. For example, spread ... and arrow => are typically not regarded as operators. However, we still included them to show how tightly they bind compared to other operators/expressions.
  • The left operand of an exponentiation ** (precedence 13) cannot be one of the unary operators with precedence 14 without grouping, or there will be a SyntaxError . That means, although -1 ** 2 is technically unambiguous, the language requires you to use (-1) ** 2 instead.
  • The operands of nullish coalescing ?? (precedence 3) cannot be a logical OR || (precedence 3) or logical AND && (precedence 4). That means you have to write (a ?? b) || c or a ?? (b || c) , instead of a ?? b || c .
  • Some operators have certain operands that require expressions narrower than those produced by higher-precedence operators. For example, the right-hand side of member access . (precedence 17) must be an identifier instead of a grouped expression. The left-hand side of arrow => (precedence 2) must be an arguments list or a single identifier instead of some random expression.
  • Some operators have certain operands that accept expressions wider than those produced by higher-precedence operators. For example, the bracket-enclosed expression of bracket notation [ … ] (precedence 17) can be any expression, even comma (precedence 1) joined ones. These operators act as if that operand is "automatically grouped". In this case we will omit the associativity.
Precedence Operator type Associativity Individual operators
18 [Grouping](/~bremner/teaching/cs2613/books/mdn/Reference/Operators/Grouping) n/a
17 [Member Access](/~bremner/teaching/cs2613/books/mdn/Reference/Operators/Property_accessors) left-to-right
[Computed Member Access](/~bremner/teaching/cs2613/books/mdn/Reference/Operators/Property_accessors) n/a
[new](/~bremner/teaching/cs2613/books/mdn/Reference/Operators/new) (with argument list)
16 [new](/~bremner/teaching/cs2613/books/mdn/Reference/Operators/new) (without argument list) n/a
15 [Postfix Increment](/~bremner/teaching/cs2613/books/mdn/Reference/Operators) n/a
[Postfix Decrement](/~bremner/teaching/cs2613/books/mdn/Reference/Operators)
14 n/a
[Prefix Increment](/~bremner/teaching/cs2613/books/mdn/Reference/Operators)
[Prefix Decrement](/~bremner/teaching/cs2613/books/mdn/Reference/Operators)
[typeof](/~bremner/teaching/cs2613/books/mdn/Reference/Operators/typeof)
[void](/~bremner/teaching/cs2613/books/mdn/Reference/Operators/void)
[delete](/~bremner/teaching/cs2613/books/mdn/Reference/Operators/delete)
[await](/~bremner/teaching/cs2613/books/mdn/Reference/Operators/await)
13 right-to-left
12 left-to-right
11 left-to-right
10 left-to-right
9 left-to-right
[in](/~bremner/teaching/cs2613/books/mdn/Reference/Operators/in)
[instanceof](/~bremner/teaching/cs2613/books/mdn/Reference/Operators/instanceof)
8 left-to-right
7 left-to-right
6 left-to-right
5 left-to-right
4 left-to-right
3 left-to-right
2 right-to-left
right-to-left
(Groups on expressions after )
right-to-left
[yield](/~bremner/teaching/cs2613/books/mdn/Reference/Operators/yield) n/a
[yield*](/~bremner/teaching/cs2613/books/mdn/Reference/Operators/yield_star_)
1 left-to-right
  • BYJU'S GATE
  • GATE Study Material
  • GATE Notes For CSE
  • Introduction To C Programming
  • Operators In C

Operator Precedence and Associativity in C

The precedence of operators in C dictates the order in which the operators will be evolved in an expression. Associativity, on the other hand, defines the order in which the operators of the same precedence will be evaluated in an expression. Also, associativity can occur from either right to left or left to right.

GATE Rank Predictor

In this article, we will take a closer look at Operator Precedence and Associativity in C according to the GATE Syllabus for CSE (Computer Science Engineering) . Read ahead to know more.

Table of Contents

Operator Precedence

Operator associativity.

  • Summary Of Operator Precedence And Associativity In C
  • Some Important Points To Remember
  • Practice Problems On Operator Precedence And Associativity In C

Use of the Operator Precedence and Associativity in C

Precedence and Associativity are two of the characters that are used for operators in an expression for determining the order of sub-expressions when they do not have brackets.

Operator precedence helps us determine which of the operators in an expression must be evaluated first in case the expression consists of more than a single operator.

50 – 2 * 15 is going to yield 20. It is because it gets evaluated as 50 – (2 * 15), and not as (50 – 2) * 15. The reason here is that subtraction (-) has lower precedence as compared to multiplication (*).

We use associativity when two or more than two operators with the same precedence are present in the same expression.

The precedence of Division and Multiplication arithmetic operators is the same. So, let’s say we have an expression with us which is 6 * 3 / 20. The evaluation of this expression would be (6 * 3) / 20 because the associativity will be left to right for both the operators – multiplication and division. In a similar case, the calculation of 40 / 4 * 5 would be (40 / 4) * 5 because the associativity would be from right to left here as well.

Summary of Operator Precedence and Associativity in C

Here is how the operator precedence and associativity work in the C language:

. Direct member selection Left to right
-> Indirect member selection Left to right
[] Array element reference Left to right
() Functional call Left to right
~ Bitwise(1’s) complement Right to left
! Logical negation Right to left
Unary minus Right to left
+ Unary plus Right to left
Decrement Right to left
++ Increment Right to left
* Pointer reference Right to left
& Dereference (Address) Right to left
(type) Typecast (conversion) Right to left
sizeof Returns the size of an object Right to left
% Remainder Left to right
/ Divide Left to right
* Multiply Left to right
Binary minus (subtraction) Left to right
+ Binary plus (Addition) Left to right
>> Right shift Left to right
<< Left shift Left to right
> Greater than Left to right
< Less than Left to right
>= Greater than or equal Left to right
<= Less than or equal Left to right
== Equal to Left to right
!= Not equal to Left to right
^ Bitwise exclusive OR Left to right
& Bitwise AND Left to right
|| Logical OR Left to right
| Bitwise OR Left to right
?: Conditional Operator Right to left
&& Logical AND Left to right
, Separator of expressions Left to right
= Simple assignment Right to left
/= Assign quotient Right to left
*= Assign product Right to left
%= Assign remainder Right to left
-= Assign difference Right to left
+= Assign sum Right to left
|= Assign bitwise OR Right to left
^= Assign bitwise XOR Right to left
&= Assign bitwise AND Right to left
>>= Assign right shift Right to left
<<= Assign left shift Right to left

Some Important Points to Remember

1. We only use associativity when we have two or more operators that have the same precedence in an expression.

The point to note here is that associativity is not applicable when we are defining the order of evaluation of operands with different levels of precedence.

2. All the operators that have a similar level of precedence have the same associativity. It is very important, or else the compiler won’t be able to decide what order of evaluation must an expression follow when it has two operators with the same precedence but different associativity. For example, – and + have the very same associativity.

3. The associativity and precedence of prefix ++ and postfix ++ are very different from each other. Here, the precedence of prefix ++ is less as compared to the postfix ++. Thus, their associativity also turns out to be different. Here, the associativity of prefix ++ is from right to left, while the associativity of postfix ++ is from left to right.

4. We must use a comma (,) very carefully, as it has the least level of precedence among all the other operators present in an expression.

5. We don’t have chaining of comparison in the C programming language. The Python language treats the expressions such as x > y > z as x > y and y > z. No similar type of chaining occurs in the C program.

Practice Problems on Operator Precedence and Associativity in C

1. What would be the output/result obtained from this program?

int x = 5, y = 10;

z = x * 2 + y;

printf(“\n output = %d”, z);

Answer – C. 20

We can calculate the output of this code using the precedence table. According to this table, the precedence of the assignment operator ( – ) and the addition operator ( + ) is lower than that of the multiplication operator ( * ). Thus, multiplication will get evaluated first here.

Thus, z = x * 2 + y

z = 5 * 2 + 10

z = 10 + 10

2. What would be the output/result obtained from this program?

int x = 50, y = 5;

z = x / 2 + y;

Answer – B. 30

We can calculate the output of this code using the precedence table. According to this table, the precedence of the assignment operator ( – ) and the addition operator ( + ) is lower than that of the division operator ( / ). Thus, multiplication will get evaluated first here.

Thus, z = x / 2 + y

z = 50 / 2 + 5

3. What would be the output/result obtained from this program?

int x = 30, y = 12;

z = x * 2 / y;

Answer – A. 5

The evaluation of this expression would be (30 * 2) / 12 because the associativity will be left to right for both the operators – multiplication and division.

Thus, z = x * 2 / y

z = (30 * 2) / 12

z = 60 / 12

4. What would be the output/result obtained from this program?

int x = 80, y = 3;

z = x / 2 * y;

Answer – D. 120

The evaluation of this expression would be (80 / 2) * 3 because the associativity will be left to right for both the operators – multiplication and division.

Thus, z = x / 2 * y

z = (80 / 2) * 3

Which of the operators has higher precedence- the addition or subtraction?

The precedence of Addition and Subtraction arithmetic operators is the same. So, let’s say we have an expression with us which is 20 + 5 – 10. The evaluation of this expression would be (20 + 5) – 10 because the associativity will be left to right for both the operators – multiplication and division. In a similar case, the calculation of 25 – 10 would be 15 because the associativity would be from right to left here as well.

Which of the operators has higher precedence- the multiplication or division?

The precedence of Division and Multiplication arithmetic operators is the same. So, let’s say we have an expression with us which is 6 * 3 / 20. The evaluation of this expression would be (6 * 3) / 20 because the associativity will be left to right for both the operators – multiplication and division. In a similar case, the calculation of 40 / 4 * 5 would be (40 / 4) * 5 because the associativity would be from right to left here as well.

Keep learning and stay tuned to get the latest updates on  GATE Exam  along with  GATE Eligibility Criteria ,  GATE 2023 ,  GATE Admit Card ,  GATE Syllabus for CSE (Computer Science Engineering) ,  GATE CSE Notes ,  GATE CSE Question Paper , and more.

Also Explore,

  • Arithmetic Operators in C
  • Bitwise Operators in C
  • Increment and Decrement Operators in C
  • Logical Operators in C
  • Operators in C
  • Relational Operators in C
  • Comma Operator in C
GATE Related Links

Leave a Comment Cancel reply

Your Mobile number and Email id will not be published. Required fields are marked *

Request OTP on Voice Call

Post My Comment

assignment operator associativity

GATE 2024 - Your dream can come true!

Download the ultimate guide to gate preparation, register with byju's & download free pdfs, register with byju's & watch live videos.

6.1 — Operator precedence and associativity

Prec/AssOperatorDescriptionPattern
1 L->R::
::
Global scope (unary)
Namespace scope (binary)
::name
class_name::member_name
2 L->R()
()
type()
type{}
[]
.
->
++
––
typeid
const_cast
dynamic_cast
reinterpret_cast
static_cast
sizeof…
noexcept
alignof
Parentheses
Function call
Functional cast
List init temporary object (C++11)
Array subscript
Member access from object
Member access from object ptr
Post-increment
Post-decrement
Run-time type information
Cast away const
Run-time type-checked cast
Cast one type to another
Compile-time type-checked cast
Get parameter pack size
Compile-time exception check
Get type alignment
(expression)
function_name(arguments)
type(expression)
type{expression}
pointer[expression]
object.member_name
object_pointer->member_name
lvalue++
lvalue––
typeid(type) or typeid(expression)
const_cast<type>(expression)
dynamic_cast<type>(expression)
reinterpret_cast<type>(expression)
static_cast<type>(expression)
sizeof…(expression)
noexcept(expression)
alignof(type)
3 R->L+
-
++
––
!
not
~
(type)
sizeof
co_await
&
*
new
new[]
delete
delete[]
Unary plus
Unary minus
Pre-increment
Pre-decrement
Logical NOT
Logical NOT
Bitwise NOT
C-style cast
Size in bytes
Await asynchronous call
Address of
Dereference
Dynamic memory allocation
Dynamic array allocation
Dynamic memory deletion
Dynamic array deletion
+expression
-expression
++lvalue
––lvalue
!expression
not expression
~expression
(new_type)expression
sizeof(type) or sizeof(expression)
co_await expression (C++20)
&lvalue
*expression
new type
new type[expression]
delete pointer
delete[] pointer
4 L->R->*
.*
Member pointer selector
Member object selector
object_pointer->*pointer_to_member
object.*pointer_to_member
5 L->R*
/
%
Multiplication
Division
Remainder
expression * expression
expression / expression
expression % expression
6 L->R+
-
Addition
Subtraction
expression + expression
expression - expression
7 L->R<<
>>
Bitwise shift left / Insertion
Bitwise shift right / Extraction
expression << expression
expression >> expression
8 L->R<=>Three-way comparison (C++20)expression <=> expression
9 L->R<
<=
>
>=
Comparison less than
Comparison less than or equals
Comparison greater than
Comparison greater than or equals
expression < expression
expression <= expression
expression > expression
expression >= expression
10 L->R==
!=
Equality
Inequality
expression == expression
expression != expression
11 L->R&Bitwise ANDexpression & expression
12 L->R^Bitwise XORexpression ^ expression
13 L->R|Bitwise ORexpression | expression
14 L->R&&
and
Logical AND
Logical AND
expression && expression
expression and expression

15 L->R||
or
Logical OR
Logical OR
expression || expression
expression or expression
16 R->Lthrow
co_yield
?:
=
*=
/=
%=
+=
-=
<<=
>>=
&=
|=
^=
Throw expression
Yield expression (C++20)
Conditional
Assignment
Multiplication assignment
Division assignment
Remainder assignment
Addition assignment
Subtraction assignment
Bitwise shift left assignment
Bitwise shift right assignment
Bitwise AND assignment
Bitwise OR assignment
Bitwise XOR assignment
throw expression
co_yield expression
expression ? expression : expression
lvalue = expression
lvalue *= expression
lvalue /= expression
lvalue %= expression
lvalue += expression
lvalue -= expression
lvalue <<= expression
lvalue >>= expression
lvalue &= expression
lvalue |= expression
lvalue ^= expression
17 L->R,Comma operatorexpression, expression

Best practice

Value computation (of operations)

Consider the following expression:

Sample problem: x = 2 + 3 % 4

Binary operator has higher precedence than operator or operator , so it gets evaluated first:

x = 2 + (3 % 4)

Binary operator has a higher precedence than operator , so it gets evaluated next:

Final answer: x = (2 + (3 % 4))

We now no longer need the table above to understand how this expression will evaluate.

cppreference.com

  • View source

Operator precedence and associativity

.

Operator precedence defines the order in which operators are evaluated in expressions with multiple operators.

Operators with higher precedence will be bound tighter (as if by parentheses) to its argument than the operators with lower precedence. For example, the expression a + b * c is equivalent to a + ( b * c ) . That is, we firstly evaluate the multiplication operator and only then sum the result of the multiplication and the value of a . This is because the multiplication operator has higher precedence.

If there are multiple operators of the same precedence in the expression, the order of evaluation is defined by their associativity: either right-to-left or left-to-right. For example, a + b - c is equivalent to ( a + b ) - c as associativity of these particular operators is left to right.

The following table lists the precedence and associativity of C++ operators.

Operators are listed top to bottom, in descending precedence. in an

Precedence Operator Description Associativity
1 Scope resolution Left-to-right
2 Suffix/postfix increment and decrement
Function call
Array subscripting
Element selection by reference
Element selection through pointer
3 Prefix increment and decrement Right-to-left
Unary plus and minus
Logical NOT and bitwise NOT
) Type cast
Indirection (dereference)
Address-of
Size-of
, Dynamic memory allocation
, Dynamic memory deallocation
4 Pointer to member Left-to-right
5 Multiplication, division, and remainder
6 Addition and subtraction
7 Bitwise left shift and right shift
8 For relational operators < and ≤ respectively
For relational operators > and ≥ respectively
9 For relational = and ≠ respectively
10 Bitwise AND
11 Bitwise XOR (exclusive or)
12 Bitwise OR (inclusive or)
13 Logical AND
14 Logical OR
15 Ternary conditional Right-to-left
Direct assignment (provided by default for C++ classes)
Assignment by sum and difference
Assignment by product, quotient, and remainder
Assignment by bitwise left shift and right shift
Assignment by bitwise AND, XOR, and OR
16 Throw operator (for exceptions)
17 Comma Left-to-right
  • Community portal
  • Current events
  • Recent changes
  • Random page
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • This page was last modified on 23 September 2013, at 11:43.
  • This page has been accessed 10,055 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Operator precedence

Operator precedence determines how operators are parsed concerning each other. Operators with higher precedence become the operands of operators with lower precedence.

Precedence and associativity

Consider an expression describable by the representation below, where both OP1 and OP2 are fill-in-the-blanks for OPerators.

The combination above has two possible interpretations:

Which one the language decides to adopt depends on the identity of OP1 and OP2 .

If OP1 and OP2 have different precedence levels (see the table below), the operator with the higher precedence goes first and associativity does not matter. Observe how multiplication has higher precedence than addition and executed first, even though addition is written first in the code.

Within operators of the same precedence, the language groups them by associativity . Left-associativity (left-to-right) means that it is interpreted as (a OP1 b) OP2 c , while right-associativity (right-to-left) means it is interpreted as a OP1 (b OP2 c) . Assignment operators are right-associative, so you can write:

with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5 — the return value of b = 5 , a.k.a. right operand of the assignment.

As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity.

Operators are first grouped by precedence, and then, for adjacent operators that have the same precedence, by associativity. So, when mixing division and exponentiation, the exponentiation always comes before the division. For example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2) .

For prefix unary operators, suppose we have the following pattern:

where OP1 is a prefix unary operator and OP2 is a binary operator. If OP1 has higher precedence than OP2 , then it would be grouped as (OP1 a) OP2 b ; otherwise, it would be OP1 (a OP2 b) .

If the unary operator is on the second operand:

Then the binary operator OP2 must have lower precedence than the unary operator OP1 for it to be grouped as a OP2 (OP1 b) . For example, the following is invalid:

Because + has higher precedence than yield , this would become (a + yield) 1 — but because yield is a reserved word in generator functions, this would be a syntax error. Luckily, most unary operators have higher precedence than binary operators and do not suffer from this pitfall.

If we have two prefix unary operators:

Then the unary operator closer to the operand, OP2 , must have higher precedence than OP1 for it to be grouped as OP1 (OP2 a) . It's possible to get it the other way and end up with (OP1 OP2) a :

Because await has higher precedence than yield , this would become (await yield) 1 , which is awaiting an identifier called yield , and a syntax error. Similarly, if you have new !A; , because ! has lower precedence than new , this would become (new !) A , which is obviously invalid. (This code looks nonsensical to write anyway, since !A always produces a boolean, not a constructor function.)

For postfix unary operators (namely, ++ and -- ), the same rules apply. Luckily, both operators have higher precedence than any binary operator, so the grouping is always what you would expect. Moreover, because ++ evaluates to a value , not a reference , you can't chain multiple increments together either, as you may do in C.

Operator precedence will be handled recursively . For example, consider this expression:

First, we group operators with different precedence by decreasing levels of precedence.

  • The ** operator has the highest precedence, so it's grouped first.
  • Looking around the ** expression, it has * on the right and + on the left. * has higher precedence, so it's grouped first. * and / have the same precedence, so we group them together for now.
  • Looking around the * / / expression grouped in 2, because + has higher precedence than >> , the former is grouped.

Within the * / / group, because they are both left-associative, the left operand would be grouped.

Note that operator precedence and associativity only affect the order of evaluation of operators (the implicit grouping), but not the order of evaluation of operands . The operands are always evaluated from left-to-right. The higher-precedence expressions are always evaluated first, and their results are then composed according to the order of operator precedence.

If you are familiar with binary trees, think about it as a post-order traversal .

After all operators have been properly grouped, the binary operators would form a binary tree. Evaluation starts from the outermost group — which is the operator with the lowest precedence ( / in this case). The left operand of this operator is first evaluated, which may be composed of higher-precedence operators (such as a call expression echo("left", 4) ). After the left operand has been evaluated, the right operand is evaluated in the same fashion. Therefore, all leaf nodes — the echo() calls — would be visited left-to-right, regardless of the precedence of operators joining them.

Short-circuiting

In the previous section, we said "the higher-precedence expressions are always evaluated first" — this is generally true, but it has to be amended with the acknowledgement of short-circuiting , in which case an operand may not be evaluated at all.

Short-circuiting is jargon for conditional evaluation. For example, in the expression a && (b + c) , if a is falsy , then the sub-expression (b + c) will not even get evaluated, even if it is grouped and therefore has higher precedence than && . We could say that the logical AND operator ( && ) is "short-circuited". Along with logical AND, other short-circuited operators include logical OR ( || ), nullish coalescing ( ?? ), and optional chaining ( ?. ).

When evaluating a short-circuited operator, the left operand is always evaluated. The right operand will only be evaluated if the left operand cannot determine the result of the operation.

Note: The behavior of short-circuiting is baked in these operators. Other operators would always evaluate both operands, regardless if that's actually useful — for example, NaN * foo() will always call foo , even when the result would never be something other than NaN .

The previous model of a post-order traversal still stands. However, after the left subtree of a short-circuiting operator has been visited, the language will decide if the right operand needs to be evaluated. If not (for example, because the left operand of || is already truthy), the result is directly returned without visiting the right subtree.

Consider this case:

Only C() is evaluated, despite && having higher precedence. This does not mean that || has higher precedence in this case — it's exactly because (B() && A()) has higher precedence that causes it to be neglected as a whole. If it's re-arranged as:

Then the short-circuiting effect of && would only prevent C() from being evaluated, but because A() && C() as a whole is false , B() would still be evaluated.

However, note that short-circuiting does not change the final evaluation outcome. It only affects the evaluation of operands , not how operators are grouped — if evaluation of operands doesn't have side effects (for example, logging to the console, assigning to variables, throwing an error), short-circuiting would not be observable at all.

The assignment counterparts of these operators ( &&= , ||= , ??= ) are short-circuited as well. They are short-circuited in a way that the assignment does not happen at all.

The following table lists operators in order from highest precedence (18) to lowest precedence (1).

Several general notes about the table:

  • Not all syntax included here are "operators" in the strict sense. For example, spread ... and arrow => are typically not regarded as operators. However, we still included them to show how tightly they bind compared to other operators/expressions.
  • Some operators have certain operands that require expressions narrower than those produced by higher-precedence operators. For example, the right-hand side of member access . (precedence 17) must be an identifier instead of a grouped expression. The left-hand side of arrow => (precedence 2) must be an arguments list or a single identifier instead of some random expression.
  • Some operators have certain operands that accept expressions wider than those produced by higher-precedence operators. For example, the bracket-enclosed expression of bracket notation [ … ] (precedence 17) can be any expression, even comma (precedence 1) joined ones. These operators act as if that operand is "automatically grouped". In this case we will omit the associativity.
Precedence Associativity Individual operators Notes
18: grouping n/a
[1]
17: access and call left-to-right
[2]

n/a
[3]
with argument list
[4]

16: new n/a without argument list
15: postfix operators n/a
[5]

14: prefix operators n/a
[6]





[7]
13: exponentiation right-to-left
[8]
12: multiplicative operators left-to-right


11: additive operators left-to-right

10: bitwise shift left-to-right


9: relational operators left-to-right



8: equality operators left-to-right



7: bitwise AND left-to-right
6: bitwise XOR left-to-right
5: bitwise OR left-to-right
4: logical AND left-to-right
3: logical OR, nullish coalescing left-to-right

[9]
2: assignment and miscellaneous right-to-left
[10]















right-to-left
[11]
right-to-left
[12]
n/a

[13]
1: comma left-to-right
  • The operand can be any expression.
  • The "right-hand side" must be an identifier.
  • The "right-hand side" can be any expression.
  • The "right-hand side" is a comma-separated list of any expression with precedence > 1 (i.e. not comma expressions).
  • The operand must be a valid assignment target (identifier or property access). Its precedence means new Foo++ is (new Foo)++ (a syntax error) and not new (Foo++) (a TypeError: (Foo++) is not a constructor).
  • The operand must be a valid assignment target (identifier or property access).
  • The operand cannot be an identifier or a private property access.
  • The left-hand side cannot have precedence 14.
  • The operands cannot be a logical OR || or logical AND && operator without grouping.
  • The "left-hand side" must be a valid assignment target (identifier or property access).
  • The associativity means the two expressions after ? are implicitly grouped.
  • The "left-hand side" is a single identifier or a parenthesized parameter list.
  • Only valid inside object literals, array literals, or argument lists.
  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

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.

Python assignment operator associativity

Consider the following Python3 program:

I expected the output to be:

But instead I got:

My question is: is there anything in the Python language specification about associativity of the assignment operator, or is the behavior for the above example undefined?

All I was able to find is that expressions are evaluated form left to right, except that r-value is evaluated first in case of assignment, but that doesn't help.

Ivan Sikiric's user avatar

  • 1 Interestingly, your example is very similar to the example at the end of the section . –  Jeff Mercado Commented Oct 12, 2011 at 9:54

2 Answers 2

Short answer: the code is well defined; the order is left-to-right.

Long answer:

First of all, let's get the terminology right. Unlike in some other languages, assignment in Python is a statement , not an operator . This means that you can't use assignment as part of another expression: for example i = (j = 0) is not valid Python code.

The assignment statement is defined to explicitly permit multiple assignment targets (in your example, these are i and a[i] ). Each target can be a list, but let's leave that aside.

Where there are multiple assignment targets, the value is assigned from left to right. To quote the documentation :

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right .

NPE's user avatar

Just to make it clear, since I struggled myself to understand this. The statement:

is equivalent to

wjandrea's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

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 .

Not the answer you're looking for? Browse other questions tagged python operators or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • The 2024 Developer Survey Is Live
  • The return of Staging Ground to Stack Overflow
  • Policy: Generative AI (e.g., ChatGPT) is banned

Hot Network Questions

  • Are there any precautions I should take if I plan on storing something very heavy near my foundation?
  • Why is “selling a birthright (πρωτοτόκια)” so bad? -- Hebrews 12:16
  • In general, How's a computer science subject taught in Best Universities of the World that are not MIT level?
  • How can you destroy a mage hand?
  • Did the NES CPU save die area by omitting BCD?
  • Properties of Hamilton cycles in hypercubes
  • Why in ordinary linear regression is no global test for lack of model fit unless there are replicate observations at various settings of X?
  • How to count the number of lines in an array
  • What might cause an inner tube to "behave" flat in a tire?
  • What was the title and author of this children's book of mazes?
  • Is there any way to play Runescape singleplayer?
  • Is there an analytical solution for the integral of a ratio of sin functions like this one?
  • Where is the documentation for the new apt sources format used in 22.04?
  • Is it possible for Mathematica to output the name of a matrix as opposed to its matrix form?
  • Bound states between neutrinos using Schrödinger's equation?
  • How do I perform pandas cumsum while skipping rows that are duplicated in another field?
  • What aspects define how present the garlic taste in an aglio e olio pasta becomes?
  • Are state and Federal Grand Jury proceedings, testimony and deliberations secret in perpetuity?
  • Can my grant pay for a conference marginally related to award?
  • Dill seedling leaves turning from green to red
  • Can we study scientifically the set of facts and behaviors if we have no scientific explanation for the source, origin or underlying mechanism of it?
  • Horror movie that has a demon hand coming through a mirror
  • Transactional Replication - how to set up alerts/notification to send alerts before transaction log space is full on publisher?
  • Is there a name for books in which the narrator isn't the protagonist but someone who know them well?

assignment operator associativity

Javatpoint Logo

Java Tutorial

Control statements, java object class, java inheritance, java polymorphism, java abstraction, java encapsulation, java oops misc.

JavaTpoint

A Java operator is a special symbol that performs a certain operation on multiple operands and gives the result as an output.

Java has a large number of operators that are divided into two categories. First, an operator's performance is based on the number of operands it performs on. Second, the type or nature of the operation performed by an operator.

Operators can be categorized into the following groups based on the sort of operation they perform:

Precedence and associativity are two features of Java operators. When there are two or more operators in an expression, the operator with the highest priority will be executed first.

For example, consider the equation, 1 + 2 * 5. Here, the multiplication (*) operator is executed first, followed by addition. Because multiplication operator takes precedence over the addition operator.

Alternatively, when an operand is shared by two operators (2 in the example above is shared by + and *), the higher priority operator processes the shared operand. You should have grasped the significance of precedence or priority in the execution of operators from the preceding example.

However, the situation may not always be as obvious as in the example above. What if the precedence of all operators in an expression is the same? In that instance, the second quality associated with an operator, associativity, comes into existence.

specifies the order in which operators are executed, which can be left to right or right to left. For example, in the phrase a = b = c = 8, the assignment operator is used from right to left. It means that the value 8 is assigned to c, then c is assigned to b, and at last b is assigned to a. This phrase can be parenthesized as (a = (b = (c = 8)).

The priority of a Java operator can be modified by putting parenthesis around the lower order priority operator, but not the associativity. In the equation (1 + 2) * 3, for example, the addition will be performed first since parentheses take precedence over the multiplication operator.

Category Operators Associativity
Postfix ++ - - Left to right
Unary + - ! ~ ++ - - Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Java Operator Associativity

Operators with the same precedence follow the operator group's operator associativity. Operators in Java can be left-associative, right-associative, or have no associativity at all. Left-associative operators are assessed from left to right, right-associative operators are reviewed from right to left, and operators with no associativity are evaluated in any order.

Operator Precedence Vs. Operator Associativity

The operator's precedence refers to the order in which operators are evaluated within an expression whereas associativity refers to the order in which the consecutive operators within the same group are carried out.

Precedence rules specify the priority (which operators will be evaluated first) of operators.

Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

  • United States
  • United Kingdom

Jeff Friesen

By Jeff Friesen , |

A beginner's library for learning about essential Java programming concepts, syntax, APIs, and packages.

Evaluate Java expressions with operators

Here's everything you need to know about java operators and operator types, and how to use them to write expressions for your java programs..

Evaluate Java expressions with operators

What is a Java expression?

How to write simple expressions, how to write compound expressions, about java operators and operands, operator types in java.

  • Operator precedence and associativity
  • Primitive-type conversions

In this tutorial, you will learn how to write expressions for your Java programs. In many cases, you'll use operators to write your Java expressions, and there are many operator types  to know how to use. I'll briefly introduce Java's operator types, including the additive, bitwise, logical, conditional, shift, and equality types and their operands. You'll also learn about operator overloading and operator precedence, and you'll see a demonstration of primitive-type conversion. I'll conclude with a small Java program that you can use to practice primitive-type conversions on your own.

What you'll learn in this Java tutorial

  • All the operator types in Java, with examples
  • About operator precedence and associativity
  • How to work with primitive-type conversions

Expressions  are combinations of literals, method calls, variable names, and operators. Java applications evaluate expressions. Evaluating an expression produces a new value that can be stored in a variable, used to make a decision, and more.

A simple expression is a literal, variable name, or method call. No operators are involved. Here are some examples of simple expressions:

A simple expression has a type , which is either a primitive type or a reference type. In these examples, 52 is a 32-bit integer ( int );  System.out.println("ABC"); is void ( void ) because it returns no value;  "Java" is a string ( String );  98.6D is a 64-bit double-precision floating-point value ( double ); and 89L is a 64-bit long integer ( long ). We don't know age 's type.

Use jshell to experiment

You can easily try out these and other simple expressions using jshell . For example, enter 52 at the jshell> prompt and you'll receive something like the following output:

$1 is the name of a scratch variable that jshell creates to store 52 . (Scratch variables are created whenever literals are entered.) Execute System.out.println($1) and you'll see 52 as the output.

You can run jshell with the -v command-line argument ( jshell -v ) to generate verbose feedback. In this case, entering 52 would result in the following message, revealing that scratch variable $1 has int (32-bit integer) type:

Next, try entering age . In this case, you'll probably receive an error message that the symbol was not found. The Java Shell assumes that age is a variable, but it doesn't know its type. You would have to include a type; for example, see what happens if you enter int age .

A compound expression consists of one or more simple expressions integrated into a larger expression via an operator , which is a sequence of instructions symbolically represented in source code. The operator transforms its expression operand(s) into another value. For example, in 6 * 5 , the multiplication operator ( * ) transforms operands 6 and 5 into 30.

Compound expressions can be combined into larger expressions. For example, 6 * 5 + 10 presents compound expression 6 * 5 and a compound expression consisting of their product, addition operator + , and the number 10 . The order of evaluation (multiply first and then add) is dictated by Java's rule of precedence , which we'll get to shortly.

Java's operators are classified by their number of operands:

  • A unary operator has one operand, for example,  unary minus (e.g., -5 ).
  • A binary operator has two operands, examples are multiplication and addition.
  • A ternary operator has three operands; an example is the conditional operator ( ?: ).

Java's operators are also classified by position:

  • A prefix operator is a unary operator that precedes its operand (e.g., -5 ).
  • A postfix operator is a unary operator that follows its operand (e.g., age++; -- add 1 to age 's numeric value).
  • An infix operator is a binary or ternary operator between the operator's operands (e.g., age + 5 ).

Another jshell example

I'll introduce more operators in the following sections, where I present examples in the form of applications. You could also try out these operators with jshell , like so:

In this case, we first enter the expression 6 + 2 , which jshell evaluates, assigning the resulting 8 to scratch variable $1 . Next, we multiply $1 by 7 , which stores 56 in scratch variable $2 . This example demonstrates that you can use scratch variables in Java expressions.

Next, we'll tour all the operator types in Java. After introducing each operator type, I'll present an example that shows you how it's used in Java expressions.

Additive operators

The additive operators increase or decrease a numeric value through addition and subtraction. Additive operators include addition ( + ), subtraction ( - ), postdecrement ( -- ), postincrement ( ++ ), predecrement ( -- ), and preincrement ( ++ ). String concatenation ( + ) is also considered to be additive. Here's a formal definition for each of these operators:

  • Addition : Given operand1 + operand2 , where each operand must be of character or numeric type, add operand2 to operand1 and return the sum. Example: 4 + 6 .
  • Subtraction : Given operand1 - operand2 , where each operand must be of character or numeric type, subtract operand2 from operand1 and return the difference. Example: 4 - 6 .
  • Postdecrement : Given variable -- , where variable must be of character or numeric type, subtract 1 from variable 's value (storing the result in variable ) and return the original value. Example: x--; .
  • Postincrement : Given variable ++ , where variable must be of character or numeric type, add 1 to variable 's value (storing the result in variable ) and return the original value. Example: x++; .
  • Predecrement : Given -- variable , where variable must be of character or numeric type, subtract 1 from its value, store the result in variable , and return the new decremented value. Example: --x; .
  • Preincrement : Given ++ variable , where variable must be of character or numeric type, add 1 to its value, store the result in variable , and return the new incremented value. Example: ++x; .
  • String concatenation : Given operand1 + operand2 , where at least one operand is of String type, append operand2 's string representation to operand1 's string representation and return the result. Example: "A" + "B" .

The addition, subtraction, postdecrement, postincrement, predecrement, and preincrement operators can generate values that overflow the limits of the result type. For example, adding two large positive 64-bit integer values can produce a value that cannot be represented in 64 bits. The resulting overflow is not detected or reported by Java's additive operators.

Example application: Additive operators

Listing 1 presents a small application for playing with Java's additive operators.

Listing 1. Additive operators in Java (AddOp.java)

See Elementary Java language features for an introduction to using the JDK's javac tool to compile Java source code and the java tool to run the resulting application. Execute the following command to compile Listing 1:

Assuming successful compilation, you should observe an AddOp.class file in the current directory. Execute the following command to run it:

AddOp responds by producing the following output:

Studying this output offers insight into the postincrement, postdecrement, preincrement, and predecrement operators. For postincrement/postdecrement, age 's current value is output before the increment/decrement operation. For preincrement/predecrement, the operation is performed and its result is stored in age , and then age 's new value is output.

Array index operator

The array index operator ( [] ) accesses an array element by providing the element's index (position). This operator is placed after the array variable's name, as in grades[0] (access the first element in the array assigned to grades ; the first element is stored at index 0). Here's a formal definition:

Given variable [ index ] , where index must be of integer ( int ) type, read a value from or store a value into variable 's storage element at location index . Example: temperatures[1]

The value passed to index is a 32-bit integer that is either 0 or a positive value ranging to one less than the array's length, which is indicated by appending .length to the name of the array. For example, grades.length returns the number of elements in the array assigned to grades .

Example application: Array index operator

Listing 2 presents the source code to an example application that lets you play with the array index operator.

Listing 2. Array index operator in Java (ArrayIndexOp.java)

Listing 2 is somewhat more interesting than Listing 1. After creating a five-element, one-dimensional array of integers (via an array initializer) and assigning the array's reference to grades , main() proceeds to access various elements. Two items are of special interest:

  • The array index operator's index must ultimately be a 32-bit integer (0 or a positive value). You can specify the name of an integer variable (e.g., index ), which contains the index value, as the index.
  • You can specify a calculation involving character literals. (Later in this tutorial I'll introduce type conversions, and you'll discover why 'C' - 'A' produces an integer (2), which serves as a valid index.)

The final example, which passes 1D as an index to the array index operator, is commented out because it will not compile. If you uncomment the line and attempt to compile Listing 2, you will receive an error message about incompatible types: "possible lossy conversion from double to int. ."

Compile Listing 2 ( javac ArrayIndexOp.java ) and run the application ( java ArrayIndexOp ). You should observe the following output:

Assignment operators

The assignment operator ( = ) assigns an expression's value to a variable (e.g., i = 6; ), including an array element (e.g., x[0] = 15; ). The expression and variable must be assignment compatible , meaning their types must agree. For example, you cannot assign a string literal to an integer variable. I'll explain more about this when we discuss type conversions.

  • Programming Languages
  • Software Development

assignment operator associativity

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python Operators

Precedence and associativity of operators in python.

  • Python Arithmetic Operators
  • Difference between / vs. // operator in Python
  • Python - Star or Asterisk operator ( * )
  • What does the Double Star operator mean in Python?
  • Division Operators in Python
  • Modulo operator (%) in Python
  • Python Logical Operators
  • Python OR Operator
  • Difference between 'and' and '&' in Python
  • not Operator in Python | Boolean Logic

Ternary Operator in Python

  • Python Bitwise Operators

Python Assignment Operators

Assignment operators in python.

  • Walrus Operator in Python 3.8
  • Increment += and Decrement -= Assignment Operators in Python
  • Merging and Updating Dictionary Operators in Python 3.9
  • New '=' Operator in Python3.8 f-string

Python Relational Operators

  • Comparison Operators in Python
  • Python NOT EQUAL operator
  • Difference between == and is operator in Python
  • Chaining comparison operators in Python
  • Python Membership and Identity Operators
  • Difference between != and is not operator 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. 

  • OPERATORS: These are the special symbols. Eg- + , * , /, etc.
  • OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Identity Operators and Membership Operators

Python Operators

Arithmetic Operators in Python

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.

OperatorDescriptionSyntax
+Addition: adds two operandsx + y
Subtraction: subtracts two operandsx – y
*Multiplication: multiplies two operandsx * y
/Division (float): divides the first operand by the secondx / y
//Division (floor): divides the first operand by the secondx // y
%Modulus: returns the remainder when the first operand is divided by the secondx % y
**Power: Returns first raised to power secondx ** y

Example of Arithmetic Operators in Python

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: 

Float division

  • Floor division

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’ .

Integer division( Floor division)

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.

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in Python is as follows:

  • P – Parentheses
  • E – Exponentiation
  • M – Multiplication (Multiplication and division have the same precedence)
  • D – Division
  • A – Addition (Addition and subtraction have the same precedence)
  • S – Subtraction

The modulus of Python operators helps us extract the last digit/s of a number. For example:

  • x % 10 -> yields the last digit
  • x % 100 -> yield last two digits

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power

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.

Comparison of Python Operators

In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.

OperatorDescriptionSyntax
>Greater than: True if the left operand is greater than the rightx > y
<Less than: True if the left operand is less than the rightx < y
==Equal to: True if both operands are equalx == y
!=Not equal to – True if operands are not equalx != y
>=Greater than or equal to True if the left operand is greater than or equal to the rightx >= y
<=Less than or equal to True if the left operand is less than or equal to the rightx <= y

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In Python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have the same precedence order.

Example of Comparison Operators in Python

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’ .

Logical Operators in Python

Python Logical operators perform Logical AND , Logical OR , and Logical NOT operations. It is used to combine conditional statements.

OperatorDescriptionSyntax
andLogical AND: True if both the operands are truex and y
orLogical OR: True if either of the operands is true x or y
notLogical NOT: True if the operand is false not x

Precedence of Logical Operators in Python

The precedence of Logical Operators in Python is as follows:

  • Logical not
  • logical and

Example of Logical Operators in Python

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.

Bitwise Operators in Python

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.

OperatorDescriptionSyntax
&Bitwise ANDx & y
|Bitwise ORx | y
~Bitwise NOT~x
^Bitwise XORx ^ y
>>Bitwise right shiftx>>
<<Bitwise left shiftx<<

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in Python is as follows:

  • Bitwise NOT
  • Bitwise Shift
  • Bitwise AND
  • Bitwise XOR

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.

OperatorDescriptionSyntax
=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 operanda+=b     a=a+b
-=Subtract AND: Subtract right operand from left operand and then assign to left operanda-=b     a=a-b
*=Multiply AND: Multiply right operand with left operand and then assign to left operanda*=b     a=a*b
/=Divide AND: Divide left operand with right operand and then assign to left operanda/=b     a=a/b
%=Modulus AND: Takes modulus using left and right operands and assign the result to left operanda%=b     a=a%b
//=Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left operanda//=b     a=a//b
**=Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operanda**=b     a=a**b
&=Performs Bitwise AND on operands and assign value to left operanda&=b     a=a&b
|=Performs Bitwise OR on operands and assign value to left operanda|=b     a=a|b
^=Performs Bitwise xOR on operands and assign value to left operanda^=b     a=a^b
>>=Performs Bitwise right shift on operands and assign value to left operanda>>=b     a=a>>b
<<=Performs Bitwise left shift on operands and assign value to left operanda <<= 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’ .

Identity Operators in Python

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. 

Example Identity Operators in Python

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’ ).

Membership Operators in Python

In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.

Examples of Membership Operators in Python

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] 

Examples of Ternary Operator in Python

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.

Operator Precedence in Python

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.”

Operator Associativity in Python

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 . 

Python Operator Exercise Questions

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

Please Login to comment...

Similar reads.

  • python-basics
  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. PPT

    assignment operator associativity

  2. Operator Precedence and Associativity in Python

    assignment operator associativity

  3. Operator Precedence and Associativity in C

    assignment operator associativity

  4. Precedence and Associativity of Operators

    assignment operator associativity

  5. PPT

    assignment operator associativity

  6. Operator Associativity in Python-CBSE class11 Qissba

    assignment operator associativity

VIDEO

  1. Week 2

  2. 06_Ruby basics ( Assignment Operators)

  3. 8. Conditional, Equality and Assignment operators in C

  4. Compilers_29 : Solving Operator associativity برمنظ 29_عربي

  5. Lecture 15 (Computer Programming in C) Operators: Relational, logical, and assignment operators

  6. 10

COMMENTS

  1. Operator associativity

    The associativity and precedence of an operator is a part of the definition of the programming language; different programming languages may have different associativity and precedence for the same type of operator. Consider the expression a ~ b ~ c. If the operator ~ has left associativity, this expression would be interpreted as (a ~ b) ~ c.

  2. Operator Precedence and Associativity in C

    The concept of operator precedence and associativity in C helps in determining which operators will be given priority when there are multiple operators in the expression. It is very common to have multiple operators in C language and the compiler first evaluates the operater with higher precedence. It helps to maintain the ambiguity of the ...

  3. Operator Associativity in Programming

    Operator associative refers to the order in which operators of the same precedence are used in a word. In a programming language, it is important to understand the interactions between operators to properly define and test expressions. In this article, we will discuss operator associativity in programming. Table of Content.

  4. C Operator Precedence

    Precedence and associativity are independent from order of evaluation. The standard itself doesn't specify precedence levels. They are derived from the grammar. In C++, the conditional operator has the same precedence as assignment operators, and prefix ++ and --and assignment operators don't have the restrictions about their operands.

  5. Operator Precedence and Associativity in C++

    Left-to-right associativity: In expressions like a + b - c, the addition and subtraction operators are evaluated from left to right. So, (a + b) - c is equivalent. Right-to-left associativity: Some operators, like the assignment operator =, have right-to-left associativity. For example, a = b = 4; assigns the value of b to a.

  6. C Precedence And Associativity Of Operators

    The precedence of operators determines which operator is executed first if there is more than one operator in an expression. Let us consider an example: In C, the precedence of * is higher than - and =. Hence, 17 * 6 is evaluated first. Then the expression involving - is evaluated as the precedence of - is higher than that of =.

  7. What is associativity of operators and why is it important?

    Associativity in CPU caches. The Associative property in mathematics is a property of operators such as addition (+). This property allows you to rearrange parentheses without changing the value of a statement, i.e.: (a + b) + c = a + (b + c) In programming languages, the associativity (or fixity) of an operator is a property that determines ...

  8. C++ built-in operators, precedence, and associativity

    C++ operator precedence and associativity table. The following table shows the precedence and associativity of C++ operators (from highest to lowest precedence). Operators with the same precedence number have equal precedence unless another relationship is explicitly forced by parentheses. Expand table. Operator Description.

  9. C++ Operator Precedence and Associativity

    C++ Operators Associativity. Operator associativity is the direction from which an expression is evaluated. For example, int a = 1; int b = 4; // a will be 4 a = b; Take a look at a = 4; statement. The associativity of the = operator is from right to left. Hence, the value of b is assigned to a, and not in the other direction.. Also, multiple operators can have the same level of precedence (as ...

  10. Operator precedence

    Assignment operators are right-associative, so you can write: a = b = 5; // same as writing a = (b = 5); with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5 — the return value of b = 5, a.k.a. right operand of the ...

  11. C++ Operator Precedence

    Operators that have the same precedence are bound to their arguments in the direction of their associativity. For example, the expression a = b = c is parsed as a =(b = c), and not as (a = b)= c because of right-to-left associativity of assignment, but a + b - c is parsed (a + b)- c and not a +(b - c) because of left-to-right associativity of ...

  12. Operator Precedence and Associativity in C

    The precedence of operators in C dictates the order in which the operators will be evolved in an expression. Associativity, on the other hand, defines the order in which the operators of the same precedence will be evaluated in an expression. Also, associativity can occur from either right to left or left to right.

  13. 6.1

    An operation is a mathematical process involving zero or more input values (called operands) that produces a new value (called an output value). The specific operation to be performed is denoted by a construct (typically a symbol or pair of symbols) called an operator. For example, as children we all learn that 2 + 3 equals 5.

  14. Operator precedence and associativity

    If there are multiple operators of the same precedence in the expression, the order of evaluation is defined by their associativity: either right-to-left or left-to-right. For example, a + b - c is equivalent to (a + b) - c as associativity of these particular operators is left to right. The following table lists the precedence and ...

  15. Operator Precedence and Associativity in Programming

    To solve this problem there is the concept of operator precedence. Operator Precedence is a set of rules that defines the priority for all the operators present in a programming language. The operation which has an operator with the highest priority will be executed first. Example: a= 4+5/10; In the above given example if we solve the addition ...

  16. 5.4.1 Precedence and Associativity

    When operators of the same precedence level appear in an expression, the order of evaluation is determined by the associativity. Except for the assignment operator, associativity of most binary operators is left to right; associativity of the assignment operator and most unary operators is right to left. Consider the following program fragment:

  17. Operator precedence

    This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5 — the return value of b = 5, a.k.a. right operand of the assignment. As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity.

  18. Python assignment operator associativity

    13. Short answer: the code is well defined; the order is left-to-right. Long answer: First of all, let's get the terminology right. Unlike in some other languages, assignment in Python is a statement, not an operator. This means that you can't use assignment as part of another expression: for example i = (j = 0) is not valid Python code.

  19. Associativity of Operators in Java

    Associativity specifies the order in which operators are executed, which can be left to right or right to left. For example, in the phrase a = b = c = 8, the assignment operator is used from right to left. It means that the value 8 is assigned to c, then c is assigned to b, and at last b is assigned to a. This phrase can be parenthesized as (a ...

  20. Operators in C and C++

    Assignment operators. All assignment expressions exist in C and C++ and can be overloaded in C++. ... The following is a table that lists the precedence and associativity of all the operators in the C and C++ languages. Operators are listed top to bottom, in descending precedence. Descending precedence refers to the priority of the grouping of ...

  21. Assignment Operators in Programming

    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 ...

  22. Evaluate Java expressions with operators

    About operator precedence and associativity; How to work with primitive-type conversions; ... Assignment operators. The assignment operator (=) assigns an expression's value to a variable ...

  23. What are Operators in Programming?

    Assignment operators are fundamental for updating variable values, especially in loops and mathematical computations, contributing to the dynamic nature of programming. ... Operator Associativity is a rule that determines the grouping of operators with the same precedence in an expression when they appear consecutively. It specifies the ...

  24. Python Operators

    Assignment Operators; Identity Operators and Membership Operators; ... 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