Learn C practically and Get Certified .

Popular Tutorials

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

  • Getting Started with C
  • Your First C Program

C Fundamentals

  • C Variables, Constants and Literals
  • C Data Types
  • C Input Output (I/O)
  • C Programming Operators

C Flow Control

  • C if...else Statement
  • C while and do...while Loop
  • C break and continue
  • C switch Statement
  • C goto Statement
  • C Functions
  • C User-defined functions
  • Types of User-defined Functions in C Programming
  • C Recursion
  • C Storage Class

C Programming Arrays

  • C Multidimensional Arrays
  • Pass arrays to a function in C

C Programming Pointers

Relationship Between Arrays and Pointers

C Pass Addresses and Pointers

C Dynamic Memory Allocation

  • C Array and Pointer Examples
  • C Programming Strings
  • String Manipulations In C Programming Using Library Functions
  • String Examples in C Programming

C Structure and Union

C structs and Pointers

  • C Structure and Function

C Programming Files

  • C File Handling
  • C Files Examples

C Additional Topics

  • C Keywords and Identifiers
  • C Precedence And Associativity Of Operators
  • C Bitwise Operators
  • C Preprocessor and Macros
  • C Standard Library Functions

C Tutorials

  • Access Array Elements Using Pointer

Pointers are powerful features of C and C++ programming. Before we learn pointers, let's learn about addresses in C programming.

  • Address in C

If you have a variable var in your program, &var will give you its address in the memory.

We have used address numerous times while using the scanf() function.

Here, the value entered by the user is stored in the address of var variable. Let's take a working example.

Note: You will probably get a different address when you run the above code.

Pointers (pointer variables) are special variables that are used to store addresses rather than values.

Pointer Syntax

Here is how we can declare pointers.

Here, we have declared a pointer p of int type.

You can also declare pointers in these ways.

Let's take another example of declaring pointers.

Here, we have declared a pointer p1 and a normal variable p2 .

  • Assigning addresses to Pointers

Let's take an example.

Here, 5 is assigned to the c variable. And, the address of c is assigned to the pc pointer.

Get Value of Thing Pointed by Pointers

To get the value of the thing pointed by the pointers, we use the * operator. For example:

Here, the address of c is assigned to the pc pointer. To get the value stored in that address, we used *pc .

Note: In the above example, pc is a pointer, not *pc . You cannot and should not do something like *pc = &c ;

By the way, * is called the dereference operator (when working with pointers). It operates on a pointer and gives the value stored in that pointer.

  • Changing Value Pointed by Pointers

We have assigned the address of c to the pc pointer.

Then, we changed the value of c to 1. Since pc and the address of c is the same, *pc gives us 1.

Let's take another example.

Then, we changed *pc to 1 using *pc = 1; . Since pc and the address of c is the same, c will be equal to 1.

Let's take one more example.

Initially, the address of c is assigned to the pc pointer using pc = &c; . Since c is 5, *pc gives us 5.

Then, the address of d is assigned to the pc pointer using pc = &d; . Since d is -15, *pc gives us -15.

  • Example: Working of Pointers

Let's take a working example.

Explanation of the program

A pointer variable and a normal variable is created.

Common mistakes when working with pointers

Suppose, you want pointer pc to point to the address of c . Then,

Here's an example of pointer syntax beginners often find confusing.

Why didn't we get an error when using int *p = &c; ?

It's because

is equivalent to

In both cases, we are creating a pointer p (not *p ) and assigning &c to it.

To avoid this confusion, we can use the statement like this:

Now you know what pointers are, you will learn how pointers are related to arrays in the next tutorial.

Table of Contents

  • What is a pointer?
  • Common Mistakes

Sorry about that.

Related Tutorials

CHAPTER 1: What is a pointer?

cppreference.com

Assignment operators.

(C++20)
(C++20)
(C++11)
(C++20)
(C++17)
(C++11)
(C++11)
General topics
(C++11)
-
-expression
block


/
(C++11)
(C++11)
(C++11)
(C++20)
(C++20)
(C++11)

expression
pointer
specifier

specifier (C++11)
specifier (C++11)
(C++11)

(C++11)
(C++11)
(C++11)
General
(C++11)
(C++26)

(C++11)
(C++11)
-expression
-expression
-expression
(C++11)
(C++11)
(C++17)
(C++20)
    

Assignment operators modify the value of the object.

