cppreference.com

C operator precedence.

The following table lists the precedence and associativity of C operators. Operators are listed top to bottom, in descending precedence.

  • ↑ The operand of prefix ++ and -- can't be a type cast. This rule grammatically forbids some expressions that would be semantically invalid anyway. Some compilers ignore this rule and detect the invalidity semantically.
  • ↑ The operand of sizeof can't be a type cast: the expression sizeof ( int ) * p is unambiguously interpreted as ( sizeof ( int ) ) * p , but not sizeof ( ( int ) * p ) .
  • ↑ The expression in the middle of the conditional operator (between ? and : ) is parsed as if parenthesized: its precedence relative to ?: is ignored.
  • ↑ Assignment operators' left operands must be unary (level-2 non-cast) expressions. This rule grammatically forbids some expressions that would be semantically invalid anyway. Many compilers ignore this rule and detect the invalidity semantically. For example, e = a < d ? a ++ : a = d is an expression that cannot be parsed because of this rule. However, many compilers ignore this rule and parse it as e = ( ( ( a < d ) ? ( a ++ ) : a ) = d ) , and then give an error because it is semantically invalid.

When parsing an expression, an operator which is listed on some row will be bound tighter (as if by parentheses) to its arguments than any operator that is listed on a row further below it. For example, the expression * p ++ is parsed as * ( p ++ ) , and not as ( * p ) ++ .

Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same precedence, in the given direction. 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.

[ edit ] Notes

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.

Associativity specification is redundant for unary operators and is only shown for completeness: unary prefix operators always associate right-to-left ( sizeof ++* p is sizeof ( ++ ( * p ) ) ) and unary postfix operators always associate left-to-right ( a [ 1 ] [ 2 ] ++ is ( ( a [ 1 ] ) [ 2 ] ) ++ ). Note that the associativity is meaningful for member access operators, even though they are grouped with unary postfix operators: a. b ++ is parsed ( a. b ) ++ and not a. ( b ++ ) .

[ edit ] References

  • C17 standard (ISO/IEC 9899:2018):
  • A.2.1 Expressions
  • C11 standard (ISO/IEC 9899:2011):
  • C99 standard (ISO/IEC 9899:1999):
  • C89/C90 standard (ISO/IEC 9899:1990):
  • A.1.2.1 Expressions

[ edit ] See also

Order of evaluation of operator arguments at run time.

  • Recent changes
  • Offline version
  • What links here
  • Related changes
  • Upload file
  • Special pages
  • Printable version
  • Permanent link
  • Page information
  • In other languages
  • This page was last modified on 31 July 2023, at 09:28.
  • This page has been accessed 2,665,989 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Learn C practically and Get Certified .

Popular Tutorials

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

  • Keywords & Identifier
  • Variables & Constants
  • C Data Types
  • C Input/Output
  • C Operators
  • C Introduction Examples

C Flow Control

  • C if...else
  • C while Loop
  • C break and continue
  • C switch...case
  • C Programming goto
  • Control Flow Examples

C Functions

  • C Programming Functions
  • C User-defined Functions
  • C Function Types
  • C Recursion
  • C Storage Class
  • C Function Examples
  • C Programming Arrays
  • C Multi-dimensional Arrays
  • C Arrays & Function
  • C Programming Pointers
  • C Pointers & Arrays
  • C Pointers And Functions
  • C Memory Allocation
  • Array & Pointer Examples

C Programming Strings

  • C Programming String
  • C String Functions
  • C String Examples

Structure And Union

  • C Structure
  • C Struct & Pointers
  • C Struct & Function
  • C struct Examples

C Programming Files

  • C Files Input/Output
  • C Files Examples

Additional Topics

  • C Enumeration
  • C Preprocessors
  • C Standard Library
  • C Programming Examples

Bitwise Operators in C Programming

C Programming Operators

C if...else Statement

  • C while and do...while Loop
  • Compute Quotient and Remainder

C Precedence And Associativity Of Operators

  • Precedence 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 = .

Here's a table of operators precedence from higher to lower. The property of associativity will be discussed shortly.

  • Operators Precedence & Associativity Table
  • Associativity of Operators

The associativity of operators determines the direction in which an expression is evaluated. For example,

Here, the value of a is assigned to b , and not the other way around. It's because the associativity of the = operator is from right to left.

Also, if two operators of the same precedence (priority) are present, associativity determines the direction in which they execute.

Here, operators == and != have the same precedence. And, their associativity is from left to right. Hence, 1 == 2 is executed first.

The expression above is equivalent to:

Note: If a statement has multiple operators, you can use parentheses () to make the code more readable.

Table of Contents

Sorry about that.

Related Tutorials

This browser is no longer supported.

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

Precedence and order of evaluation

  • 7 contributors

The precedence and associativity of C operators affect the grouping and evaluation of operands in expressions. An operator's precedence is meaningful only if other operators with higher or lower precedence are present. Expressions with higher-precedence operators are evaluated first. Precedence can also be described by the word "binding." Operators with a higher precedence are said to have tighter binding.

The following table summarizes the precedence and associativity (the order in which the operands are evaluated) of C operators, listing them in order of precedence from highest to lowest. Where several operators appear together, they have equal precedence and are evaluated according to their associativity. The operators in the table are described in the sections beginning with Postfix Operators . The rest of this section gives general information about precedence and associativity.

Precedence and associativity of C operators

1 Operators are listed in descending order of precedence. If several operators appear on the same line or in a group, they have equal precedence.

2 All simple and compound-assignment operators have equal precedence.

An expression can contain several operators with equal precedence. When several such operators appear at the same level in an expression, evaluation proceeds according to the associativity of the operator, either from right to left or from left to right. The direction of evaluation does not affect the results of expressions that include more than one multiplication ( * ), addition ( + ), or binary-bitwise ( & , | , or ^ ) operator at the same level. Order of operations is not defined by the language. The compiler is free to evaluate such expressions in any order, if the compiler can guarantee a consistent result.

Only the sequential-evaluation ( , ), logical-AND ( && ), logical-OR ( || ), conditional-expression ( ? : ), and function-call operators constitute sequence points, and therefore guarantee a particular order of evaluation for their operands. The function-call operator is the set of parentheses following the function identifier. The sequential-evaluation operator ( , ) is guaranteed to evaluate its operands from left to right. (The comma operator in a function call is not the same as the sequential-evaluation operator and does not provide any such guarantee.) For more information, see Sequence points .

Logical operators also guarantee evaluation of their operands from left to right. However, they evaluate the smallest number of operands needed to determine the result of the expression. This is called "short-circuit" evaluation. Thus, some operands of the expression may not be evaluated. For example, in the expression

x && y++

the second operand, y++ , is evaluated only if x is true (nonzero). Thus, y is not incremented if x is false (0).

The following list shows how the compiler automatically binds several sample expressions:

In the first expression, the bitwise-AND operator ( & ) has higher precedence than the logical-OR operator ( || ), so a & b forms the first operand of the logical-OR operation.

In the second expression, the logical-OR operator ( || ) has higher precedence than the simple-assignment operator ( = ), so b || c is grouped as the right-hand operand in the assignment. Note that the value assigned to a is either 0 or 1.

The third expression shows a correctly formed expression that may produce an unexpected result. The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- . However, if q && r evaluates to a nonzero value, s-- is not evaluated, and s is not decremented. If not decrementing s would cause a problem in your program, s-- should appear as the first operand of the expression, or s should be decremented in a separate operation.

The following expression is illegal and produces a diagnostic message at compile time:

In this expression, the equality operator ( == ) has the highest precedence, so p == 0 is grouped as an operand. The conditional-expression operator ( ? : ) has the next-highest precedence. Its first operand is p == 0 , and its second operand is p += 1 . However, the last operand of the conditional-expression operator is considered to be p rather than p += 2 , since this occurrence of p binds more closely to the conditional-expression operator than it does to the compound-assignment operator. A syntax error occurs because += 2 does not have a left-hand operand. You should use parentheses to prevent errors of this kind and produce more readable code. For example, you could use parentheses as shown below to correct and clarify the preceding example:

( p == 0 ) ? ( p += 1 ) : ( p += 2 )

C operators

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

