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 - Scope Rules
  • C - Pointers
  • C - Strings
  • C - 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

Assignment Operators in C

In C, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable or an expression. The value to be assigned forms the right hand operand, whereas the variable to be assigned should be the operand to the left of = symbol, which is defined as a simple assignment operator in C. In addition, C has several augmented assignment operators.

The following table lists the assignment operators supported by the C language −

Simple assignment operator (=)

The = operator is the most frequently used operator in C. As per ANSI C standard, all the variables must be declared in the beginning. Variable declaration after the first processing statement is not allowed. You can declare a variable to be assigned a value later in the code, or you can initialize it at the time of declaration.

You can use a literal, another variable or an expression in the assignment statement.

Once a variable of a certain type is declared, it cannot be assigned a value of any other type. In such a case the C compiler reports a type mismatch error.

In C, the expressions that refer to a memory location are called "lvalue" expressions. A lvalue may appear as either the left-hand or right-hand side of an assignment.

On the other hand, the term rvalue refers to a data value that is stored at some address in memory. A rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.

Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −

Augmented assignment operators

In addition to the = operator, C allows you to combine arithmetic and bitwise operators with the = symbol to form augmented or compound assignment operator. The augmented operators offer a convenient shortcut for combining arithmetic or bitwise operation with assignment.

For example, the expression a+=b has the same effect of performing a+b first and then assigning the result back to the variable a.

Similarly, the expression a<<=b has the same effect of performing a<<b first and then assigning the result back to the variable a.

Here is a C program that demonstrates the use of assignment operators in C:

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

Assignment Operators in C

C++ Course: Learn the Essentials

Operators are a fundamental part of all the computations that computers perform. Today we will learn about one of them known as Assignment Operators in C. Assignment Operators are used to assign values to variables. The most common assignment operator is = . Assignment Operators are Binary Operators.

Types of Assignment Operators in C

LHS and RHS Operands

Here is a list of the assignment operators that you can find in the C language:

  • basic assignment ( = )
  • subtraction assignment ( -= )
  • addition assignment ( += )
  • division assignment ( /= )
  • multiplication assignment ( *= )
  • modulo assignment ( %= )
  • bitwise XOR assignment ( ^= )
  • bitwise OR assignment ( |= )
  • bitwise AND assignment ( &= )
  • bitwise right shift assignment ( >>= )
  • bitwise left shift assignment ( <<= )

Working of Assignment Operators in C

This is the complete list of all assignment operators in C. To read the meaning of operator please keep in mind the above example.

Example for Assignment Operators in C

Basic assignment ( = ) :

Subtraction assignment ( -= ) :

Addition assignment ( += ) :

Division assignment ( /= ) :

Multiplication assignment ( *= ) :

Modulo assignment ( %= ) :

Bitwise XOR assignment ( ^= ) :

Bitwise OR assignment ( |= ) :

Bitwise AND assignment ( &= ) :

Bitwise right shift assignment ( >>= ) :

Bitwise left shift assignment ( <<= ) :

This is the detailed explanation of all the assignment operators in C that we have. Hopefully, This is clear to you.

Practice Problems on Assignment Operators in C

1. what will be the value of a after the following code is executed.

A) 10 B) 11 C) 12 D) 15

Answer – C. 12 Explanation: a starts at 10, increases by 5 to 15, then decreases by 3 to 12. So, a is 12.

2. After executing the following code, what is the value of num ?

A) 4 B) 8 C) 16 D) 32

Answer: C) 16 Explanation: After right-shifting 8 (binary 1000) by one and then left-shifting the result by two, the value becomes 16 (binary 10000).

Q. How does the /= operator function? Is it a combination of two other operators?

A. The /= operator is a compound assignment operator in C++. It divides the left operand by the right operand and assigns the result to the left operand. It is equivalent to using the / operator and then the = operator separately.

Q. What is the most basic operator among all the assignment operators available in the C language?