Operator name  Syntax  Prototype examples (for class T)
Inside class definition Outside class definition
simple assignment Yes T& T::operator =(const T2& b);
addition assignment Yes T& T::operator +=(const T2& b); T& operator +=(T& a, const T2& b);
subtraction assignment Yes T& T::operator -=(const T2& b); T& operator -=(T& a, const T2& b);
multiplication assignment Yes T& T::operator *=(const T2& b); T& operator *=(T& a, const T2& b);
division assignment Yes T& T::operator /=(const T2& b); T& operator /=(T& a, const T2& b);
remainder assignment Yes T& T::operator %=(const T2& b); T& operator %=(T& a, const T2& b);
bitwise AND assignment Yes T& T::operator &=(const T2& b); T& operator &=(T& a, const T2& b);
bitwise OR assignment Yes T& T::operator |=(const T2& b); T& operator |=(T& a, const T2& b);
bitwise XOR assignment Yes T& T::operator ^=(const T2& b); T& operator ^=(T& a, const T2& b);
bitwise left shift assignment Yes T& T::operator <<=(const T2& b); T& operator <<=(T& a, const T2& b);
bitwise right shift assignment Yes T& T::operator >>=(const T2& b); T& operator >>=(T& a, const T2& b);

this, and most also return *this so that the user-defined operators can be used in the same manner as the built-ins. However, in a user-defined operator overload, any type can be used as return type (including void). can be any type including .
Definitions Assignment operator syntax Built-in simple assignment operator Assignment from an expression Assignment from a non-expression initializer clause Built-in compound assignment operator Example Defect reports See also

[ edit ] Definitions

Copy assignment replaces the contents of the object a with a copy of the contents of b ( b is not modified). For class types, this is performed in a special member function, described in copy assignment operator .

replaces the contents of the object a with the contents of b, avoiding copying if possible (b may be modified). For class types, this is performed in a special member function, described in .

(since C++11)

For non-class types, copy and move assignment are indistinguishable and are referred to as direct assignment .

Compound assignment replace the contents of the object a with the result of a binary operation between the previous value of a and the value of b .

[ edit ] Assignment operator syntax

The assignment expressions have the form

target-expr new-value (1)
target-expr op new-value (2)
target-expr - the expression to be assigned to
op - one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |=
new-value - the expression (until C++11) (since C++11) to assign to the target
  • ↑ target-expr must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

If new-value is not an expression, the assignment expression will never match an overloaded compound assignment operator.

(since C++11)

[ edit ] Built-in simple assignment operator

For the built-in simple assignment, the object referred to by target-expr is modified by replacing its value with the result of new-value . target-expr must be a modifiable lvalue.

The result of a built-in simple assignment is an lvalue of the type of target-expr , referring to target-expr . If target-expr is a bit-field , the result is also a bit-field.

[ edit ] Assignment from an expression

If new-value is an expression, it is implicitly converted to the cv-unqualified type of target-expr . When target-expr is a bit-field that cannot represent the value of the expression, the resulting value of the bit-field is implementation-defined.

If target-expr and new-value identify overlapping objects, the behavior is undefined (unless the overlap is exact and the type is the same).

If the type of target-expr is volatile-qualified, the assignment is deprecated, unless the (possibly parenthesized) assignment expression is a or an .

(since C++20)

new-value is only allowed not to be an expression in following situations:

is of a , and new-value is empty or has only one element. In this case, given an invented variable t declared and initialized as T t = new-value , the meaning of x = new-value  is x = t. is of class type. In this case, new-value is passed as the argument to the assignment operator function selected by .   <double> z; z = {1, 2}; // meaning z.operator=({1, 2}) z += {1, 2}; // meaning z.operator+=({1, 2})   int a, b; a = b = {1}; // meaning a = b = 1; a = {1} = b; // syntax error
(since C++11)

In overload resolution against user-defined operators , for every type T , the following function signatures participate in overload resolution:

& operator=(T*&, T*);
volatile & operator=(T*volatile &, T*);

For every enumeration or pointer to member type T , optionally volatile-qualified, the following function signature participates in overload resolution:

operator=(T&, T);

For every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signature participates in overload resolution:

operator=(A1&, A2);

[ edit ] Built-in compound assignment operator

The behavior of every built-in compound-assignment expression target-expr   op   =   new-value is exactly the same as the behavior of the expression target-expr   =   target-expr   op   new-value , except that target-expr is evaluated only once.