CProgramming Tutorial

  • C Programming Tutorial
  • C - Overview
  • C - Features
  • C - History
  • C - Environment Setup
  • C - Program Structure
  • C - Hello World
  • C - Compilation Process
  • C - Comments
  • C - Keywords
  • C - Identifiers
  • C - User Input
  • C - Basic Syntax
  • C - Data Types
  • C - Variables
  • C - Integer Promotions
  • C - Type Conversion
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • C - Storage Classes
  • C - Operators
  • C - Decision Making
  • C - While loop
  • C - Functions
  • C - Main Functions
  • C - Return Statement
  • C - Scope Rules
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • C - Pointers
  • C - Pointer Arithmetics
  • C - Passing Pointers to Functions
  • C - Strings
  • C - Array of Strings
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Pointers to Structures
  • C - Self-Referential Structures
  • C - Nested Structures
  • C - Bit Fields
  • C - Typedef
  • C - Input & Output
  • C - File I/O
  • C - Preprocessors
  • C - Header Files
  • C - Type Casting
  • C - Error Handling
  • C - Recursion
  • C - Variable Arguments
  • C - Memory Management
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

Operators Precedence in C

Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedence operators will be evaluated first.

Try the following example to understand operator precedence in C −

When you compile and execute the above program, it produces the following result −

C Language Precedence

Switch to English

In the world of programming, the order in which operations are executed can significantly impact the outcome. This is where the concept of operator precedence in C language comes into play.

  • Understanding Operator Precedence in C

Table of Contents

Operator Precedence Table

Operator associativity in c, tips and tricks, common errors.

  • Operator Precedence, or simply precedence, refers to the order in which expressions involving more than one operator are evaluated. In the C language, each operator has a specific precedence associated with it. Operators with higher precedence are evaluated before operators with lower precedence.
  • Associativity is the rule that determines how operators of the same precedence level are grouped in absence of parentheses. Operators can have either Left-to-Right associativity or Right-to-Left associativity.
  • Use Parentheses for Clarity
  • Be mindful of Assignment Operator Precedence
  • Now Trending:
  • How do I check if a list...
  • How do I concatenate two...
  • How to find the index of...
  • How to make a dictionary...

Precedence & Associativity of Operators in C

How to use the Precedence and Associativity of the operators smartly is one of the important part of C programming.

Precedence talks about the priority among the different operators, which to consider first. Like arithmetic operators have higher priority than assignment operators and so on.

When we have more than one operator in a single statement then this precedence comes into the picture as the result may vary greatly.

For eg – 2 + 3 * 4 – 1 == 2+ (3 * 4) – 1 = 16  => This happens because precedence of multiplication operator is higher than the other two.

Associativity comes into the picture when we have operators of the same precedence. It doesn’t talk about which to pick first rather says the order of evaluation.

Here is the precedence and associativity in C table,

Precedence and Associativity Table

Table of Contents

1. How to use the Precedence and Associativity table in C?

Down the rows in the table shows the priorities decreasing. Under each row, all the operators have the same priority, there comes associativity.

It can be clearly seen, Unary, Ternary, and Assignment Operators are evaluated right to left.

1.1. Logical Operator

“x == 5  &&  x == 10 || x != 0 “

In the above statement relational operator(== and !=) is executed first then, logical AND (&&), and at last logical (OR).

“ X == 5 || X == 10 || X == 20”

A relational operator has Left to Right associativity, therefore. The statement will be executed as (take note of the added brackets)

A relational operator has Left to Right associativity, therefore. The statement will be executed as (take note of the added brackets) “ (X == 5 || X == 10) || X == 20”.

1.2. Assignment Operator

1.3. comma operator.

Comma(,) is worked as both operator and separator and has the least priority.

Comma as an operator acts as a sequence point. When evaluating an expression with more than one operand separated by a comma, it’ll evaluate and discard all except the last one.

Comma behaves as a separator in the case of function calls and definitions, variable declarations, enum declarations, and similar constructs.

2. Post-increment and decrement operator

The post increment/decrement operator behaves in a unique way. It has the highest priority(hence, applied to the immediate variable), however, it’s done i.e. reflected in the memory after the statement is completed. See the example below,

An example involving pointer:

Helpful Links

Please follow C Programming tutorials or the menu in the sidebar for the complete tutorial series.

Also for the example C programs please refer to C Programming Examples . All examples are hosted on Github .

Recommended Books

An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

guest

associativity of unary operator is wrong it should be !,~,++,–,+-,*,sizeof

  • Algorithm Tutorials
  • C Programming Examples
  • C Programming tutorials
  • Complete Python Tutorials – Beginner to Advanced
  • Data Structure Tutorials
  • Python Programming Examples – Basic to Advanced
  • Subscribe to our Newsletter !!

C Programming Tutorial

  • Assignment Operator in C

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:

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:

are called assignment expression. If we put a semicolon( ; ) at the end of the expression like this:

then the assignment expression becomes assignment statement.

Compound Assignment Operator #

Assignment operations that use the old value of a variable to compute its new value are called Compound Assignment.

Consider the following two statements:

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:

The following program demonstrates Compound assignment operators in action:

Expected Output:

Load Comments

  • Intro to C Programming
  • Installing Code Blocks
  • Creating and Running The First C Program
  • Basic Elements of a C Program
  • Keywords and Identifiers
  • Data Types in C
  • Constants in C
  • Variables in C
  • Input and Output in C
  • Formatted Input and Output in C
  • Arithmetic Operators in C
  • Operator Precedence and Associativity in C
  • Increment and Decrement Operators in C
  • Relational Operators in C
  • Logical Operators in C
  • Conditional Operator, Comma operator and sizeof() operator in C
  • Implicit Type Conversion in C
  • Explicit Type Conversion in C
  • if-else statements in C
  • The while loop in C
  • The do while loop in C
  • The for loop in C
  • The Infinite Loop in C
  • The break and continue statement in C
  • The Switch statement in C
  • Function basics in C
  • The return statement in C
  • Actual and Formal arguments in C
  • Local, Global and Static variables in C
  • Recursive Function in C
  • One dimensional Array in C
  • One Dimensional Array and Function in C
  • Two Dimensional Array in C
  • Pointer Basics in C
  • Pointer Arithmetic in C
  • Pointers and 1-D arrays
  • Pointers and 2-D arrays
  • Call by Value and Call by Reference in C
  • Returning more than one value from function in C
  • Returning a Pointer from a Function in C
  • Passing 1-D Array to a Function in C
  • Passing 2-D Array to a Function in C
  • Array of Pointers in C
  • Void Pointers in C
  • The malloc() Function in C
  • The calloc() Function in C
  • The realloc() Function in C
  • String Basics in C
  • The strlen() Function in C
  • The strcmp() Function in C
  • The strcpy() Function in C
  • The strcat() Function in C
  • Character Array and Character Pointer in C
  • Array of Strings in C
  • Array of Pointers to Strings in C
  • The sprintf() Function in C
  • The sscanf() Function in C
  • Structure Basics in C
  • Array of Structures in C
  • Array as Member of Structure in C
  • Nested Structures in C
  • Pointer to a Structure in C
  • Pointers as Structure Member in C
  • Structures and Functions in C
  • Union Basics in C
  • typedef statement in C
  • Basics of File Handling in C
  • fputc() Function in C
  • fgetc() Function in C
  • fputs() Function in C
  • fgets() Function in C
  • fprintf() Function in C
  • fscanf() Function in C
  • fwrite() Function in C
  • fread() Function in C

Recent Posts

  • Machine Learning Experts You Should Be Following Online
  • 4 Ways to Prepare for the AP Computer Science A Exam
  • Finance Assignment Online Help for the Busy and Tired Students: Get Help from Experts
  • Top 9 Machine Learning Algorithms for Data Scientists
  • Data Science Learning Path or Steps to become a data scientist Final
  • Enable Edit Button in Shutter In Linux Mint 19 and Ubuntu 18.04
  • Python 3 time module
  • Pygments Tutorial
  • How to use Virtualenv?
  • Installing MySQL (Windows, Linux and Mac)
  • What is if __name__ == '__main__' in Python ?
  • Installing GoAccess (A Real-time web log analyzer)
  • Installing Isso

MarketSplash

Mastering The Art Of Assignment: Exploring C Assignment Operators

Dive into the world of C Assignment Operators in our extensive guide. Understand the syntax, deep-dive into variables, and explore complex techniques and practical applications.

💡 KEY INSIGHTS

  • Assignment operators in C are not just for basic value assignment; they enable simultaneous arithmetic operations, enhancing code efficiency and readability.
  • The article emphasizes the importance of understanding operator precedence in C, as misinterpretation can lead to unexpected results, especially with compound assignment operators.
  • Common mistakes like confusing assignment with equality ('=' vs '==') are highlighted, offering practical advice for avoiding such pitfalls in C programming.
  • The guide provides real-world analogies for each assignment operator, making complex concepts more relatable and easier to grasp for programmers.