A. The most basic assignment operator in the C language is the simple = operator, which is used for assigning a value to a variable.

  • Assignment operators are used to assign the result of an expression to a variable.
  • There are two types of assignment operators in C. Simple assignment operator and compound assignment operator.
  • Compound Assignment operators are easy to use and the left operand of expression needs not to write again and again.
  • They work the same way in C++ as in C.

Codeforwin

Assignment and shorthand assignment operator in C

Quick links.

  • Shorthand assignment

Assignment operator is used to assign value to a variable (memory location). There is a single assignment operator = in C. It evaluates expression on right side of = symbol and assigns evaluated value to left side the variable.

For example consider the below assignment table.

The RHS of assignment operator must be a constant, expression or variable. Whereas LHS must be a variable (valid memory location).

Shorthand assignment operator

C supports a short variant of assignment operator called compound assignment or shorthand assignment. Shorthand assignment operator combines one of the arithmetic or bitwise operators with assignment operator.

For example, consider following C statements.

The above expression a = a + 2 is equivalent to a += 2 .

Similarly, there are many shorthand assignment operators. Below is a list of shorthand assignment operators in C.

Library homepage

  • school Campus Bookshelves
  • menu_book Bookshelves
  • perm_media Learning Objects
  • login Login
  • how_to_reg Request Instructor Account
  • hub Instructor Commons
  • Download Page (PDF)
  • Download Full Book (PDF)
  • Periodic Table
  • Physics Constants
  • Scientific Calculator
  • Reference & Cite
  • Tools expand_more
  • Readability

selected template will load here

This action is not available.

Engineering LibreTexts

4.6: Assignment Operator

  • Last updated
  • Save as PDF
  • Page ID 29038

  • Patrick McClanahan
  • San Joaquin Delta College

Assignment Operator

The assignment operator allows us to change the value of a modifiable data object (for beginning programmers this typically means a variable). It is associated with the concept of moving a value into the storage location (again usually a variable). Within C++ programming language the symbol used is the equal symbol. But bite your tongue, when you see the = symbol you need to start thinking: assignment. The assignment operator has two operands. The one to the left of the operator is usually an identifier name for a variable. The one to the right of the operator is a value.

The value 21 is moved to the memory location for the variable named: age. Another way to say it: age is assigned the value 21.

The item to the right of the assignment operator is an expression. The expression will be evaluated and the answer is 14. The value 14 would assigned to the variable named: total_cousins.

The expression to the right of the assignment operator contains some identifier names. The program would fetch the values stored in those variables; add them together and get a value of 44; then assign the 44 to the total_students variable.

As we have seen, assignment operators are used to 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:

  • “=” : This is the simplest assignment operator, which was discussed above. This operator is used to assign the value on the right to the variable on the left. For example: a = 10; b = 20; ch = 'y';

If initially the value 5 is stored in the variable a,  then:  (a += 6) is equal to 11.  (the same as: a = a + 6)

If initially value 8 is stored in the variable a, then (a -= 6) is equal to  2. (the same as a = a - 6)

If initially value 5 is stored in the variable a,, then (a *= 6) is equal to 30. (the same as a = a * 6)

If initially value 6 is stored in the variable a, then (a /= 2) is equal to 3. (the same as a = a / 2)

Below example illustrates the various Assignment Operators:

Definitions

 Adapted from:  "Assignment Operator"  by  Kenneth Leroy Busbee , (Download for free at http://cnx.org/contents/[email protected] ) is licensed under  CC BY 4.0

C Functions

C structures, c operators.

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and another variable:

C divides the operators into the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator ( = ) to assign the value 10 to a variable called x :

The addition assignment operator ( += ) adds a value to a variable:

A list of all assignment operators:

Comparison Operators

Comparison operators are used to compare two values (or variables). This is important in programming, because it helps us to find answers and make decisions.

The return value of a comparison is either 1 or 0 , which means true ( 1 ) or false ( 0 ). These values are known as Boolean values , and you will learn more about them in the Booleans and If..Else chapter.

Comparison operators are used to compare two values.

Note: The return value of a comparison is either true ( 1 ) or false ( 0 ).

In the following example, we use the greater than operator ( > ) to find out if 5 is greater than 3:

A list of all comparison operators:

Logical Operators

You can also test for true or false values with logical operators.

Logical operators are used to determine the logic between variables or values:

C Exercises

Test yourself with exercises.

Fill in the blanks to multiply 10 with 5 , and print the result:

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

Javatpoint Logo

  • Design Pattern
  • Interview Q

C Control Statements

C functions, c dynamic memory, c structure union, c file handling, c preprocessor, c command line, c programming test, c interview.

JavaTpoint

  • 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

Programtopia

C Programming Operators and Expressions

In this Section, you will learn about Operators in C Programming (all valid operators available in C), expressions (combination of operators, variables and constants) and precedence of operators (which operator has higher priority and which operator has lower priority).

C Operators

  • Expressions in C
  • C Operator Precedence

Operators are the symbols which tell the computer to execute certain mathematical or logical operations. A mathematical or logical expression is generally formed with the help of an operator. C programming offers a number of operators which are classified into 8 categories viz.

  • Arithmetic operators
  • Relational operators
  • Logical operators
  • Assignment operators
  • Increment and Decrement operators
  • Conditional operators
  • Bitwise operators
  • Special operators

1. Arithmetic Operators

C programming language provides all basic arithmetic operators: +, -, *, / and %.

Arithmetic Operators in C

Note: ‘/’ is integer division which only gives integer part as result after division. ‘%’ is modulo division which gives the remainder of integer division as result.

Some examples of arithmetic operators are:

In these examples, a and b are variables and are called operands.

Note: ‘%’ cannot be used on floating data type.

2. Relational Operators

Relational operators are used when we have to make comparisons. C programming offers 6 relational operators.

Relational Operators in C

Relational expression is an expression which contains the relational operator. Relational operators are most commonly used in decision statements like if , while , etc. Some simple relational expressions are:

Note: Arithmetic operators have higher priority than relational operators meaning that if arithmetic expressions are present on two sides of a relational operator then arithmetic expressions will be calculated first and then the result will be compared.

3. Logical Operators

Logical operators are used when more than one conditions are to be tested and based on that result, decisions have to be made. C programming offers three logical operators. They are:

Logical Operators in C

For example:

An expression which combines two or more relational expressions is known as logical expression.

Note: Relative precedence of relational and logical operators are as follows

4. Assignment Operators

Assignment operators are used to assign result of an expression to a variable. ‘=’ is the assignment operator in C. Furthermore, C also allows the use of shorthand assignment operators. Shorthand operators take the form:

where var is a variable, op is arithmetic operator, exp is an expression. In this case, ‘op=’ is known as shorthand assignment operator.

The above assignment

is the same as the assignment

Consider an example:

Here, the above statement means the same as

Note: Shorthand assignment can be used with all arithmetic operators.

5. Increment and Decrement Operators

C programming allows the use of ++ and – operators which are increment and decrement operators respectively. Both the increment and decrement operators are unary operators. The increment operator ++ adds 1 to the operand and the decrement operator – subtracts 1 from the operand. The general syntax of these operators are:

Increment Operator: m++ or ++m ;

Decrement Operator: m–or –m ;

In the example above, m++ simply means m=m+1; and m– simply means m=m-1;

Increment and decrement operators are mostly used in for and while loops.

++m and m++ performs the same operation when they form statements independently but they function differently when they are used in right hand side of an expression.

++m is known as prefix operator and m++ is known as postfix operator. A prefix operator firstly adds 1 to the operand and then the result is assigned to the variable on the left whereas a postfix operator firstly assigns value to the variable on the left and then increases the operand by 1. Same is in the case of decrement operator.

For example,

X=10; Y=++X;

In this case, the value of X and Y will be 6.

In this case, the value of Y will be 10 and the value of X will be 11.

6. Conditional Operator

The operator pair “?” and “:” is known as conditional operator. These pair of operators are ternary operators. The general syntax of conditional operator is:

This syntax can be understood as a substitute of if else statement.

Consider an if else statement as:

Now, this if else statement can be written by using conditional operator as:

7. Bitwise Operator

In C programming, bitwise operators are used for testing the bits or shifting them left or right. The bitwise operators available in C are:

Bitwise Operators in C

8. Special Operators

C programming supports special operators like comma operator, sizeof operator, pointer operators (& and *) and member selection operators (. and ->). The comma operator and sizeof operator are discussed in this section whereas the pointer and member selection operators are discussed in later sections.

1. Comma Operator

The comma operator can be used to link the related expressions together. A comma linked expression is evaluated from left to right and the value of the right most expression is the value of the combined expression.

In this example, the expression is evaluated from left to right. So at first, variable a is assigned value 2, then variable b is assigned value 4 and then value 6 is assigned to the variable x. Comma operators are commonly used in for loops, while loops, while exchanging values, etc.

2 .Sizeof() operator

The sizeof operator is usually used with an operand which may be variable, constant or a data type qualifier. This operator returns the number of bytes the operand occupies. Sizeof operator is a compile time operator. Some examples of use of sizeof operator are:

The sizeof operator is usually used to determine the length of arrays and structures when their sizes are not known. It is also used in dynamic memory allocation.

9. C Expressions

Arithmetic expression in C is a combination of variables, constants and operators written in a proper syntax. C can easily handle any complex mathematical expressions but these mathematical expressions have to be written in a proper syntax. Some examples of mathematical expressions written in proper syntax of C are:

Note: C does not have any operator for exponentiation.

10. C Operator Precedence

At first, the expressions within parenthesis are evaluated. If no parenthesis is present, then the arithmetic expression is evaluated from left to right. There are two priority levels of operators in C.

High priority: * / % Low priority: + –

The evaluation procedure of an arithmetic expression includes two left to right passes through the entire expression. In the first pass, the high priority operators are applied as they are encountered and in the second pass, low priority operations are applied as they are encountered.

Suppose, we have an arithmetic expression as:

This expression is evaluated in two left to right passes as:

But when parenthesis is used in the same expression, the order of evaluation gets changed.

When parentheses are present then the expression inside the parenthesis are evaluated first from left to right. The expression is now evaluated in three passes as:

Second Pass

There may even arise a case where nested parentheses are present (i.e. parenthesis inside parenthesis). In such case, the expression inside the innermost set of parentheses is evaluated first and then the outer parentheses are evaluated.

For example, we have an expression as:

The expression is now evaluated as:

First Pass:

Note: The number of evaluation steps is equal to the number of operators in the arithmetic expression.

cppreference.com

Copy assignment operator.

A copy assignment operator is a non-template non-static member function with the name operator = that can be called with an argument of the same class type and copies the content of the argument without mutating the argument.

[ edit ] Syntax

For the formal copy assignment operator syntax, see function declaration . The syntax list below only demonstrates a subset of all valid copy assignment operator syntaxes.

[ edit ] Explanation

The copy assignment operator is called whenever selected by overload resolution , e.g. when an object appears on the left side of an assignment expression.

[ edit ] Implicitly-declared copy assignment operator

If no user-defined copy assignment operators are provided for a class type, the compiler will always declare one as an inline public member of the class. This implicitly-declared copy assignment operator has the form T & T :: operator = ( const T & ) if all of the following is true:

  • each direct base B of T has a copy assignment operator whose parameters are B or const B & or const volatile B & ;
  • each non-static data member M of T of class type or array of class type has a copy assignment operator whose parameters are M or const M & or const volatile M & .

Otherwise the implicitly-declared copy assignment operator is declared as T & T :: operator = ( T & ) .

Due to these rules, the implicitly-declared copy assignment operator cannot bind to a volatile lvalue argument.

A class can have multiple copy assignment operators, e.g. both T & T :: operator = ( T & ) and T & T :: operator = ( T ) . If some user-defined copy assignment operators are present, the user may still force the generation of the implicitly declared copy assignment operator with the keyword default . (since C++11)

The implicitly-declared (or defaulted on its first declaration) copy assignment operator has an exception specification as described in dynamic exception specification (until C++17) noexcept specification (since C++17)

Because the copy assignment operator is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.

[ edit ] Implicitly-defined copy assignment operator

If the implicitly-declared copy assignment operator is neither deleted nor trivial, it is defined (that is, a function body is generated and compiled) by the compiler if odr-used or needed for constant evaluation (since C++14) . For union types, the implicitly-defined copy assignment copies the object representation (as by std::memmove ). For non-union class types, the operator performs member-wise copy assignment of the object's direct bases and non-static data members, in their initialization order, using built-in assignment for the scalars, memberwise copy-assignment for arrays, and copy assignment operator for class types (called non-virtually).

[ edit ] Deleted copy assignment operator

An implicitly-declared or explicitly-defaulted (since C++11) copy assignment operator for class T is undefined (until C++11) defined as deleted (since C++11) if any of the following conditions is satisfied:

  • T has a non-static data member of a const-qualified non-class type (or possibly multi-dimensional array thereof).
  • T has a non-static data member of a reference type.
  • T has a potentially constructed subobject of class type M (or possibly multi-dimensional array thereof) such that the overload resolution as applied to find M 's copy assignment operator
  • does not result in a usable candidate, or
  • in the case of the subobject being a variant member , selects a non-trivial function.

[ edit ] Trivial copy assignment operator

The copy assignment operator for class T is trivial if all of the following is true:

  • it is not user-provided (meaning, it is implicitly-defined or defaulted);
  • T has no virtual member functions;
  • T has no virtual base classes;
  • the copy assignment operator selected for every direct base of T is trivial;
  • the copy assignment operator selected for every non-static class type (or array of class type) member of T is trivial.

A trivial copy assignment operator makes a copy of the object representation as if by std::memmove . All data types compatible with the C language (POD types) are trivially copy-assignable.

[ edit ] Eligible copy assignment operator

Triviality of eligible copy assignment operators determines whether the class is a trivially copyable type .

[ edit ] Notes

If both copy and move assignment operators are provided, overload resolution selects the move assignment if the argument is an rvalue (either a prvalue such as a nameless temporary or an xvalue such as the result of std::move ), and selects the copy assignment if the argument is an lvalue (named object or a function/operator returning lvalue reference). If only the copy assignment is provided, all argument categories select it (as long as it takes its argument by value or as reference to const, since rvalues can bind to const references), which makes copy assignment the fallback for move assignment, when move is unavailable.

It is unspecified whether virtual base class subobjects that are accessible through more than one path in the inheritance lattice, are assigned more than once by the implicitly-defined copy assignment operator (same applies to move assignment ).

See assignment operator overloading for additional detail on the expected behavior of a user-defined copy-assignment operator.

[ edit ] Example

[ edit ] defect reports.

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

[ edit ] See also

  • converting constructor
  • copy constructor
  • copy elision
  • default constructor
  • aggregate initialization
  • constant initialization
  • copy initialization
  • default initialization
  • direct initialization
  • initializer list
  • list initialization
  • reference initialization
  • value initialization
  • zero initialization
  • move assignment
  • move constructor
  • 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 2 February 2024, at 15:13.
  • This page has been accessed 1,333,785 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

This browser is no longer supported.

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

Move Constructors and Move Assignment Operators (C++)

  • 9 contributors

This topic describes how to write a move constructor and a move assignment operator for a C++ class. A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying. For more information about move semantics, see Rvalue Reference Declarator: && .

This topic builds upon the following C++ class, MemoryBlock , which manages a memory buffer.

The following procedures describe how to write a move constructor and a move assignment operator for the example C++ class.

To create a move constructor for a C++ class

Define an empty constructor method that takes an rvalue reference to the class type as its parameter, as demonstrated in the following example:

In the move constructor, assign the class data members from the source object to the object that is being constructed:

Assign the data members of the source object to default values. This prevents the destructor from freeing resources (such as memory) multiple times:

To create a move assignment operator for a C++ class

Define an empty assignment operator that takes an rvalue reference to the class type as its parameter and returns a reference to the class type, as demonstrated in the following example:

In the move assignment operator, add a conditional statement that performs no operation if you try to assign the object to itself.

In the conditional statement, free any resources (such as memory) from the object that is being assigned to.

The following example frees the _data member from the object that is being assigned to:

Follow steps 2 and 3 in the first procedure to transfer the data members from the source object to the object that is being constructed:

Return a reference to the current object, as shown in the following example:

Example: Complete move constructor and assignment operator

The following example shows the complete move constructor and move assignment operator for the MemoryBlock class:

Example Use move semantics to improve performance

The following example shows how move semantics can improve the performance of your applications. The example adds two elements to a vector object and then inserts a new element between the two existing elements. The vector class uses move semantics to perform the insertion operation efficiently by moving the elements of the vector instead of copying them.

This example produces the following output:

Before Visual Studio 2010, this example produced the following output:

The version of this example that uses move semantics is more efficient than the version that does not use move semantics because it performs fewer copy, memory allocation, and memory deallocation operations.

Robust Programming

To prevent resource leaks, always free resources (such as memory, file handles, and sockets) in the move assignment operator.

To prevent the unrecoverable destruction of resources, properly handle self-assignment in the move assignment operator.

If you provide both a move constructor and a move assignment operator for your class, you can eliminate redundant code by writing the move constructor to call the move assignment operator. The following example shows a revised version of the move constructor that calls the move assignment operator:

The std::move function converts the lvalue other to an rvalue.

Rvalue Reference Declarator: && std::move

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

  • Trending Now
  • Data Structures & Algorithms
  • Foundational Courses
  • Data Science
  • Practice Problem
  • Machine Learning
  • System Design
  • DevOps Tutorial
  • Web Development
  • Web Browser

Related Articles

  • 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

C Data Types

  • 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

C Operators

  • 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
  • C Functions
  • 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 Preprocessors
  • 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?

C File Handling

  • 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 Interview Questions

  • 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

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 expression and helps us in avoiding unnecessary use of parenthesis.

In this article, we will discuss operator precedence, operator associativity, and precedence table according to which the priority of the operators in expression is decided in C language.

Operator Precedence and Associativity Table

The following tables list the C operator precedence from highest to lowest and the associativity for each of the operators:

Operator Precedence in C

Operator precedence determines which operation is performed first in an expression with more than one operator with different precedence.

Example of Operator Precedence

Let’s try to evaluate the following expression,

The expression contains two operators, + (plus) , and * (multiply). According to the given table, the * has higher precedence than + so, the first evaluation will be

After evaluating the higher precedence operator, the expression is

Now, the + operator will be evaluated.

operator precedence

We can verify this using the following C program

As we can see, the expression is evaluated as, 10 + (20 * 30) but not as (10 + 20) * 30 due to * operator having higher precedence.

Operator Associativity

Operator associativity is used when two operators of the same precedence appear in an expression. Associativity can be either from Left to Right or Right to Left. 

Example of Operator Associativity

Let’s evaluate the following expression,

Both / (division) and % (Modulus) operators have the same precedence, so the order of evaluation will be decided by associativity.

According to the given table, the associativity of the multiplicative operators is from Left to Right. So,

After evaluation, the expression will be

Now, the % operator will be evaluated.

operator associativity

We can verify the above using the following C program:

Operators Precedence and Associativity are two characteristics of operators that determine the evaluation order of sub-expressions.

Example of Operator Precedence and Associativity

In general, the concept of precedence and associativity is applied together in expressions. So let’s consider an expression where we have operators with various precedence and associativity

Here, we have four operators, in which the / and * operators have the same precedence but have higher precedence than the + and – operators. So, according to the Left-to-Right associativity of / and * , / will be evaluated first.

After that, * will be evaluated,

Now, between + and – , + will be evaluated due to Left-to-Right associativity.

At last, – will be evaluated.

operator precedence and associativity

Again, we can verify this using the following C program.

100 + 200 / 10 – 3 * 10 = 90

Important Points

There are a few important points and cases that we need to remember for operator associativity and precedence which are as follows:

1. Associativity is only used when there are two or more operators of the same precedence.

The point to note is associativity doesn’t define the order in which operands of a single operator are evaluated. For example, consider the following program, associativity of the + operator is left to right, but it doesn’t mean f1() is always called before f2(). The output of the following program is in-fact compiler-dependent.

See this for details.

2. We can use parenthesis to change the order of evaluation

Parenthesis ( ) got the highest priority among all the C operators. So, if we want to change the order of evaluation in an expression, we can enclose that particular operator in ( ) parenthesis along with its operands.

Consider the given expression

But if we enclose 100 + 200 in parenthesis, then the result will be different.

As the + operator will be evaluated before / operator.

2. All operators with the same precedence have the same associativity.

This is necessary, otherwise, there won’t be any way for the compiler to decide the evaluation order of expressions that have two operators of the same precedence and different associativity. For example + and – have the same associativity.

3. Precedence and associativity of postfix ++ and prefix ++ are different.

The precedence of postfix ++ is more than prefix ++, their associativity is also different. The associativity of postfix ++ is left to right and the associativity of prefix ++ is right to left. See this for examples.

4. Comma has the least precedence among all operators and should be used carefully.

For example, consider the following program, the output is 1.

See this and this for more details.

5. There is no chaining of comparison operators in C

In Python, an expression like “c > b > a” is treated as “c > b and b > a”, but this type of chaining doesn’t happen in C. For example, consider the following program. The output of the following program is “FALSE”.

It is necessary to know the precedence and associativity for the efficient usage of operators. It allows us to write clean expressions by avoiding the use of unnecessary parenthesis. Also, it is the same for all the C compilers so it also allows us to understand the expressions in the code written by other programmers.

Also, when confused about or want to change the order of evaluation, we can always rely on parenthesis ( ) . The advantage of brackets is that the reader doesn’t have to see the table to find out the order.

Please Login to comment...

  • C-Operators
  • cpp-operator
  • sirraghavgupta
  • vishal07das
  • spsomarcayam
  • govarthenan
  • abhishekcpp
  • singhsnigdha2712
  • 10 Best ChatGPT Prompts for Lawyers 2024
  • What is Meta’s new V-JEPA model? [Explained]
  • What is Chaiverse & How it Works?
  • Top 10 Mailchimp Alternatives (Free) - 2024
  • Dev Scripter 2024 - Biggest Technical Writing Event By GeeksforGeeks

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Assignment Operators in C

    define assignment operators in c

  2. Operators in C

    define assignment operators in c

  3. PPT

    define assignment operators in c

  4. Assignment Operators in C Detailed Explanation

    define assignment operators in c

  5. Assignment operators in C++ programming

    define assignment operators in c

  6. Assignment Operators in C++

    define assignment operators in c

VIDEO

  1. Lecture 15||Relational Operators||C programming Tutorials||Complete Playlist||Placements||

  2. Augmented assignment operators in C

  3. Operators in C language

  4. Working with Assignment operators in C| C Tutorials for Beginners

  5. Assignment Operator in C Programming

  6. PART_11 Logical Operators in C ||Programming in C #viral #clanguage #shortvideos @languagefacts

COMMENTS

  1. Assignment Operators in C

    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.

  2. Assignment Operators in C

    Assignment Operators in C The following table lists the assignment operators supported by the C language − Example Try the following example to understand all the assignment operators available in C − Live Demo

  3. C Assignment Operators

    Syntax See also An assignment operation assigns the value of the right-hand operand to the storage location named by the left-hand operand. Therefore, the left-hand operand of an assignment operation must be a modifiable l-value. After the assignment, an assignment expression has the value of the left operand but isn't an l-value. Syntax

  4. Operators in C

    Assignment Operators Other Operators 1. Arithmetic Operations in C The arithmetic operators are used to perform arithmetic/mathematical operations on operands. There are 9 arithmetic operators in C language: Example of C Arithmetic Operators C #include <stdio.h> int main () { int a = 25, b = 5; printf("a + b = %d\n", a + b);

  5. Assignment operators

    Assignment operators modify the value of the object. Syntax Over load able Prototype examples (for replaces the contents of the object is not modified). For class types, this is performed in a special member function, described in For non-class types, copy and move assignment are indistinguishable and are referred to as

  6. Assignment operators

    Assignment and compound assignment operators are binary operators that modify the variable to their left using the value to their right. becomes equal to becomes equal to the addition of becomes equal to the subtraction of becomes equal to the product of becomes equal to the division of becomes equal to the remainder of

  7. Operators in C

    An assignment operator is used for assigning a value to a variable. The most common assignment operator is = Example 3: Assignment Operators

  8. Assignment Operators in C Example

    The Assignment operators in C are some of the Programming operators that are useful for assigning the values to the declared variables. Equals (=) operator is the most commonly used assignment operator. For example: int i = 10; The below table displays all the assignment operators present in C Programming with an example.

  9. Assignment Operators in C

    A. The most basic assignment operator in the C language is the simple = operator, which is used for assigning a value to a variable. Conclusion. Assignment operators are used to assign the result of an expression to a variable. There are two types of assignment operators in C. Simple assignment operator and compound assignment operator.

  10. Assignment and shorthand assignment operator in C

    Shorthand assignment operator. C supports a short variant of assignment operator called compound assignment or shorthand assignment. Shorthand assignment operator combines one of the arithmetic or bitwise operators with assignment operator. For example, consider following C statements. The above expression a = a + 2 is equivalent to a += 2.

  11. 4.6: Assignment Operator

    Assignment Operator. The assignment operator allows us to change the value of a modifiable data object (for beginning programmers this typically means a variable). It is associated with the concept of moving a value into the storage location (again usually a variable). Within C++ programming language the symbol used is the equal symbol.

  12. C Operators

    Assignment operators are used to assign values to variables. In the example below, we use the assignment operator ( =) to assign the value 10 to a variable called x: Example int x = 10; Try it Yourself » The addition assignment operator ( +=) adds a value to a variable: Example int x = 10; x += 5; Try it Yourself »

  13. Assignment (computer science)

    Assignment (computer science) For assignment of letters to disk file systems, see Drive letter assignment. In computer programming, an assignment statement sets and/or re-sets the value stored in the storage location (s) denoted by a variable name; in other words, it copies a value into the variable. In most imperative programming languages ...

  14. Assignment Operator in C

    Assignment Operator in C. There are different kinds of the operators, such as arithmetic, relational, bitwise, assignment, etc., in the C programming language. The assignment operator is used to assign the value, variable and function to another variable. Let's discuss the various types of the assignment operators such as =, +=, -=, /=, *= and %=.

  15. C Programming Operators and Expressions

    Assignment Operators. Assignment operators are used to assign result of an expression to a variable. '=' is the assignment operator in C. Furthermore, C also allows the use of shorthand assignment operators. Shorthand operators take the form: var op = exp; where var is a variable, op is arithmetic operator, exp is an expression. In this ...

  16. What is the difference between += and =+ C assignment operators

    In modern C, or even moderately ancient C, += is a compound assignment operator, and =+ is parsed as two separate tokens. = and +. Punctuation tokens are allowed to be adjacent. except that x is only evaluated once (which can matter if it's a more complicated expression). and the + is a unary plus operator.

  17. Copy assignment operator

    A copy assignment operator is a non-template non-static member function with the name that can be called with an argument of the same class type and copies the content of the argument without mutating the argument. Implicitly-declared copy assignment operator. Implicitly-defined copy assignment operator. Deleted copy assignment operator.

  18. Assignment Operators In C++

    There are 10 compound assignment operators in C++: Addition Assignment Operator ( += ) Subtraction Assignment Operator ( -= ) Multiplication Assignment Operator ( *= ) Division Assignment Operator ( /= ) Modulus Assignment Operator ( %= ) Bitwise AND Assignment Operator ( &= ) Bitwise OR Assignment Operator ( |= )

  19. How to: Define move constructors and move assignment operators (C++

    This topic describes how to write a move constructor and a move assignment operator for a C++ class. A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying. For more information about move semantics, see Rvalue Reference Declarator: &&. This topic builds upon the following C++ class ...

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

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