The requirements on target-expr and new-value of built-in simple assignment operators also apply. Furthermore:

  • For + = and - = , the type of target-expr must be an arithmetic type or a pointer to a (possibly cv-qualified) completely-defined object type .
  • For all other compound assignment operators, the type of target-expr must be an arithmetic type.

In overload resolution against user-defined operators , for every pair A1 and A2 , where A1 is an arithmetic type (optionally volatile-qualified) and A2 is a promoted arithmetic type, the following function signatures participate in overload resolution:

operator*=(A1&, A2);
operator/=(A1&, A2);
operator+=(A1&, A2);
operator-=(A1&, A2);

For every pair I1 and I2 , where I1 is an integral type (optionally volatile-qualified) and I2 is a promoted integral type, the following function signatures participate in overload resolution:

operator%=(I1&, I2);
operator<<=(I1&, I2);
operator>>=(I1&, I2);
operator&=(I1&, I2);
operator^=(I1&, I2);
operator|=(I1&, I2);

For every optionally cv-qualified object type T , the following function signatures participate in overload resolution:

& operator+=(T*&, );
& operator-=(T*&, );
volatile & operator+=(T*volatile &, );
volatile & operator-=(T*volatile &, );

[ edit ] Example

Possible output:

[ edit ] Defect reports

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

DR Applied to Behavior as published Correct behavior
C++11 for assignments to class type objects, the right operand
could be an initializer list only when the assignment
is defined by a user-defined assignment operator
removed user-defined
assignment constraint
C++11 E1 = {E2} was equivalent to E1 = T(E2)
( is the type of ), this introduced a C-style cast
it is equivalent
to E1 = T{E2}
C++20 compound assignment operators for volatile
-qualified types were inconsistently deprecated
none of them
is deprecated
C++11 an assignment from a non-expression initializer clause
to a scalar value would perform direct-list-initialization
performs copy-list-
initialization instead
C++20 bitwise compound assignment operators for volatile types
were deprecated while being useful for some platforms
they are not
deprecated

[ edit ] See also

Operator precedence

Operator overloading

Common operators

a = b
a += b
a -= b
a *= b
a /= b
a %= b
a &= b
a |= b
a ^= b
a <<= b
a >>= b

++a
--a
a++
a--

+a
-a
a + b
a - b
a * b
a / b
a % b
~a
a & b
a | b
a ^ b
a << b
a >> b

!a
a && b
a || b

a == b
a != b
a < b
a > b
a <= b
a >= b
a <=> b

a[...]
*a
&a
a->b
a.b
a->*b
a.*b

function call
a(...)
comma
a, b
conditional
a ? b : c
Special operators

converts one type to another related type
converts within inheritance hierarchies
adds or removes -qualifiers
converts type to unrelated type
converts one type to another by a mix of , , and
creates objects with dynamic storage duration
destructs objects previously created by the new expression and releases obtained memory area
queries the size of a type
queries the size of a (since C++11)
queries the type information of a type
checks if an expression can throw an exception (since C++11)
queries alignment requirements of a type (since C++11)

for Assignment operators
  • 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 25 January 2024, at 23:41.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Home » Learn C Programming from Scratch » C Assignment Operators

C Assignment Operators

Summary : in this tutorial, you’ll learn about the C assignment operators and how to use them effectively.

Introduction to the C assignment operators

An assignment operator assigns the vale of the right-hand operand to the left-hand operand. The following example uses the assignment operator (=) to assign 1 to the counter variable:

After the assignmment, the counter variable holds the number 1.

The following example adds 1 to the counter and assign the result to the counter:

The = assignment operator is called a simple assignment operator. It assigns the value of the left operand to the right operand.

Besides the simple assignment operator, C supports compound assignment operators. A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.

The following example uses a compound-assignment operator (+=):

The expression:

is equivalent to the following expression:

The following table illustrates the compound-assignment operators in C:

OperatorOperation PerformedExampleEquivalent expression
Multiplication assignmentx *= yx = x * y
Division assignmentx /= yx = x / y
Remainder assignmentx %= yx = x % y
Addition assignmentx += yx = x + y
Subtraction assignmentx -= yx = x – y
Left-shift assignmentx <<= yx = x <<=y
Right-shift assignmentx >>=yx = x >>= y
Bitwise-AND assignmentx &= yx = x & y
Bitwise-exclusive-OR assignmentx ^= yx = x ^ y
Bitwise-inclusive-OR assignmentx |= yx = x | y
  • A simple assignment operator assigns the value of the left operand to the right operand.
  • A compound assignment operator performs the operation specified by the additional operator and then assigns the result to the left operand.