Welcome, bold programmers and coding enthusiasts! Let's set the stage: you're at your desk, fingers hovering over the keyboard, ready to embark on a journey deep into the belly of C programming. You might be wondering, why do I need to know about these 'assignment operators'?

Well, imagine trying to build a house with a toolbox that only has a hammer. You could probably make something that vaguely resembles a house, but without a screwdriver, wrench, or saw, it's going to be a bit...wobbly. This, my friends, is the importance of understanding operators in C. They're like the indispensable tools in your coding toolbox. And today, we're honing in on the assignment operators .

Now, our mission, should we choose to accept it, is to delve into the world of assignment operators in C. Like secret agents discovering the inner workings of a villain's lair, we're going to uncover the secrets that these '=' or '+=' symbols hold.

To all the night owls out there, I see you, and I raise you an operator. Just like how a cup of coffee (or three) helps us conquer that midnight oil, mastering operators in C can transform your coding journey from a groggy stumble to a smooth sprint.

But don't just take my word for it. Let's take a real-world example. Imagine you're coding a video game. You need your character to jump higher each time they collect a power-up. Without assignment operators, you'd be stuck adding numbers line by line. But with the '+=' operator, you can simply write 'jumpHeight += powerUpBoost,' and your code becomes a thing of elegance. It's like going from riding a tricycle to a high-speed motorbike.

In this article, we're going to unpack, examine, and get intimately acquainted with these assignment operators. We'll reveal their secrets, understand their behaviors, and learn how to use them effectively to power our C programming skills to new heights. Let's strap in, buckle up, and get ready for takeoff into the cosmic realms of C assignment operators!

The Basics Of C Operators

Deep dive into assignment operators in c, detailed exploration of each assignment operator, common use cases of assignment operators, common mistakes and how to avoid them, practice exercises, references and further reading.

Alright, get ready to pack your mental suitcase as we prepare to embark on the grand tour of C operators. We'll be stopping by the various categories, getting to know the locals (the operators, that is), and understanding how they contribute to the vibrant community that is a C program.

What Are Operators In C?

Operators in C are like the spicy condiments of coding. Without them, you'd be left with a bland dish—or rather, a simple list of variables. But splash on some operators, and suddenly you've got yourself an extravagant, dynamic, computational feast. In technical terms, operators are special symbols that perform specific operations on one, two, or three operands, and then return a result . They're the magic sauce that allows us to perform calculations, manipulate bits, and compare data.

Categories Of Operators In C

Now, just as you wouldn't use hot sauce on your ice cream (unless that's your thing), different operators serve different purposes. C language has been generous enough to provide us with a variety of operator categories, each with its distinct charm and role.

Let's break it down:

Imagine you're running a pizza shop. The arithmetic operators are like your basic ingredients: cheese, sauce, dough. They form the foundation of your pizza (program). But then you want to offer different pizza sizes. That's where your relational operators come in, comparing the diameter of small, medium, and large pizzas.

You're going well, but then you decide to offer deals. Buy two pizzas, get one free. Enter the logical operators , evaluating whether the conditions for the deal have been met. And finally, you want to spice things up with some exotic ingredients. That's your bitwise operators , working behind the scenes, adding that unique flavor that makes your customers keep coming back.

However, today, we're going to focus on a particular subset of the arithmetic operators: the assignment operators . These are the operators that don't just make the pizza but ensure it reaches the customer's plate (or in this case, the right variable).

Next up: We explore these unsung heroes of the programming world, toasting their accomplishments and discovering their capabilities. So, hold onto your hats and glasses, folks. This here's the wildest ride in the coding wilderness!

Prepare your diving gear and adjust your oxygen masks, friends, as we're about to plunge deep into the ocean of C programming. Hidden in the coral reef of code, you'll find the bright and beautiful creatures known as assignment operators.

What Are Assignment Operators?

In the broad ocean of C operators, the assignment operators are the dolphins - intelligent, adaptable, and extremely useful. On the surface, they may appear simple, but don't be fooled; these creatures are powerful. They have the capability to not only assign values to variables but also perform arithmetic operations concurrently.

The basic assignment operator in C is the '=' symbol. It's like the water of the ocean, essential to life (in the world of C programming). But alongside this staple, we have a whole family of compound assignment operators including '+=', '-=', '*=', '/=', and '%='. These are the playful dolphins leaping out of the water, each adding their unique twist to the task of assignment.

Syntax And Usage Of Assignment Operators

Remember, even dolphins have their ways of communicating, and so do assignment operators. They communicate through their syntax. The syntax for assignment operators in C follows a simple pattern:

In this dance, the operator and the '=' symbol perform a duet, holding onto each other without a space in between. They're the dancing pair that adds life to the party (aka your program).

Let's say you've won the lottery (congratulations, by the way!) and you want to divide your winnings between your three children. You could write out the arithmetic long-hand, or you could use the '/=' operator to streamline your process:

Just like that, your winnings are divided evenly, no calculator required.

List Of Assignment Operators In C

As promised, let's get to know the whole family of assignment operators residing in the C ocean:

Alright, we've taken the plunge and gotten our feet wet (or fins, in the case of our dolphin friends). But the dive is far from over. Next up, we're going to swim alongside each of these assignment operators, exploring their unique behaviors and abilities in the wild, vibrant world of C programming. So, keep your scuba gear on and get ready for more underwater adventure!

Welcome back, dear diver! Now that we've acquainted ourselves with the beautiful pod of dolphins, aka assignment operators, it's time to learn about each dolphin individually. We're about to uncover their quirks, appreciate their styles, and recognize their talents.

The Simple Assignment Operator '='

Let's start with the leader of the pack: the '=' operator. This unassuming symbol is like the diligent mail carrier, ensuring the right packages (values) get to the correct houses (variables).

Take a look at this:

In this code snippet, '=' ensures that the value '5' gets assigned to the variable 'chocolate'. Simple as that. No muss, no fuss, just a straightforward delivery of value.

The Addition Assignment Operator '+='

Next, we have the '+=' operator. This operator is a bit like a friendly baker. He takes what he has, adds more ingredients, and gives you the result - a delicious cake! Or, in this case, a new value.

Consider this:

We started with 12 doughnuts. But oh look, a friend dropped by with 3 more! So we add those to our box, and now we have 15. The '+=' operator made that addition quick and easy.

The Subtraction Assignment Operator '-='

Following the '+=' operator, we have its twin but with a different personality - the '-=' operator. If '+=' is the friendly baker, then '-=' is the weight-conscious friend who always removes extra toppings from their pizza. They take away rather than add.

For instance:

You've consumed 2000 calories today, but then you went for a run and burned 500. The '-=' operator is there to quickly update your calorie count.

The Multiplication Assignment Operator '*='

Say hello to the '*=' operator. This one is like the enthusiastic party planner who multiplies the fun! They take your initial value and multiply it with another, bringing more to the table.

Check this out:

You're at a level 7 excitement about your upcoming birthday, but then you learn that your best friend is flying in to celebrate with you. Your excitement level just doubled, and '*=' is here to make that calculation easy.

The Division Assignment Operator '/='

Here's the '/=' operator, the calm and composed yoga teacher of the group. They're all about division and balance. They take your original value and divide it by another, bringing harmony to your code.

You're pretty anxious about your job interview - let's say a level 10 anxiety. But then you do some deep breathing exercises, which helps you halve your anxiety level. The '/=' operator helps you reflect that change in your code.

The Modulus Assignment Operator '%='

Finally, we meet the quirky '%=' operator, the mystery novelist of the group. They're not about the whole story but the remainder, the leftovers, the little details others might overlook.

Look at this:

You have 10 books to distribute equally among your 3 friends. Everyone gets 3, and you're left with 1 book. The '%=' operator is there to quickly calculate that remainder for you.

That's the end of our detailed exploration. I hope this underwater journey has provided you with a greater appreciation and understanding of these remarkable creatures. Remember, each operator, like a dolphin, has its unique abilities, and knowing how to utilize them effectively can greatly enhance your programming prowess.

Now, let's swerve away from the theoretical and deep-dive into the practical. After all, C assignment operators aren't just sparkling little seashells you collect and admire. They're more like versatile tools in your programming Swiss Army knife. So, let's carve out some real-world use cases for our cherished assignment operators.

Variable Initialization And Value Change

Assignment operators aren't just for show; they've got some moves. Take our plain and humble '='. It's the bread-and-butter operator used in variable initialization and value changes, helping your code be as versatile as a chameleon.

In this scenario, our friend '=' is doing double duty—initializing 'a' with the value 10 and then changing it to 20. Not flashy, but oh-so-vital.

Calculation Updates In Real-Time Applications

Assignment operators are like those awesome, multitasking waitstaff you see in busy restaurants, juggling multiple tables and orders while still managing to serve everyone with a smile. They are brilliant when you want to perform real-time updates to your data.

In this scenario, '+=' and '-=' are the maitre d' of our code-restaurant, updating the user's balance with each buy or sell order.

Running Totals And Averages

Assignment operators are great runners - they don't tire and always keep the tally running.

Here, the '+=' and '-=' operators keep a running tally of points, allowing the system to adjust to the ebbs and flows of the school year like a seasoned marathon runner pacing themselves.

Iterations In Loop Constructs

The '*=' and '/=' operators often lurk within loop constructs, handling iterations with the grace of a prima ballerina. They're the choreographers of your loops, making sure each iteration flows seamlessly into the next.

In this case, '/=' is the elegant dancer gracefully halving 'i' with each twirl across the dance floor (iteration).

Working With Remainders

And let's not forget our mysterious '%=', the detective of the bunch, always searching for the remainder, the evidence left behind.

Here, '%=' is the sleuth, determining whether a number is even or odd by examining the remainder when divided by 2.

So, these are just a few examples of how assignment operators flex their muscles in the real world. They're like superheroes, each with their unique powers, ready to assist you in writing clean, efficient, and understandable code. Use them wisely, and your code will be as smooth as a well-choreographed ballet.

Let's face it, even the best of us trip over our own feet sometimes. And when it comes to assignment operators in C, there are some pitfalls that could make you stumble. But don't worry! We've all been there. Let's shed some light on these common mistakes so we can step over them with the grace of a ballet dancer leaping over a pit of snapping alligators.

Confusing Assignment With Equality

A surprisingly common misstep is confusing the assignment operator '=' with the equality operator '=='. It's like mixing up salt with sugar while baking. Sure, they might look similar, but one will definitely not sweeten your cake.

In this snippet, instead of checking if 'a' equals 10, we've assigned 'a' the value 10. The compiler will happily let this pass and might even give you a standing ovation for your comedy of errors. The correct approach?

Overlooking Operator Precedence

C operators are a bit like the characters in "Game of Thrones." They've got a complex hierarchy and they respect the rule of precedence. Sometimes, this can lead to unexpected results. For instance, check out this bit of misdirection:

Here, '/=' doesn't immediately divide 'a' by 2. It waits for the multiplication to happen (due to operator precedence), and then performs the operation. So it's actually doing a /= (2*5), not (a/=2)*5. It's like arriving late to a party and finding out all the pizza is gone. To ensure you get your slice, use parentheses:

Misusing Modulo With Floats

Ah, the modulo operator, always looking for the remainder. But when you ask it to work with floats, it gets as confused as a penguin in a desert. It simply can't compute.

Modulo and floats go together like oil and water. The solution? Stick to integers when dealing with '%='.

So there you have it. Some common missteps while dancing with assignment operators and the quick moves to avoid them. Just remember, every great coder has tripped before. The key is to keep your chin up, learn from your stumbles, and soon you'll be waltzing with assignment operators like a seasoned pro.

Alright, amigos! It's time to put your newfound knowledge to the test. After all, becoming a master in the art of C assignment operators is not a walk in the park, it's a marathon run on a stony path with occasional dance-offs. So brace yourselves and let's get those brain cells pumping.

Exercise 1: The Shy Variable

Your task here is to write a C program that initializes an integer variable to 10. Then, using only assignment operators, make that variable as shy as a teenager at their first dance. I mean, reduce it to zero without directly assigning it to zero. You might want to remember the '/=' operator here. He's like the high school wallflower who can suddenly breakdance like a champ when the music starts playing.

Exercise 2: Sneaky Increment

The '+=' operator is like the mischievous friend who always pushes you into the spotlight when you least expect it. Create a program that initializes an integer to 0. Then, using a loop and our sneaky '+=' friend, increment that variable until it's equal to 100. Here's the catch: You can't use '+=' with anything greater than 1. It's a slow and steady race to the finish line!

Exercise 3: Modulo Madness

Remember the modulo operator? It's like the friend who always knows how much pizza is left over after a party. Create a program that counts from 1 to 100. But here's the twist: for every number that's divisible by 3, print "Fizz", and for every number divisible by 5, print "Buzz". If a number is divisible by both 3 and 5, print "FizzBuzz". For all other numbers, just print the number. This will help you get better acquainted with our friend '%='.

Exercise 4: Swapping Values

Create a program that swaps the values of two variables without using a third temporary variable. Remember, your only allies here are the assignment operators. This is like trying to switch places on the dance floor without stepping on anyone's toes.

Exercise 5: Converting Fahrenheit To Celsius

Let's play with the ' =' operator. Write a program that converts a temperature in Fahrenheit to Celsius. The formula to convert Fahrenheit to Celsius is (Fahrenheit - 32) * 5 / 9 . As a challenge, try doing the conversion in a single line using the '-=', ' =' and '/=' operators. It's like preparing a complicated dinner recipe using only a few simple steps.

Remember, practice makes perfect, especially when it comes to mastering C assignment operators. Don't be disheartened if you stumble, just dust yourself off and try again. Because as the saying goes, "The master has failed more times than the beginner has even tried". So, good luck, and happy coding!

References and Further Reading

So, you've reached the end of this riveting journey through the meadows of C assignment operators. It's been quite a ride, hasn't it? We've shared laughs, shed tears, and hopefully, we've learned a thing or two. But remember, the end of one journey marks the beginning of another. It's like eating at a buffet – you might be done with the pasta, but there's still the sushi to try! So, here are some materials to sink your teeth into for the next course of your coding feast.

1. The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie

This book, also known as 'K&R' after its authors, is the definitive guide to C programming. It's like the "Godfather" of programming books – deep, powerful, and a little intimidating at times. But hey, we all know that the best lessons come from challenging ourselves.

2. Expert C Programming by Peter van der Linden

Consider this book as the "Star Wars" to the "Godfather" of 'K&R'. It has a bit more adventure and a lot of real-world applications to keep you engaged. Not to mention some rather amusing footnotes.

3. C Programming Absolute Beginner's Guide by Greg Perry and Dean Miller

This one's for you if you're still feeling a bit wobbly on your C programming legs. Think of it as a warm hug from a friend who's been there and done that. It's simple, straightforward, and gently walks you through the concepts.

4. The Pragmatic Programmer by Andrew Hunt and David Thomas

Even though it's not about C specifically, this book is a must-read for any serious programmer. It's like a mentor who shares all their best tips and tricks for mastering the craft. It's filled with practical advice and real-life examples to help you on your programming journey.

This is a great online resource for interactive C tutorials. It's like your favorite video game, but it's actually helping you become a better programmer.

6. Cprogramming.com

This website has a vast collection of articles, tutorials, and quizzes on C programming. It's like an all-you-can-eat buffet for your hungry, coding mind.

Remember, every master was once a beginner, and every beginner can become a master. So, keep reading, keep practicing, and keep coding. And most importantly, don't forget to have fun while you're at it. After all, as Douglas Adams said, "I may not have gone where I intended to go, but I think I have ended up where I needed to be." Here's to ending up where you need to be in your coding journey!

As our immersive journey into C Assignment Operators culminates, we've unraveled the nuanced details of these powerful tools. From fundamental syntax to intricate applications, C Assignment Operators have showcased their indispensability in coding. Equipped with this newfound understanding, it's time for you to embark on your coding adventures, mastering the digital realm with the prowess of C Assignment Operators!

Which C assignment operator adds a value to a variable?

Please submit an answer to see if you're correct!

Continue Learning With These C Guides

  • C Syntax Explained: From Variables To Functions
  • C Programming Basics And Its Applications
  • Basic C Programming Examples For Beginners
  • C Data Types And Their Usage
  • C Variables And Their Usage

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

C Data Types

C operators.

  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors

C File Handling

  • C Cheatsheet

C Interview Questions

  • Solve Coding Problems
  • C Programming Language Tutorial
  • C Language Introduction
  • Features of C Programming Language
  • C Programming Language Standard
  • C Hello World Program
  • Compiling a C Program: Behind the Scenes
  • Tokens in C
  • Keywords in C

C Variables and Constants

  • C Variables
  • Constants in C
  • Const Qualifier in C
  • Different ways to declare variable as constant in C
  • Scope rules in C
  • Internal Linkage and External Linkage in C
  • Global Variables in C
  • Data Types in C
  • Literals in C
  • Escape Sequence in C
  • Integer Promotions in C
  • Character Arithmetic in C
  • Type Conversion in C