Assignment Operators in C

C Assignment OperatorsExampleExplanation
=x = 25Value 25 is assigned to x
+=x += 25This is the same as x = x + 25
-=x -= 25This is the same as x = x – 25
*=y *= 25This is the same as y = y * 25
/=y /= 25This is the same as y = y / 25
%=y%= 25This is the same as y = y % 25

Assignment Operators in C Example

Learn to Code, Prepare for Interviews, and Get Hired

01 Career Opportunities

  • Top 50 Mostly Asked C Interview Questions and Answers

02 Beginner

  • If Statement in C
  • Understanding do...while loop in C
  • Understanding for loop in C
  • if else if statements in C Programming
  • If...else statement in C Programming
  • Understanding realloc() function in C
  • Understanding While loop in C
  • Why C is called middle level language?
  • Beginner's Guide to C Programming
  • First C program and Its Syntax
  • Escape Sequences and Comments in C
  • Keywords in C: List of Keywords
  • Identifiers in C: Types of Identifiers
  • Data Types in C Programming - A Beginner Guide with examples
  • Variables in C Programming - Types of Variables in C ( With Examples )
  • 10 Reasons Why You Should Learn C
  • Boolean and Static in C Programming With Examples ( Full Guide )
  • Operators in C: Types of Operators
  • Bitwise Operators in C: AND, OR, XOR, Shift & Complement
  • Expressions in C Programming - Types of Expressions in C ( With Examples )
  • Conditional Statements in C: if, if..else, Nested if
  • Switch Statement in C: Syntax and Examples
  • Ternary Operator in C: Ternary Operator vs. if...else Statement
  • Loop in C with Examples: For, While, Do..While Loops
  • Nested Loops in C - Types of Expressions in C ( With Examples )
  • Infinite Loops in C: Types of Infinite Loops
  • Jump Statements in C: break, continue, goto, return
  • Continue Statement in C: What is Break & Continue Statement in C with Example

03 Intermediate

  • Constants in C language
  • Getting Started with Data Structures in C
  • Functions in C Programming
  • Call by Value and Call by Reference in C
  • Recursion in C: Types, its Working and Examples
  • Storage Classes in C: Auto, Extern, Static, Register
  • Arrays in C Programming: Operations on Arrays
  • Strings in C with Examples: String Functions

04 Advanced

  • How to Dynamically Allocate Memory using calloc() in C?
  • How to Dynamically Allocate Memory using malloc() in C?
  • Pointers in C: Types of Pointers
  • Multidimensional Arrays in C: 2D and 3D Arrays
  • Dynamic Memory Allocation in C: Malloc(), Calloc(), Realloc(), Free()

05 Training Programs

  • Java Programming Course
  • C++ Programming Course
  • C Programming Course
  • Data Structures and Algorithms Training
  • C Programming Assignment ..

C Programming Assignment Operators

C Programming Assignment Operators

assignment operator pointer in c

C Programming For Beginners Free Course

What is an assignment operator in c.

Assignment Operators in C are used to assign values to the variables. They come under the category of binary operators as they require two operands to operate upon. The left side operand is called a variable and the right side operand is the value. The value on the right side of the "=" is assigned to the variable on the left side of "=". The value on the right side must be of the same data type as the variable on the left side. Hence, the associativity is from right to left.

In this C tutorial , we'll understand the types of C programming assignment operators with examples. To delve deeper you can enroll in our C Programming Course .

Before going in-depth about assignment operators you must know about operators in C. If you haven't visited the Operators in C tutorial, refer to Operators in C: Types of Operators .

Types of Assignment Operators in C

There are two types of assignment operators in C:

Types of Assignment Operators in C
+=addition assignmentIt adds the right operand to the left operand and assigns the result to the left operand.
-=subtraction assignmentIt subtracts the right operand from the left operand and assigns the result to the left operand.
*=multiplication assignmentIt multiplies the right operand with the left operand and assigns the result to the left operand
/=division assignmentIt divides the left operand with the right operand and assigns the result to the left operand.
%=modulo assignmentIt takes modulus using two operands and assigns the result to the left operand.

Example of Augmented Arithmetic and Assignment Operators

There can be five combinations of bitwise operators with the assignment operator, "=". Let's look at them one by one.