C Input/Output

  • Basic Input and Output in C
  • Format Specifiers in C
  • printf in C
  • Scansets in C
  • Formatted and Unformatted Input/Output functions in C with Examples
  • Operators in C
  • Arithmetic Operators in C
  • Unary operators in C
  • Relational Operators in C
  • Bitwise Operators in C
  • C Logical Operators

Assignment Operators in C

  • Increment and Decrement Operators in C
  • Conditional or Ternary Operator (?:) in C
  • sizeof operator in C
  • Operator Precedence and Associativity in C

C Control Statements Decision-Making

  • Decision Making in C (if , if..else, Nested if, if-else-if )
  • C - if Statement
  • C if...else Statement
  • C if else if ladder
  • Switch Statement in C
  • Using Range in switch Case in C
  • while loop in C
  • do...while Loop in C
  • For Versus While
  • Continue Statement in C
  • Break Statement in C
  • goto Statement in C
  • User-Defined Function in C
  • Parameter Passing Techniques in C
  • Function Prototype in C
  • How can I return multiple values from a function?
  • main Function in C
  • Implicit return type int in C
  • Callbacks in C
  • Nested functions in C
  • Variadic functions in C
  • _Noreturn function specifier in C
  • Predefined Identifier __func__ in C
  • C Library math.h Functions

C Arrays & Strings

  • Properties of Array in C
  • Multidimensional Arrays in C
  • Initialization of Multidimensional Array in C
  • Pass Array to Functions in C
  • How to pass a 2D array as a parameter in C?
  • What are the data types for which it is not possible to create an array?
  • How to pass an array by value in C ?
  • Strings in C
  • Array of Strings in C
  • What is the difference between single quoted and double quoted declaration of char array?
  • C String Functions
  • Pointer Arithmetics in C with Examples
  • C - Pointer to Pointer (Double Pointer)
  • Function Pointer in C
  • How to declare a pointer to a function?
  • Pointer to an Array | Array Pointer
  • Difference between constant pointer, pointers to constant, and constant pointers to constants
  • Pointer vs Array in C
  • Dangling, Void , Null and Wild Pointers in C
  • Near, Far and Huge Pointers in C
  • restrict keyword in C

C User-Defined Data Types

  • C Structures
  • dot (.) Operator in C
  • Structure Member Alignment, Padding and Data Packing
  • Flexible Array Members in a structure in C
  • Bit Fields in C
  • Difference Between Structure and Union in C
  • Anonymous Union and Structure in C
  • Enumeration (or enum) in C

C Storage Classes

  • Storage Classes in C
  • extern Keyword in C
  • Static Variables in C
  • Initialization of static variables in C
  • Static functions in C
  • Understanding "volatile" qualifier in C | Set 2 (Examples)
  • Understanding "register" keyword in C

C Memory Management

  • Memory Layout of C Programs
  • Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
  • Difference Between malloc() and calloc() with Examples
  • What is Memory Leak? How can we avoid?
  • Dynamic Array in C
  • How to dynamically allocate a 2D array in C?
  • Dynamically Growing Array in C

C Preprocessor

  • C Preprocessor Directives
  • How a Preprocessor works in C?
  • Header Files in C
  • What’s difference between header files "stdio.h" and "stdlib.h" ?
  • How to write your own header file in C?
  • Macros and its types in C
  • Interesting Facts about Macros and Preprocessors in C
  • # and ## Operators in C
  • How to print a variable name in C?
  • Multiline macros in C
  • Variable length arguments for Macros
  • Branch prediction macros in GCC
  • typedef versus #define in C
  • Difference between #define and const in C?
  • Basics of File Handling in C
  • C fopen() function with Examples
  • EOF, getc() and feof() in C
  • fgets() and gets() in C language
  • fseek() vs rewind() in C
  • What is return type of getchar(), fgetc() and getc() ?
  • Read/Write Structure From/to a File in C
  • C Program to print contents of file
  • C program to delete a file
  • C Program to merge contents of two files into a third file
  • What is the difference between printf, sprintf and fprintf?
  • Difference between getc(), getchar(), getch() and getche()

Miscellaneous

  • time.h header file in C with Examples
  • Input-output system calls in C | Create, Open, Close, Read, Write
  • Signals in C language
  • Program error signals
  • Socket Programming in C
  • _Generics Keyword in C
  • Multithreading in C
  • C Programming Interview Questions (2024)
  • Commonly Asked C Programming Interview Questions | Set 1
  • Commonly Asked C Programming Interview Questions | Set 2
  • Commonly Asked C Programming Interview Questions | Set 3

c assignment precedence

Assignment operators are used for assigning value to a variable. The left side operand of the assignment operator is a variable and right side operand of the assignment operator is a value. The value on the right side must be of the same data-type of the variable on the left side otherwise the compiler will raise an error.

Different types of assignment operators are shown below:

1. “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example:

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 then assigns the result to the variable on the left. Example:

If initially value stored in a is 5. Then (a += 6) = 11.

3. “-=” This operator is combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on the right from the current value of the variable on left and then assigns the result to the variable on the left. Example:

If initially value stored in a is 8. Then (a -= 6) = 2.

4. “*=” This operator is combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 5. Then (a *= 6) = 30.

5. “/=” This operator is combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. Example:

If initially value stored in a is 6. Then (a /= 2) = 3.

Below example illustrates the various Assignment Operators:

Please Login to comment...

  • C-Operators
  • cpp-operator
  • WhatsApp To Launch New App Lock Feature
  • Top Design Resources for Icons
  • Node.js 21 is here: What’s new
  • Zoom: World’s Most Innovative Companies of 2024
  • 30 OOPs Interview Questions and Answers (2024)

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Learn C++

6.1 — Operator precedence and associativity

Chapter introduction

This chapter builds on top of the concepts from lesson 1.9 -- Introduction to literals and operators . A quick review follows:

An operation is a mathematical process involving zero or more input values (called operands ) that produces a new value (called an output value). The specific operation to be performed is denoted by a construct (typically a symbol or pair of symbols) called an operator .

For example, as children we all learn that 2 + 3 equals 5 . In this case, the literals 2 and 3 are the operands, and the symbol + is the operator that tells us to apply mathematical addition on the operands to produce the new value 5 . Because there is only one operator being used here, this is straightforward.

In this chapter, we’ll discuss topics related to operators, and explore many of the common operators that C++ supports.

Evaluation of compound expressions

Now, let’s consider a compound expression, such as 4 + 2 * 3 . Should this be grouped as (4 + 2) * 3 which evaluates to 18 , or 4 + (2 * 3) which evaluates to 10 ? Using normal mathematical precedence rules (which state that multiplication is resolved before addition), we know that the above expression should be grouped as 4 + (2 * 3) to produce the value 10 . But how does the compiler know?

In order to evaluate an expression, the compiler must do two things:

  • At compile time, the compiler must parse the expression and determine how operands are grouped with operators. This is done via the precedence and associativity rules, which we’ll discuss momentarily.
  • At compile time or runtime, the operands are evaluated and operations executed to produce a result.

Operator precedence

To assist with parsing a compound expression, all operators are assigned a level of precedence. Operators with a higher precedence level are grouped with operands first.

You can see in the table below that multiplication and division (precedence level 5) have a higher precedence level than addition and subtraction (precedence level 6). Thus, multiplication and division will be grouped with operands before addition and subtraction. In other words, 4 + 2 * 3 will be grouped as 4 + (2 * 3) .

Operator associativity

Consider a compound expression like 7 - 4 - 1 . Should this be grouped as (7 - 4) - 1 which evaluates to 2 , or 7 - (4 - 1) , which evaluates to 4 ? Since both subtraction operators have the same precedence level, the compiler can not use precedence alone to determine how this should be grouped.

If two operators with the same precedence level are adjacent to each other in an expression, the operator’s associativity tells the compiler whether to evaluate the operators from left to right or from right to left. Subtraction has precedence level 6, and the operators in precedence level 6 have an associativity of left to right. So this expression is grouped from left to right: (7 - 4) - 1 .

Table of operator precedence and associativity

The below table is primarily meant to be a reference chart that you can refer back to in the future to resolve any precedence or associativity questions you have.

  • Precedence level 1 is the highest precedence level, and level 17 is the lowest. Operators with a higher precedence level have their operands grouped first.
  • L->R means left to right associativity.
  • R->L means right to left associativity.

You should already recognize a few of these operators, such as + , - , * , / , () , and sizeof . However, unless you have experience with another programming language, the majority of the operators in this table will probably be incomprehensible to you right now. That’s expected at this point. We’ll cover many of them in this chapter, and the rest will be introduced as there is a need for them.

Q: Where is the exponent operator?

C++ doesn’t include an operator to do exponentiation ( operator^ has a different function in C++). We discuss exponentiation more in lesson 6.3 -- Remainder and Exponentiation .

Note that operator<< handles both bitwise left shift and insertion, and operator>> handles both bitwise right shift and extraction. The compiler can determine which operation to perform based on the types of the operands.

Parenthesization

Due to the precedence rules, 4 + 2 * 3 will be grouped as 4 + (2 * 3) . But what if we actually meant (4 + 2) * 3 ? Just like in normal mathematics, in C++ we can explicitly use parentheses to set the grouping of operands as we desire. This works because parentheses have one of the highest precedence levels, so parentheses generally evaluate before whatever is inside them.

Use parenthesis to make compound expressions easier to understand

Now consider an expression like x && y || z . Does this evaluate as (x && y) || z or x && (y || z) ? You could look up in the table and see that && takes precedence over || . But there are so many operators and precedence levels that it’s hard to remember them all. And you don’t want to have to look up operators all the time to understand how a compound expression evaluates.

In order to reduce mistakes and make your code easier to understand without referencing a precedence table, it’s a good idea to parenthesize any non-trivial compound expression, so it’s clear what your intent is.

Best practice

Use parentheses to make it clear how a non-trivial compound expression should evaluate (even if they are technically unnecessary).

A good rule of thumb is: Parenthesize everything, except addition, subtraction, multiplication, and division.

There is one additional exception to the above best practice: Expressions that have a single assignment operator (and no comma operator) do not need to have the right operand of the assignment wrapped in parenthesis.

For example:

The assignment operators have the second lowest precedence (only the comma operator is lower, and it’s rarely used). Therefore, so long as there is only one assignment (and no commas), we know the right operand will fully evaluate before the assignment.

Expressions with a single assignment operator do not need to have the right operand of the assignment wrapped in parenthesis.

Value computation (of operations)

The C++ standard uses the term value computation to mean the execution of operators in an expression to produce a value. The precedence and association rules determine the order in which value computation happens.

For example, given the expression 4 + 2 * 3 , due to the precedence rules this groups as 4 + (2 * 3) . 2 * 3 must be evaluated first, so that the resulting value of 6 can be used as the right operand of operator+ .

Key insight

The precedence and associativity rules generally determine the order of value computation (of operators).

Order of evaluation (of operands)

The C++ standard (mostly) uses the term evaluation to refer to the evaluation of operands (not the evaluation of operators or expressions!). For example, given expression a + b , a will be evaluated to produce some value, and b will be evaluated to produce some value. These values can be then used as operands to operator+ to compute a value.

Nomenclature

Informally, we typically use the term “evaluates” to mean the evaluation of an entire expression (value computation), not just the operands of an expression.

The order of evaluation of operands and function arguments is mostly unspecified

In most cases, the order of evaluation for operands and function arguments is unspecified, meaning they may be evaluated in any order.

Consider the following expression:

We know from the precedence and associativity rules above that this expression will be grouped as if we had typed:

If a is 1 , b is 2 , c is 3 , and d is 4 , this expression will always compute the value 14 .

However, the precedence and associativity rules only tell us how operators and operands are grouped and the order in which value computation will occur. They do not tell us the order in which the operands or subexpressions are evaluated. The compiler is free to evaluate operands a , b , c , or d in any order. The compiler is also free to calculate a * b or c * d first.

For most expressions, this is irrelevant. In our sample expression above, it doesn’t matter whether in which order variables a , b , c , or d are evaluated for their values: the value calculated will always be 14 . There is no ambiguity here.

But it is possible to write expressions where the order of evaluation does matter. Consider this program, which contains a mistake often made by new C++ programmers:

If you run this program and enter the inputs 1 , 2 , and 3 , you might assume that this program would calculate 1 + (2 * 3) and print 7 . But that is making the assumption that the arguments to printCalculation() will evaluate in left-to-right order (so parameter x gets value 1 , y gets value 2 , and z gets value 3 ). If instead, the arguments evaluate in right-to-left order (so parameter z gets value 1 , y gets value 2 , and x gets value 3 ), then the program will print 5 instead.

The Clang compiler evaluates arguments in left-to-right order. The GCC compiler evaluates arguments in right-to-left order. You can run the above program on each of these compilers (e.g. on Wandbox ) and see for yourself.

The above program can be made unambiguous by making each function call to getValue() a separate statement:

In this version, a will always have value 1 , b will have value 2 , and c will have value 3 . When the arguments to printCalculation() are evaluated, it doesn’t matter which order the argument evaluation happens in -- parameter x will always get value 1 , y will get value 2 , and z will get value 3 . This version will deterministically print 7 .

Operands, function arguments, and subexpressions may be evaluated in any order.

Ensure that the expressions (or function calls) you write are not dependent on operand (or argument) evaluation order.

Related content

Operators with side effects can also cause unexpected evaluation results. We cover this in lesson 6.4 -- Increment/decrement operators, and side effects .

Question #1

You know from everyday mathematics that expressions inside of parentheses get evaluated first. For example, in the expression (2 + 3) * 4 , the (2 + 3) part is evaluated first.

For this exercise, you are given a set of expressions that have no parentheses. Using the operator precedence and associativity rules in the table above, add parentheses to each expression to make it clear how the compiler will evaluate the expression.

a) x = 3 + 4 + 5;

Show Solution

Binary operator + has higher precedence than = :

x = (3 + 4 + 5);

Binary operator + has left to right association:

Final answer: x = ((3 + 4) + 5);

b) x = y = z;

Binary operator = has right to left association:

Final answer: x = (y = z);

c) z *= ++y + 5;

Unary operator ++ has the highest precedence:

z *= (++y) + 5;

Binary operator + has the next highest precedence:

Final answer: z *= ((++y) + 5);

d) a || b && c || d;

Binary operator && has higher precedence than || :

a || (b && c) || d;

Binary operator || has left to right association:

Final answer: (a || (b && c)) || d;

guest

C++ Operator Precedence

The following table lists the precedence and associativity of C++ operators. Operators are listed top to bottom, in descending precedence.

  • ↑ The operand of sizeof can't be a C-style type cast: the expression sizeof (int) * p is unambiguously interpreted as (sizeof(int)) * p , but not sizeof((int)*p) .
  • ↑ The expression in the middle of the conditional operator (between ? and : ) is parsed as if parenthesized: its precedence relative to ?: is ignored.

When parsing an expression, an operator which is listed on some row will be bound tighter (as if by parentheses) to its arguments than any operator that is listed on a row further below it. For example, the expressions std:: cout << a & b and * p ++ are parsed as ( std:: cout << a ) & b and * ( p ++ ) , and not as std:: cout << ( a & b ) or ( * p ) ++ .

Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same precedence, in the given direction. 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.

Operator precedence is unaffected by operator overloading .

[ edit ] Notes

Precedence and associativity are independent from order of evaluation .

The standard itself doesn't specify precedence levels. They are derived from the grammar.

const_cast , static_cast , dynamic_cast , reinterpret_cast , typeid , sizeof... , noexcept and alignof are not included since they are never ambiguous.

Some of the operators have alternate spellings (e.g., and for && , or for || , not for ! , etc.).

Relative precedence of the conditional and assignment operators differs between C and C++: in C, assignment is not allowed on the right hand side of a conditional operator, so e = a < d ? a ++ : a = d cannot be parsed. Many C compilers use a modified grammar where ?: has higher precedence than = , which parses that as e = ( ( ( a < d ) ? ( a ++ ) : a ) = d ) (which then fails to compile because ?: is never lvalue in C and = requires lvalue on the left). In C++, ?: and = have equal precedence and group right-to-left, so that e = a < d ? a ++ : a = d parses as e = ( ( a < d ) ? ( a ++ ) : ( a = d ) ) .

[ edit ] See also

  • Skip to Navigation
  • Skip to Main Content
  • Skip to Related Content
  • Today's news
  • Climate change
  • My portfolio
  • My watchlist
  • Stock market
  • Biden economy
  • Personal finance
  • Stocks: most actives
  • Stocks: gainers
  • Stocks: losers
  • Trending tickers
  • World indices
  • US Treasury bonds
  • Top mutual funds
  • Highest open interest
  • Highest implied volatility
  • Currency converter
  • Basic materials
  • Communication services
  • Consumer cyclical
  • Consumer defensive
  • Financial services
  • Industrials
  • Real estate
  • Mutual funds
  • Credit card rates
  • Balance transfer credit cards
  • Business credit cards
  • Cash back credit cards
  • Rewards credit cards
  • Travel credit cards
  • Checking accounts
  • Online checking accounts
  • High-yield savings accounts
  • Money market accounts
  • Personal loans
  • Student loans
  • Car insurance
  • Home buying
  • Options pit
  • Investment ideas
  • Research reports
  • Fantasy football
  • Pro Pick 'Em
  • College Pick 'Em
  • Fantasy baseball
  • Fantasy hockey
  • Fantasy basketball
  • Download the app
  • Daily Fantasy
  • Scores and schedules
  • GameChannel
  • World Baseball Classic
  • Premier League
  • CONCACAF League
  • Champions League
  • College football
  • Horse racing
  • Newsletters