&=bitwise AND assignmentIt performs the bitwise AND operation on the variable with the value on the right
|=bitwise OR assignmentIt performs the bitwise OR operation on the variable with the value on the right
^=bitwise XOR assignmentIt performs the bitwise XOR operation on the variable with the value on the right
<<=bitwise left shift assignmentShifts the bits of the variable to the left by the value on the right
>>=bitwise right shift assignmentShifts the bits of the variable to the right by the value on the right

Example of Augmented Bitwise and Assignment Operators

Practice problems on assignment operators in c, 1. what will the value of "x" be after the execution of the following code.

The correct answer is 52. x starts at 50, increases by 5 to 55, then decreases by 3 to 52.

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

The correct answer is 144. After right-shifting 73 (binary 1001001) by one and then left-shifting the result by two, the value becomes 144 (binary 10010000).

Benefits of Using Assignment Operators

  • Simplifies Code: For example, x += 1 is shorter and clearer than x = x + 1.
  • Reduces Errors: They break complex expressions into simpler, more manageable parts thus reducing errors.
  • Improves Readability: They make the code easier to read and understand by succinctly expressing common operations.
  • Enhances Performance: They often operate in place, potentially reducing the need for additional memory or temporary variables.

Best Practices and Tips for Using the Assignment Operator

While performing arithmetic operations with the same variable, use compound assignment operators

  • Initialize Variables When Declaring int count = 0 ; // Initialization
  • Avoid Complex Expressions in Assignments a = (b + c) * (d - e); // Consider breaking it down: int temp = b + c; a = temp * (d - e);
  • Avoid Multiple Assignments in a Single Statement // Instead of this a = b = c = 0 ; // Do this a = 0 ; b = 0 ; c = 0 ;
  • Consistent Formatting int result = 0 ; result += 10 ;

When mixing assignments with other operations, use parentheses to ensure the correct order of evaluation.

Live Classes Schedule

Angular Certification Course Jun 22 SAT, SUN Filling Fast
ASP.NET Core (Project) Jun 23 SAT, SUN Filling Fast
Azure Developer Certification Training Jun 23 SAT, SUN Filling Fast
.NET Microservices Certification Training Jun 23 SAT, SUN Filling Fast
.NET Solution Architect Certification Training Jun 23 SAT, SUN Filling Fast
Full Stack .Net Developer Jun 30 SAT, SUN Filling Fast
ASP.NET Core Certification Training Jun 30 SAT, SUN Filling Fast
React JS Certification Training | Best React Training Course Jun 30 SAT, SUN Filling Fast
Advanced Full-Stack .NET Developer Certification Training Jun 30 SAT, SUN Filling Fast
Generative AI For Software Developers Jul 14 SAT, SUN Filling Fast

Can't find convenient schedule? Let us know

About Author

Author image

  • 22+ Video Courses
  • 800+ Hands-On Labs
  • 400+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support

We use cookies to make interactions with our websites and services easy and meaningful. Please read our Privacy Policy for more details.

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.

OperationDescription
Assigns 10 to variable
Evaluates expression and assign result to
Evaluates and assign result to
Error, you cannot re-assign a value to a constant
Error, you cannot re-assign a value to a constant

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.

Shorthand assignment operatorExampleMeaning

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 - Booleans
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • C - Storage Classes
  • C - Operators
  • C - Arithmetic Operators
  • C - Relational Operators
  • C - Logical Operators
  • C - Bitwise Operators
  • C - Assignment Operators
  • C - Unary Operators
  • C - Increment and Decrement Operators
  • C - Ternary Operator
  • C - sizeof Operator
  • C - Operator Precedence
  • C - Misc Operators
  • C - Decision Making
  • C - if statement
  • C - if...else statement
  • C - nested if statements
  • C - switch statement
  • C - nested switch statements
  • C - While loop
  • C - For loop
  • C - Do...while loop
  • C - Nested loop
  • C - Infinite loop
  • C - Break Statement
  • C - Continue Statement
  • C - goto Statement
  • C - Functions
  • C - Main Functions
  • C - Function call by Value
  • C - Function call by reference
  • C - Nested Functions
  • C - Variadic Functions
  • C - User-Defined Functions
  • C - Callback Function
  • C - Return Statement
  • C - Recursion
  • C - Scope Rules
  • C - Static Variables
  • C - Global Variables
  • 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 - Pointers and Arrays
  • C - Applications of Pointers
  • C - Pointer Arithmetics
  • C - Array of Pointers
  • C - Pointer to Pointer
  • C - Passing Pointers to Functions
  • C - Return Pointer from Functions
  • C - Function Pointers
  • C - Pointer to an Array
  • C - Pointers to Structures
  • C - Chain of Pointers
  • C - Pointer vs Array
  • C - Character Pointers and Functions
  • C - NULL Pointer
  • C - void Pointer
  • C - Dangling Pointers
  • C - Dereference Pointer
  • C - Near, Far and Huge Pointers
  • C - Initialization of Pointer Arrays
  • C - Pointers vs. Multi-dimensional Arrays
  • C - Strings
  • C - Array of Strings
  • C - Special Characters
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Self-Referential Structures
  • C - Lookup Tables
  • C - Dot (.) Operator
  • C - Enumeration (or enum)
  • C - Nested Structures
  • C - Structure Padding and Packing
  • C - Anonymous Structure and Union
  • C - Bit Fields
  • C - Typedef
  • C - Input & Output
  • C - File I/O
  • C - Preprocessors
  • C - Pragmas
  • C - Preprocessor Operators
  • C - Header Files
  • C - Type Casting
  • C - Error Handling
  • 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 language, the assignment operator stores a certain value in an already declared variable. A variable in C can be assigned the value in the form of a literal, another variable, or an expression.