Entertainment

  • How To Watch
  • Fall allergies
  • Health news
  • Mental health
  • Sexual health
  • Family health
  • So mini ways
  • Style and beauty
  • Unapologetically
  • Buying guides
  • Privacy Dashboard

c assignment precedence

  • March Madness
  • Yahoo Sports AM
  • Motorsports
  • College Sports
  • Fantasy Sports
  • Horse Racing
  • Top Free Agents
  • Scores/Schedules
  • Fantasy Baseball
  • World Series

Mets 2024 transaction tracker: Reliever Austin Adams traded to Oakland

Here is a look at the latest Mets roster moves...

March 24, 12:17 p.m.

The Mets announced on Sunday afternoon that reliever Austin Adams has been traded to the Oakland A’s for cash considerations.

Adams, 32, had previously been designated for assignment by the club.

The right-handed reliever originally signed with the Mets in November following stops with Arizona , San Diego , Seattle , and Washington.

Adams had a tough spring with the Mets. In seven appearances, the veteran allowed four earned runs on seven hits over 6.1 innings, posting a 1.26 WHIP.

March 23, 9:30 p.m.

With final roster decisions looming, the Mets made a flurry of moves prior to Saturday's spring training game.

After an up-and-down spring showing, right-hander  Shintaro Fujinami has been optioned to minor league camp, Mets manager Carlos Mendoza announced.

Austin Adams was also reassigned to minor league camp after he pitched to a 6.75 ERA across six spring appearances.

Righty Phil Bickford was designated for assignment to make room on the roster with the one-year deal with J.D. Martinez becoming official on Saturday morning.

Additionally, Mendoza said the team has told C Tomas Nido , INF Jose Iglesias , and 1B/DH Luke Voit that they have not cracked the big-league roster.

March 19, 2:51 p.m.

The Mets have reassigned six players to minor league camp: Right-handed pitchers  Kyle Crick , Yacksel Rios and  Cole Sulser , outfielders  Ben Gamel and Trayce Thompson and infielder Yolmer Sanchez .

Rios allowed just one hit in 5.0 innings over four appearances with six strikeouts and a walk. Sulser also allowed just one hit in 6.0 innings over five appearances with 10 strikeouts.

Thompson led the club with his six RBI in 11 spring training appearances. He had two doubles and two home runs among his six hits in 24 at-bats.

March 8, 4:12 p.m.

The Mets announced that three players have been reassigned to minor league camp: OF Taylor Kohlwey , RHP Chad Smith and LHP Nate Lavender .

In addition, OF Alex Ramirez has been optioned to Double-A while RHP Grant Hartwig and LHP Josh Walker have been optioned to Triple-A.

Ramirez, SNY's No. 18 Mets prospect , had a solid spring going 4-for-11 with a double, walk and RBI. He spent the entire 2023 season at High-A with the Brooklyn Cyclones.

March 3, 10:05 a.m.

The Mets announced a handful of roster moves on Sunday morning, with some of the organization's top prospects included.

The team announced that the following players have been reassigned to minor league camp: OF Drew Gilbert, RHP Eric Orze, C Kevin Parada, RHP Cam Robinson, RHP Christian Scott, RHP Mike Vasil, INF Jett Williams and LHP Danny Young.

In addition, INF Luisangel Acuña and LHP Kolton Ingram have been optioned to Triple-A.

Williams, Gilbert, and Acuña are ranked as Joe DeMayo’s Top 3 Mets prospects for the 2024 season. Scott and Vasil are also in DeMayo’s Top 10 prospects, and both players pitched for the Mets on Saturday begore being sent to minor league camp.

Acuña, 21, had eight at-bats with the big club this spring, hitting .375 with an RBI single.

Feb. 25, 4:55 p.m.

The Mets announced Sunday that they've claimed LHP Kolton Ingram off waivers from the Detroit Tigers .

In a corresponding move, the team transferred LHP David Peterson to the 60-day IL. Peterson had surgery to repair a torn labrum in his left hip in November and is expected to miss the first month or two of the season while working his way back to full health .

Ingram, 27, was drafted by the Tigers in the 37th round of the 2019 MLB Draft, but was later released in July 2020 while the minor league season was canceled due to the COVID-19 pandemic. He signed to the Los Angeles Angels organization in January 2021 and split the season between Single-A and Double-A. The team protected him from the Rule 5 draft in 2022 and he started 2023 in Triple-A.

The left-hander went 2-3 in Triple-A with a 3.21 ERA over 22 appearances and made his MLB debut with the Angels on June 15, 2023. He struggled over five outings with an 8.44 ERA in 5.1 innings. Ingram was then sent down to Double-A, where he went 1-1 with a 2.63 ERA over 23 outings, but was eventually DFA'd in January. He was claimed off waivers by the Tigers on Feb. 5, and then designated for assignment again on Feb. 20.

Feb. 11, 10:17 a.m.

The Mets announced Sunday that right-handed pitcher Austin Adams cleared waivers after being designated for assignment earlier this month. He was then outrighted to Triple-A Syracuse and will attend spring training as a minor league invite.

Adams was DFA’d on Feb. 6 to make room for recently-signed LHP Jake Diekman on the 40-man roster. Adams, who signed a one-year, non-guaranteed split major league contract with the Mets in November, will now have another chance to make the team out of spring training.

The righty had a 5.71 ERA and 1.38 WHIP across 17.1 innings with the Diamondbacks last season, but fractured his ankle in August, which ended his season.

Feb. 6, 4:43 p.m.

To make room for recently signed left-handed reliever Jake Diekman on the 40-man roster, the Mets have designated right-handed reliever Austin Adams for assignment.

Adams had signed a one-year major league, non-guaranteed split contract with the Mets in November.

He spent last season with the Arizona Diamondbacks, but his season was cut short due to a fractured ankle in early August.

He had a 5.71 ERA and 1.38 WHIP across just 17.1 innings.

Feb. 2, 2:10 p.m.

The Mets have traded catcher Tyler Heineman to the Boston Red Sox for cash considerations, the club announced Friday.

New York claimed Heineman off waivers from Toronto on Dec. 1, 2023, before designating him for assignment on Jan 30 to make room on the 40-man roster after signing reliever Adam Ottavino to a one-year deal.

In his last 84 big league games over the past two seasons bouncing between the Blue Jays and Pittsburgh Pirates , the 32-year-old catcher has a .221 average and .576 OPS over 221 plate appearances.

Friday was a busy day for the organization, as the Mets also agreed to sign right-handed reliever  Shintaro Fujinami and left-hander  Jake Diekman .

Jan. 30, 7:00 p.m.

The Mets made  Adam Ottavino 's one-year deal official on Tuesday night, and in a corresponding roster move to clear room on the 40-man roster, catcher Tyler Heineman  has been designated for assignment.

New York claimed Heineman off waivers from Toronto earlier this offseason, but his stay in the organization is short-lived.

The 32-year-old backstop has appeared in just 104 games and has a .218 average and .579 OPS in parts of four big league seasons with the Toronto Blue Jays, Pittsburgh Pirates, San Francisco Giants, and Marlins .

Recommended Stories

Fantasy baseball mlb team power rankings: who's on top ahead of opening day.

With just a few days left until Opening Day, Scott Pianowski ranks each MLB team based on their level of fantasy juice.

Deion Sanders wants son Shedeur and Travis Hunter to pull an Eli Manning at 2025 NFL Draft

If the wrong team takes Shedeur Sanders or Travis Hunter, Deion wants them to do what Eli Manning did in 2004 and request a trade.

Don't expand March Madness, it's perfect as is + Why Kentucky might be stuck with Calipari

Dan Wetzel, Ross Dellenger & SI’s Pat Forde kick off the podcast by reacting to the instant classic and finish between Houston and Texas A&M in the second round of March Madness. All three share their biggest takeaways from the first weekend of the tournament including Purdue's dominance so far and Kentucky's collapse against Oakland.

J.J. Watt likens NFL's hip-drop tackle ban to flag football as players sound off on controversial rule change