The value to be assigned forms the right-hand operand, whereas the variable to be assigned should be the operand to the left of the " = " 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 −

Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign the value of A + B to C
+= Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A
-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C - A
*= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. C *= A is equivalent to C = C * A
/= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Simple Assignment Operator (=)

The = operator is one of the most frequently used operators in C. As per the 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".

Run the code and check its output −

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 will produce the following result −

To Continue Learning Please Login

  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

Pointer Arithmetics in C with Examples

  • Applications of Pointers in C
  • Passing Pointers to Functions in C
  • C - Pointer to Pointer (Double Pointer)
  • Chain of Pointers in C with Examples
  • 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
  • NULL Pointer in C
  • Dangling, Void , Null and Wild Pointers in C
  • Near, Far and Huge Pointers in C
  • restrict keyword in C

Pointer Arithmetic is the set of valid arithmetic operations that can be performed on pointers. The pointer variables store the memory address of another variable. It doesn’t store any value. 

Hence, there are only a few operations that are allowed to perform on Pointers in C language. The C pointer arithmetic operations are slightly different from the ones that we generally use for mathematical calculations. These operations are:

  • Increment/Decrement of a Pointer
  • Addition of integer to a pointer
  • Subtraction of integer to a pointer
  • Subtracting two pointers of the same type
  • Comparison of pointers

1. Increment/Decrement of a Pointer

Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. 

For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 4( size of an int ), and the new address will point to 1004 . While if a float type pointer is incremented then it will increment by 4( size of a float ) and the new address will be 1004 .

Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it actually decrements by the number equal to the size of the data type for which it is a pointer. 

For Example: If an integer pointer that stores address 1000 is decremented, then it will decrement by 4( size of an int ), and the new address will point to 996 . While if a float type pointer is decremented then it will decrement by 4( size of a float ) and the new address will be 996 .

pointer increment and decrement

Note: It is assumed here that the architecture is 64-bit and all the data types are sized accordingly. For example, integer is of 4 bytes.

Example of Pointer Increment and Decrement

Below is the program to illustrate pointer increment/decrement:

Note: Pointers can be outputted using %p, since, most of the computers store the address value in hexadecimal form using %p gives the value in that form. But for simplicity and understanding we can also use %u to get the value in Unsigned int form.

2. Addition of Integer to Pointer

When a pointer is added with an integer value, the value is first multiplied by the size of the data type and then added to the pointer.

For Example: Consider the same example as above where the ptr is an integer pointer that stores 1000 as an address. If we add integer 5 to it using the expression, ptr = ptr + 5, then, the final address stored in the ptr will be ptr = 1000 + sizeof(int) * 5 = 1020.

pointer addition

Example of Addition of Integer to Pointer

3. Subtraction  of Integer to Pointer

When a pointer is subtracted with an integer value, the value is first multiplied by the size of the data type and then subtracted from the pointer similar to addition.

For Example: Consider the same example as above where the ptr is an integer pointer that stores 1000 as an address. If we subtract integer 5 from it using the expression, ptr = ptr – 5, then, the final address stored in the ptr will be ptr = 1000 – sizeof(int) * 5 = 980.

pointer substraction

Example of Subtraction of Integer from Pointer

Below is the program to illustrate pointer Subtraction:

4. Subtraction of Two Pointers

The subtraction of two pointers is possible only when they have the same data type. The result is generated by calculating the difference between the addresses of the two pointers and calculating how many bits of data it is according to the pointer data type. The subtraction of two pointers gives the increments between the two pointers. 

For Example:   Two integer pointers say ptr1(address:1000) and ptr2(address:1004) are subtracted. The difference between addresses is 4 bytes. Since the size of int is 4 bytes, therefore the increment between ptr1 and ptr2 is given by (4/4) = 1 .

Example of Subtraction of Two Pointer

Below is the implementation to illustrate the Subtraction of Two Pointers:

5. Comparison of Pointers

We can compare the two pointers by using the comparison operators in C. We can implement this by using all operators in C >, >=, <, <=, ==, !=.   It returns true for the valid condition and returns false for the unsatisfied condition. 

  • Step 1: Initialize the integer values and point these integer values to the pointer.
  • Step 2: Now, check the condition by using comparison or relational operators on pointer variables.
  • Step 3: Display the output.

Example of Pointer Comparision

Comparison to null.

A pointer can be compared or assigned a NULL value irrespective of what is the pointer type. Such pointers are called NULL pointers and are used in various pointer-related error-handling methods.

Comparison operators on Pointers using an array

In the below approach, it results in the count of odd numbers and even numbers in an array. We are going to implement this by using a pointer.

  • Step 1: First, declare the length of an array and array elements.
  • Step 2: Declare the pointer variable and point it to the first element of an array.
  • Step 3: Initialize the count_even and count_odd. Iterate the for loop and check the conditions for the number of odd elements and even elements in an array
  • Step 4: Increment the pointer location ptr++ to the next element in an array for further iteration.
  • Step 5: Print the result.

Example of Pointer Comparison in Array

Pointer Arithmetic on Arrays

Pointers contain addresses. Adding two addresses makes no sense because there is no idea what it would point to. Subtracting two addresses lets you compute the offset between the two addresses. An array name acts like a pointer constant. The value of this pointer constant is the address of the first element.

For Example: if an array is named arr then arr and &arr[0] can be used to reference the array as a pointer.

Below is the program to illustrate the Pointer Arithmetic on arrays:

Program 1:  

Program 2:  

Please Login to comment...

Similar reads.

  • C-Advanced Pointer
  • C-Pointer Basics

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

22.3 — Move constructors and move assignment

Related content

You now have enough context to understand the key insight behind move semantics.

Automatic l-values returned by value may be moved instead of copied

IMAGES

  1. Pointer Expressions in C with Examples

    assignment operator pointer in c

  2. Pointer Expressions in C with Examples

    assignment operator pointer in c

  3. Pointer Expressions in C with Examples

    assignment operator pointer in c

  4. Pointer Expressions in C with Examples

    assignment operator pointer in c

  5. Expressions de pointeur en C avec exemples

    assignment operator pointer in c

  6. Pointers in C/C++ with Examples

    assignment operator pointer in c

VIDEO

  1. Pointer & Linked List

  2. indirection operator in c

  3. assignment operators in c language

  4. Augmented assignment operators in C

  5. Conditional Expression in C

  6. POINTER in C-Language Practical

COMMENTS

  1. Directly assigning values to C Pointers

    You need to create an int variable somewhere in memory for the int * variable to point at. Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do: int main(){. int variable; int *ptr = &variable; *ptr = 20; printf("%d", *ptr); return 0;

  2. C Pointers

    The use of pointers in C can be divided into three steps: Pointer Declaration. Pointer Initialization. Pointer Dereferencing. 1. Pointer Declaration. In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer, we use the ( * ) dereference operator before its name. Example.

  3. Assignment operators

    Assignment performs implicit conversion from the value of rhs to the type of lhs and then replaces the value in the object designated by lhs with the converted value of rhs . Assignment also returns the same value as what was stored in lhs (so that expressions such as a = b = c are possible). The value category of the assignment operator is non ...

  4. Assignment Operators in C

    1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators. This operator first adds the current value of the variable on left to the value on the right and ...

  5. C Pointers (With Examples)

    Explanation of the program. int* pc, c; Here, a pointer pc and a normal variable c, both of type int, is created. Since pc and c are not initialized at initially, pointer pc points to either no address or a random address. And, variable c has an address but contains random garbage value.; c = 22; This assigns 22 to the variable c.That is, 22 is stored in the memory location of variable c.

  6. C Pointers Tutorial: Chapter 1

    The lvalue is the value permitted on the left side of the assignment operator '=' (i.e. the address where the result of evaluation of the right side ends up). The rvalue is that which is on the right side of the assignment statment, the '2' above. ... In C when we define a pointer variable we do so by preceding its name with an asterisk. In C ...

  7. Assignment operators

    for assignments to class type objects, the right operand could be an initializer list only when the assignment is defined by a user-defined assignment operator. removed user-defined assignment constraint. CWG 1538. C++11. E1 ={E2} was equivalent to E1 = T(E2) ( T is the type of E1 ), this introduced a C-style cast. it is equivalent to E1 = T{E2}

  8. Operators in C

    In C, there are 11 assignment operators : S. No. Symbol. Operator Description. Syntax. 1 = Simple Assignment: Assign the value of the right operand to the left operand. a = b. 2 += Plus and assign: ... The pointer operator * is a pointer to a variable. For example *var; will pointer to a variable var. ...

  9. C Assignment Operators

    Code language:C++(cpp) The = assignment operator is called a simple assignment operator. It assigns the value of the left operand to the right operand. Besides the simple assignment operator, C supports compound assignment operators. A compound assignment operator performs the operation specified by the additional operator and then assigns the ...

  10. 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. C Assignment Operators.

  11. C Programming Assignment Operators

    Assignment Operators in C are used to assign values to the variables. They come under the category of binary operators as they require two operands to operate upon. The left side operand is called a variable and the right side operand is the value. The value on the right side of the "=" is assigned to the variable on the left side of "=".

  12. Assignment and shorthand assignment operator in C

    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.

  13. Assignment Operators in C with Examples

    C supports following Assignment operators: 1. Simple Assignment = Operator Example. This is one of the simplest assignment operator, it simply assigns the right side value to the left side operand. #include <stdio.h> int main () { int n; //integer variable char ch; //character variable float f; //float variable // Simple assignment operator to ...

  14. 21.12

    21.12 — Overloading the assignment operator. Alex November 27, 2023. The copy assignment operator (operator=) is used to copy values from one object to another already existing object. As of C++11, C++ also supports "Move assignment". We discuss move assignment in lesson 22.3 -- Move constructors and move assignment .

  15. Assignment Operators in C

    Assigns values from right side operands to left side operand. C = A + B will assign the value of A + B to C. +=. Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A. -=. Subtract AND assignment operator.

  16. Pointer Arithmetics in C with Examples

    Step 1: First, declare the length of an array and array elements. Step 2: Declare the pointer variable and point it to the first element of an array. Step 3: Initialize the count_even and count_odd. Iterate the for loop and check the conditions for the number of odd elements and even elements in an array.

  17. 22.3

    In lesson 22.1 -- Introduction to smart pointers and move semantics, we took a look at std::auto_ptr, discussed the desire for move semantics, and took a look at some of the downsides that occur when functions designed for copy semantics (copy constructors and copy assignment operators) are redefined to implement move semantics.. In this lesson, we'll take a deeper look at how C++11 resolves ...

  18. How can you assign a value to the pointer 'this' in C++

    0. You can not. "this" is a hidden argument to every member function of a class and its type for an object of Class X is X* const. This clearly means that you can not assign a new vale to "this" as it is defined as a const. You can however modify the value pointed to by this.

  19. Operators in C and C++

    This is a list of operators in the C and C++ programming languages.All the operators (except typeof) listed exist in C++; the column "Included in C", states whether an operator is also present in C. Note that C does not support operator overloading.. When not overloaded, for the operators &&, ||, and , (the comma operator), there is a sequence point after the evaluation of the first operand.

  20. c++

    That's a good idea! Will give it a try. One question though: if I overload = operator let's say like this: ic* operator= (ic* i) { copies data from i to left hand side; } That actually works. So you can overload the assignment operator for pointers. To me it seems the issue is that lhs and rhs are not the same type.

  21. C++ Assignment operator for class that contains a unique pointer member

    1. You can create a move assignment operator which moves everything (in this case, with test& operator=(test&& other) = default; ), but that would also move the vector instead of copying it. If you implemented it manually you could do what you ask (are you getting stuck trying it), but it wouldn't behave as most people using your class would ...

  22. c++

    I have tried making the template inherit from it's type name as specified above. I have also tried overloading the assignment operator like. T* operator=(numa<T, NodeID>* ptr) { return static_cast<T*>(ptr); } inside the template definition