Reactions to the ban were impassioned and varied among NFL players past and present.

Sean Payton says it's 'realistic' for Broncos to trade up from No. 12 pick to draft QB

The Broncos are feeling frisky with that No. 12 pick.

Fantasy Hockey Waiver Wire: Timothy Liljegren leads pickups to start the week

Start the fantasy hockey week right with these pickups, led by a productive defenseman on the Maple Leafs.

2024 Fantasy Baseball Draft Kit: Your championship cheat sheet is here!

Ready to take your fantasy baseball draft prep to the next level? We've got you covered with everything you need for 2024?

USMNT beats Mexico for 3rd straight Nations League title on Tyler Adams' rocket, Gio Reyna's clincher

The USMNT beat Mexico 2-0, dos a cero, yet again, on two gorgeous goals.

Gio Reyna, 'so far past' the drama, has become the USMNT's most irreplaceable player

Gio Reyna and Gregg Berhalter have put the drama behind them, to the benefit of the USMNT.

March Madness: 5 takeaways from a thrilling Day 3 of the women's tournament

We finally got a couple of upsets on Sunday, while a near-upset produced the best game of the day at Stanford. And the title favorite did what it was supposed to.

March Madness Sunday recap: Surprise, the ACC has 4 teams in the Sweet 16

Houston held on in an overtime thriller on Sunday night to beat Texas A&M, and both UConn and San Diego State flew to blowout wins.

Are Cowboys’ really all-in? Compare them to Chiefs, and you’ll understand what Jerry Jones meant

The Cowboys' challenge: Can they rely on their core trifecta to go all the way, when in recent postseasons they’ve struggled to go *any* of the way?

March Madness: Kiki Iriafen, No. 2 Stanford fend off Iowa State in overtime to reach Sweet 16

It took an overtime shootout, but Stanford avenged last season's NCAA tournament loss and punched its ticket to the Sweet 16.

Lack of NCAA tournament upsets has a bright side: the Sweet 16 is loaded with marquee matchups

It's been an unusually chalky first two rounds of the tournament, but that means we get to watch many of the best teams and biggest brands next week.

West Virginia hiring Drake head coach Darian DeVries

West Virginia hasn't had a permanent head coach since Bob Huggins' tumultuous exit from the program last spring.

March Madness: No. 6 Clemson survives furious Baylor rally to beat back No. 3 Bears, advance to Sweet 16

Clemson almost blew a big lead, but held on to advance to the tournament's second weekend.

March Madness: Duke pulls off 16-point comeback, shocks No. 2 Ohio State to advance to Sweet 16

This is Duke's second-straight comeback after being down at halftime.

March Madness Saturday recap: No. 3 Creighton beats No. 11 Oregon in double overtime to cap the day

Creighton outscored Oregon 15-2 in the second OT.

Kim Mulkey threatens Washington Post with lawsuit during 4-minute tirade over unpublished article

The LSU coach said the article has been in the works for two years.

March Madness: Caitlin Clark, Iowa overcome slow start to advance past Holy Cross

Frustrations were high in Iowa City.

IMAGES

  1. C Operator Precedence

    c assignment precedence

  2. Programming in C

    c assignment precedence

  3. C Programming Tutorial

    c assignment precedence

  4. C# Assignment Operator

    c assignment precedence

  5. Precedence table c

    c assignment precedence

  6. Operators Precedence in C

    c assignment precedence

COMMENTS

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

  2. Operator Precedence and Associativity in C

    where, P = Postfix, U = Unary, M = Multiplicative, A = Additive, S = Shift, R = Relational, E = Equality, B = Bitwise, L = Logical, T = Ternary, A = Assignment and C = Comma. Operator Precedence in C. Operator precedence determines which operation is performed first in an expression with more than one operator with different precedence.

  3. 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: int x = 5 - 17* 6; 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 =.

  4. Precedence and order of evaluation

    The precedence and associativity of C operators affect the grouping and evaluation of operands in expressions. An operator's precedence is meaningful only if other operators with higher or lower precedence are present. Expressions with higher-precedence operators are evaluated first. ... 2 All simple and compound-assignment operators have equal ...

  5. Operators Precedence in C

    Operators Precedence in C. Operator precedence determines the grouping of terms in an expression and decides how an expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has a higher precedence than the addition operator. For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 ...

  6. Operator Precedence and Associativity in C

    Here the / operator has higher precedence hence 4/2 is evaluated first. The + and -operators have the same precedence and associates from left to right, therefore in our expression 12 + 3 - 4 / 2 < 3 + 1 after division, the + operator will be evaluated followed by the -operator. From the precedence table, you can see that precedence of the < operator is lower than that of /, + and -.

  7. Understanding Operator Precedence in C Language

    This not only makes your code easier to understand but also helps avoid any unintended results. For example, the expression a + b * c can be written as a + (b * c) to make it clear that the multiplication should be performed first. Be mindful of Assignment Operator Precedence; In C, the assignment operator (=) has the lowest precedence.

  8. Precedence & Associativity of Operators in C

    How to use the Precedence and Associativity of the operators smartly is one of the important part of C programming. Precedence talks about the priority among the different operators, which to consider first. Like arithmetic operators have higher priority than assignment operators and so on. When we have more than one operator in a single ...

  9. Assignment and Precedence of operators in c

    In the following code : int main() {. int x = 2, y = 1; x *= x + y; printf("%d\n", x); return 0; } How is the operators precedence work ? , as * has a higher precedence than + so I expect that multiplication operation should be done first however the result shows that it is calculated as x * = (x+y) so the addition is done first !

  10. Assignment Operator in C

    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.

  11. C Operator Precedence

    The following table lists the precedence and associativity of C operators. Operators are listed top to bottom, in descending precedence. Precedence Operator Description Associativity ... ↑ Assignment operators' left operands must be unary (level-2 non-cast) expressions. This rule grammatically forbids some expressions that would be ...

  12. Mastering The Art Of Assignment: Exploring C Assignment Operators

    Assignment operators in C are not just for basic value assignment; they enable simultaneous arithmetic operations, enhancing code efficiency and readability. The article emphasizes the importance of understanding operator precedence in C, as misinterpretation can lead to unexpected results, especially with compound assignment operators.

  13. Assignment Operators in C

    This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. Example: (a += b) can be written as (a = a + b) If initially value stored in a is 5. Then (a += 6) = 11. 3. "-=" This operator is combination of '-' and '=' operators.

  14. Operators in C and C++

    C++ also contains the type conversion operators const_cast, static_cast, dynamic_cast, and reinterpret_cast. The formatting of these operators means that their precedence level is unimportant. Most of the operators available in C and C++ are also available in other C-family languages such as C#, D, Java, Perl, and PHP with the same precedence ...

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

  16. C++ Operator Precedence

    Operators that are in the same cell (there may be several rows of operators listed in a cell) are evaluated with the same precedence, in the given direction. 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. Operator precedence is unaffected by operator overloading .

  17. Precedence of assignment within a conditional operator

    144k 15 280 334. "The conditional operator has higher precedence than the assignment operator in C." - actually, no. The precedence of operators in C depends on their context and cannot be correctly described simply by a precedence table. In fact, this code should compile fine. - user529758.

  18. Mets 2024 transaction tracker: Reliever Austin Adams traded to Oakland

    Adams, 32, had previously been designated for assignment by the club. The right-handed reliever originally signed with the Mets in November following stops with Arizona , San Diego , Seattle , and ...

  19. Fy 2024 Non-special Duty Assignment Meritorious Promotions

    r 211800z mar 24 maradmin 148/24 msgid/genadmin/cmc washington dc mra mm// subj/fy 2024 non-special duty assignment meritorious promotions// ref/a/msgid/doc/cmc mmpr-2/20120614//

  20. c++

    Sorted by: 4. All the assignment operators have the same precedence, and they group right-to-left. Semantically, the += operator is a combination of = and +, but syntactically it's an operator by itself, and it's the syntax that determines the precedence. Quoting the C++ standard, the syntax is: assignment-expression: conditional-expression.

  21. Fiscal Year 2025 Active Reserve Special Duty Assignment and Marine

    R 201000Z MAR 24MARADMIN 136/24SUBJ/FISCAL YEAR 2025 (FY25) ACTIVE RESERVE SPECIAL DUTY ASSIGNMENT (SDA) AND MARINE COMBAT INSTRUCTOR (MCI)

  22. C++ assignment precedence

    C++ assignment precedence. To make things more meaningful, basically for the below two cases. I somehow imagined them to be similar, right hand side first. "==" returns the result of the comparison "true" and then converts to 1.