• Assignment Statement

An Assignment statement is a statement that is used to set a value to the variable name in a program .

Assignment statement allows a variable to hold different types of values during its program lifespan. Another way of understanding an assignment statement is, it stores a value in the memory location which is denoted by a variable name.

Assignment Statement Method

The symbol used in an assignment statement is called as an operator . The symbol is ‘=’ .

Note: The Assignment Operator should never be used for Equality purpose which is double equal sign ‘==’.

The Basic Syntax of Assignment Statement in a programming language is :

variable = expression ;

variable = variable name

expression = it could be either a direct value or a math expression/formula or a function call

Few programming languages such as Java, C, C++ require data type to be specified for the variable, so that it is easy to allocate memory space and store those values during program execution.

data_type variable_name = value ;

In the above-given examples, Variable ‘a’ is assigned a value in the same statement as per its defined data type. A data type is only declared for Variable ‘b’. In the 3 rd line of code, Variable ‘a’ is reassigned the value 25. The 4 th line of code assigns the value for Variable ‘b’.

Assignment Statement Forms

This is one of the most common forms of Assignment Statements. Here the Variable name is defined, initialized, and assigned a value in the same statement. This form is generally used when we want to use the Variable quite a few times and we do not want to change its value very frequently.

Tuple Assignment

Generally, we use this form when we want to define and assign values for more than 1 variable at the same time. This saves time and is an easy method. Note that here every individual variable has a different value assigned to it.

(Code In Python)

Sequence Assignment

(Code in Python)

Multiple-target Assignment or Chain Assignment

In this format, a single value is assigned to two or more variables.

Augmented Assignment

In this format, we use the combination of mathematical expressions and values for the Variable. Other augmented Assignment forms are: &=, -=, **=, etc.

Browse more Topics Under Data Types, Variables and Constants

  • Concept of Data types
  • Built-in Data Types
  • Constants in Programing Language 
  • Access Modifier
  • Variables of Built-in-Datatypes
  • Declaration/Initialization of Variables
  • Type Modifier

Few Rules for Assignment Statement

Few Rules to be followed while writing the Assignment Statements are:

  • Variable names must begin with a letter, underscore, non-number character. Each language has its own conventions.
  • The Data type defined and the variable value must match.
  • A variable name once defined can only be used once in the program. You cannot define it again to store other types of value.
  • If you assign a new value to an existing variable, it will overwrite the previous value and assign the new value.

FAQs on Assignment Statement

Q1. Which of the following shows the syntax of an  assignment statement ?

  • variablename = expression ;
  • expression = variable ;
  • datatype = variablename ;
  • expression = datatype variable ;

Answer – Option A.

Q2. What is an expression ?

  • Same as statement
  • List of statements that make up a program
  • Combination of literals, operators, variables, math formulas used to calculate a value
  • Numbers expressed in digits

Answer – Option C.

Q3. What are the two steps that take place when an  assignment statement  is executed?

  • Evaluate the expression, store the value in the variable
  • Reserve memory, fill it with value
  • Evaluate variable, store the result
  • Store the value in the variable, evaluate the expression.

Customize your course in 30 seconds

Which class are you in.

tutor

Data Types, Variables and Constants

  • Variables in Programming Language
  • Concept of Data Types
  • Declaration of Variables
  • Type Modifiers
  • Access Modifiers
  • Constants in Programming Language

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Download the App

Google Play

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 - if statement
  • C - if...else statement
  • C - nested if statements
  • C - switch statement
  • C - nested switch statements
  • C - While loop
  • C - Functions
  • C - Main Functions
  • C - Return Statement
  • C - Scope Rules
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • C - Pointers
  • C - Pointer Arithmetics
  • C - Passing Pointers to Functions
  • C - Strings
  • C - Array of Strings
  • C - Structures
  • C - Structures and Functions
  • C - Arrays of Structures
  • C - Pointers to Structures
  • C - Self-Referential Structures
  • C - Nested Structures
  • C - Bit Fields
  • C - Typedef
  • C - Input & Output
  • C - File I/O
  • C - Preprocessors
  • C - Header Files
  • C - Type Casting
  • C - Error Handling
  • C - Recursion
  • C - Variable Arguments
  • C - Memory Management
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Useful Resources
  • C - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

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 Statement (=) in C Language

Assignment Statement in C language is a statement that assigns or set a value to a variable during program execution. Assignement statements in programming allows the programmer to change or set the value stored in variable using Assignment(=) Operator. The process of assigning the value to a variable using the assignment(=) operator is known as an assignment statement in C. Assignment(=) Operator Assigns The value or value in a variable on right hand side to the variable on the left hand side. The data type of the variable on right hand side should match to the data type of variable or constant or expression on right hand side. C Language has different (types) ways to assigns values to variable, we will learn from the diagram given below.

  Syntax :1.Basic Assignment statement

Data Type Variable_name = variable/ constant /expression; The Variable_name is assigned the values in variable or constants or expression. The data type of the variable/ constant/expression on right hand side should match to the left hand side variable Variable_name with a few exceptions where automatic type conversions are possible.

Naming Rules or conventions for Assignment Statement

Programmer need to follow some Rules while writing the Assignment Statements in C program: 1. Variable names should not begin or start with number. Variable name can a letter, underscore, non-number any character like alphabet,underscore. 2. A new value assigned to an existing variable will overwrite the previous value and assign the new value to the variable. 3. The Data type defined and the variable value must match. 4.All the statements declaration must end with a semi-colon. (;) 5. The name of variable must be meaningful and clearly describe the purpose of variable name. 6.Duplicate name of variable is not allowed i.e the name once defined can only be used once in the program. programmer cannot redefine it to store other types of value.

 assignment statements in C programming

Example 1: C program to illustrates the use of Simple Assignment statement .

/* e.g. C program to illustrate the use of simple Assignment statement or basic of assignment statements */ #include<stdio.h> int main() { int a,b,c; float avg; a = 9 ; c = 10 ; b = c ; printf("\n a=%d",a); printf("\n b=%d",b); printf("\n c=%d",c); b = c+3; printf("\n Value of b after b=c+3-->%d",b); avg = (b+c) / 2.0; printf("\n Value of avg=%.2f",avg); a = b && c; printf("\n a=b&&c--->%d",a); a = (b+c) && (b <c); printf("\n a=(b+c) && (b <c)--->%d",a); return(0); } Output: a=9 b=10 c=10 Value of b after b=c+3-->13 Value of avg=11.50 a=b&&c--->1 a=(b+c) && (b <c)--->0

Program Explanation: 1. In the above program a,b,c is declared as integer variable to store the numbers where as avg is declared as float. int a,b,c; float avg; 2. a = 9 ; c = 10 ; b = c ; variable a is assigned value 9. variable c is assigned value 10. and b is assigned the value of c. Here value of b is 10 .i.e. b=10 3. printf("\n a=%d",a); printf("\n b=%d",b); printf("\n c=%d",c); The above statements displays the integer values of variable a,b,c a=9 b=10 c=10 4. b = c+3; printf("\n Value of b after b=c+3-->%d",b); here 3 is added in c(value of vaiable c is 10) it becomes 13 and value 13 is assigned to left hand side variable b , here b is 13 i.e. b=13. the printf() displays output " Value of b after b=c+3--->13". 5. avg = (b+c) / 2.0; printf("\n Value of avg=%.2f",avg); After execution of a=(b+c)/2.0 the value of a is 11.50 so the output shown by printf() is "Value of avg=11.50". 6. a = b && c; printf("\n a=b&&c--->%d",a); Logical anding operation is performed on the values in the variables a and b. The value of c=10 and the value of b=13. After succesful execution of this statement value of variable a is 1 or 'true'. Any value in a variable except 'zero' (0 i.e false) is considered 'true' or 1. The variable a is assigned to the integer value 1 which is true. so a=1 && 1 is a=1 or a=true && true is a=true or a=1. printf("\n a=b&&c--->%d",a); displays output a=b&&c---->1 7. a = (b+c) && (b <c); printf("\n a=(b+c) && (b <c)--->%d",a); here expression (b+c) is true(1) and (b <c) is false(0). so the entire expression evaluates to false(0) and the value is assigned to the variable a i.e a=0. the printf() display the message " a=(b+c) && (b <c)--->0 "

2.Compound Assignment: As we learn in above section the simple assignment statement is used to assign values in right hand side variable to left hand side variable using = operator. A compound assignment operator has a shorter syntax to assign the result. A compound assignment operator or statements are used to do mathematical operation in shortcut. Two operands needs to perform the compound assignment operations. The operation is performed on the two operands before the result is assigned to the first operand. compound assignment operator are binary operators that modify the variable to their left hand side using the value or variable to their right.

Syntax: expression1+= expression2; These type of expression can also be written in expanded form, that is expression1=expression1+expression2;

+= Operator is called compound assignment operator. C Language provides the following list of compound Assignment Operators. 1.   += plus equal to += is Addition and Assignment operators. It add the value of the variable1 and variable2 and assigns the result to variable1. e.g. X+=Y In the above expression the addition of values in X and Y is performd and assigns result to X. The expression X+=Y is same as X=X+Y 2.   -= minus equal to -= is Subtraction and Assignment operators. It Subtract the value of the variable2 from variable1 and assigns the result to variable1. e.g. X-=Y In the above expression the subtraction is performd,the value of X is subtracted from the value in X and assigns result to X. The expression X-=Y is same as X=X-Y 3.   *= Multiplication equal to *= is Multiplication and Assignment operators. It Multiply the value of the variable1 and variable2 and assigns the result to variable1. e.g. X*=Y In the above expression the Multiplication is performd,the value of X is Multiplyed to the value in Y and assigns result to X. The expression X*=Y is same as X=X*Y 4.   /= Division equal to *= is Division and Assignment operators. It Divides the value of the variable1 byvariable2 and assigns the result to variable1. e.g. X/=Y In the above expression the Division is performd,the value of X is Divided by the value in Y and assigns result to X. The expression X/=Y is same as X=X/Y 5.   %= Modulus equal to %= is Modulus and Assignment operators. It Divides the value of the variable1 byvariable2 and assigns the remainder to variable1. e.g. X%=Y In the above expression the Division is performd,the value of X is Divided by the value in Y and assigns remainder to X. The expression X%=Y is same as X=X%Y 6.   &= Bitwise and equal to &= is Bitwise AND and Assignment operators. It performs the bitwise AND with variable1 and variable2 and assigns the result to variable1. e.g. X&=Y In the above expression the bitwise anding operation is performd, after executing the X&=Y expression the result is assigned to X. The expression X&=Y is same as X=X&Y 7.   |= Bitwise OR equal to != is Bitwise OR Assignment operators. It performs the bitwise OR with variable1 and variable2 and assigns the result to variable1. e.g. X|=Y In the above expression the bitwise OR operation is performd, after executing the X|=Y expression the result is assigned to X. The expression X|=Y is same as X=X|Y 8.   ^= Bitwise XOR equal to ^= is Bitwise XOR Assignment operators. It performs the bitwise XOR with variable1 and variable2 and assigns the result to variable1. e.g. X^=Y In the above expression the bitwise XOR operation is performd, after executing the X^=Y expression the result is assigned to X. The expression X^=Y is same as X=X^Y. 9.   Bitwise left shift and equal to e.g. X In the above expression the bitwise left shift operation is performd, after executing the X The expression X 10.   >>= Bitwise right shift and equal to >>= is Bitwise Right Shift and Assignment operators. It performs the bitwise Right shift with variable1 and assigns the result to variable1. e.g. X>>=Y In the above expression the bitwise right shift operation is performd, after executing the X>>=Y expression the result is assigned to X. The expression X>>=Y is same as X=X>>Y Lets Learn and practice The Assigment operator in detail using the following C program.

2. Assignment Operator complete C Program.

#include <stdio.h> int main() {   /* Simple Assignment*/   int x,i;  int y,j;  float c=30.0;  float d=5.0;  /*Nested or Multiple Assignment */  x = i = 5;  y = j = 3;  /*Compound Assignment*/   x += y;   printf("After Add and Assign :%d \n",x);  i -= j;  printf("After Subtract and Assign :%d \n",i);  x *= y;  printf("After Multiple and Assign :%d \n",x);  c /= d;  printf("After Divide and Assign :%f \n",c);  j %= i;  printf("After Modulo and Assign :%d \n",j);  j &= i; printf("After Bitwise And and Assign :%d \n",j);  j |= i;   printf("After Bitwise OR and Assign :%d \n",j);   x ^= y;  printf("After Bitwise XOR and Assign :%d \n",a);   x   printf ("After Bitwise Left Shift and Assign :%d \n",a);  x >>= 3;  printf ("After Bitwise Right Shift and Assign :%d \n",a);   return(0); }

Output: After Add and Assign :8 After Subtract and Assign :2 After Multiple and Assign :24 After Divide and Assign :6.000000 After Modulo and Assign :1 After Bitwise And and Assign :0 After Bitwise OR and Assign :2 After Bitwise XOR and Assign :27 After Bitwise Left Shift and Assign :108 After Bitwise Right Shift and Assign :13

/** * C program to check leap year using conditional operator ? */ #include <stdio.h> int main() { int year; /* * Input the year from user */ printf("Enter any year: "); scanf("%d", &year); /* * If year%4==0 and year%100==0 then * print leap year * else if year%400==0 then * print leap year * else * print common year */ (year%4==0 && year%100!=0) ? printf("LEAP YEAR") : (year%400 ==0 ) ? printf("LEAP YEAR") : printf("COMMON YEAR"); return 0; } Output: Enter any year 2004 LEAP YEAR

/** * C program to check leap year using conditional operator ? */ #include <stdio.h> int main() { int year; /* * Input the year from user */ printf("Enter any year: "); scanf("%d", &year); /* If year%4==0 and year%100==0 then print leap year else if year%400==0 then print leap year else print common year */ (year%4==0 && year%100!=0) ? printf("LEAP YEAR") : (year%400 ==0 ) ? printf("LEAP YEAR") : printf("COMMON YEAR"); return 0; } Output: Enter any year 2004 LEAP YEAR

Previous Topic:-->> Constant and Literals in C  || Next topic:-->> Input/Output in C.

Get in touch

Logo for Rebus Press

Want to create or adapt books like this? Learn more about how Pressbooks supports open publishing practices.

Kenneth Leroy Busbee

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

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 most programming languages the symbol used for assignment 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.

Simple Assignment

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.

Assignment with an Expression

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 be assigned to the variable named: total_cousins.

Assignment with Identifier Names in the Expression

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.

  • cnx.org: Programming Fundamentals – A Modular Structured Approach using C++
  • Wikipedia: Assignment (computer science) ↵

Programming Fundamentals Copyright © 2018 by Kenneth Leroy Busbee is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License , except where otherwise noted.

Share This Book

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.

PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Sign in to your account

Forgot your password?

Login via OTP

We will send you an one time password on your mobile number

An OTP has been sent to your mobile number please verify it below

Register with PrepBytes

Assignment operator in c.

' src=

Last Updated on June 23, 2023 by Prepbytes

assignment statement using c

This type of operator is employed for transforming and assigning values to variables within an operation. In an assignment operation, the right side represents a value, while the left side corresponds to a variable. It is essential that the value on the right side has the same data type as the variable on the left side. If this requirement is not fulfilled, the compiler will issue an error.

What is Assignment Operator in C language?

In C, the assignment operator serves the purpose of assigning a value to a variable. It is denoted by the equals sign (=) and plays a vital role in storing data within variables for further utilization in code. When using the assignment operator, the value present on the right-hand side is assigned to the variable on the left-hand side. This fundamental operation allows developers to store and manipulate data effectively throughout their programs.

Example of Assignment Operator in C

For example, consider the following line of code:

Types of Assignment Operators in C

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

Simple assignment operator (=): This is the basic assignment operator, which assigns the value on the right-hand side to the variable on the left-hand side.

Addition assignment operator (+=): This operator adds the value on the right-hand side to the variable on the left-hand side and assigns the result back to the variable.

x += 3; // Equivalent to x = x + 3; (adds 3 to the current value of "x" and assigns the result back to "x")

Subtraction assignment operator (-=): This operator subtracts the value on the right-hand side from the variable on the left-hand side and assigns the result back to the variable.

x -= 4; // Equivalent to x = x – 4; (subtracts 4 from the current value of "x" and assigns the result back to "x")

* Multiplication assignment operator ( =):** This operator multiplies the value on the right-hand side with the variable on the left-hand side and assigns the result back to the variable.

x = 2; // Equivalent to x = x 2; (multiplies the current value of "x" by 2 and assigns the result back to "x")

Division assignment operator (/=): This operator divides the variable on the left-hand side by the value on the right-hand side and assigns the result back to the variable.

x /= 2; // Equivalent to x = x / 2; (divides the current value of "x" by 2 and assigns the result back to "x")

Bitwise AND assignment (&=): The bitwise AND assignment operator "&=" performs a bitwise AND operation between the value on the left-hand side and the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x &= 3; // Binary: 0011 // After bitwise AND assignment: x = 1 (Binary: 0001)

Bitwise OR assignment (|=): The bitwise OR assignment operator "|=" performs a bitwise OR operation between the value on the left-hand side and the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x |= 3; // Binary: 0011 // After bitwise OR assignment: x = 7 (Binary: 0111)

Bitwise XOR assignment (^=): The bitwise XOR assignment operator "^=" performs a bitwise XOR operation between the value on the left-hand side and the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x ^= 3; // Binary: 0011 // After bitwise XOR assignment: x = 6 (Binary: 0110)

Left shift assignment (<<=): The left shift assignment operator "<<=" shifts the bits of the value on the left-hand side to the left by the number of positions specified by the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x <<= 2; // Binary: 010100 (Shifted left by 2 positions) // After left shift assignment: x = 20 (Binary: 10100)

Right shift assignment (>>=): The right shift assignment operator ">>=" shifts the bits of the value on the left-hand side to the right by the number of positions specified by the value on the right-hand side. It then assigns the result back to the left-hand side variable.

x >>= 2; // Binary: 101 (Shifted right by 2 positions) // After right shift assignment: x = 5 (Binary: 101)

Conclusion The assignment operator in C, denoted by the equals sign (=), is used to assign a value to a variable. It is a fundamental operation that allows programmers to store data in variables for further use in their code. In addition to the simple assignment operator, C provides compound assignment operators that combine arithmetic or bitwise operations with assignment, allowing for concise and efficient code.

FAQs related to Assignment Operator in C

Q1. Can I assign a value of one data type to a variable of another data type? In most cases, assigning a value of one data type to a variable of another data type will result in a warning or error from the compiler. It is generally recommended to assign values of compatible data types to variables.

Q2. What is the difference between the assignment operator (=) and the comparison operator (==)? The assignment operator (=) is used to assign a value to a variable, while the comparison operator (==) is used to check if two values are equal. It is important not to confuse these two operators.

Q3. Can I use multiple assignment operators in a single statement? No, it is not possible to use multiple assignment operators in a single statement. Each assignment operator should be used separately for assigning values to different variables.

Q4. Are there any limitations on the right-hand side value of the assignment operator? The right-hand side value of the assignment operator should be compatible with the data type of the left-hand side variable. If the data types are not compatible, it may lead to unexpected behavior or compiler errors.

Q5. Can I assign the result of an expression to a variable using the assignment operator? Yes, it is possible to assign the result of an expression to a variable using the assignment operator. For example, x = y + z; assigns the sum of y and z to the variable x.

Q6. What happens if I assign a value to an uninitialized variable? Assigning a value to an uninitialized variable will initialize it with the assigned value. However, it is considered good practice to explicitly initialize variables before using them to avoid potential bugs or unintended behavior.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

  • Linked List
  • Segment Tree
  • Backtracking
  • Dynamic Programming
  • Greedy Algorithm
  • Operating System
  • Company Placement
  • Interview Tips
  • General Interview Questions
  • Data Structure
  • Other Topics
  • Computational Geometry
  • Game Theory

Related Post

Null character in c, ackermann function in c, median of two sorted arrays of different size in c, number is palindrome or not in c, implementation of queue using linked list in c, c program to replace a substring in a string.

Next: Unions , Previous: Overlaying Structures , Up: Structures   [ Contents ][ Index ]

15.13 Structure Assignment

Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example:

Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

See Assignment Expressions .

When a structure type has a field which is an array, as here,

structure assigment such as r1 = r2 copies array fields’ contents just as it copies all the other fields.

This is the only way in C that you can operate on the whole contents of a array with one operation: when the array is contained in a struct . You can’t copy the contents of the data field as an array, because

would convert the array objects (as always) to pointers to the zeroth elements of the arrays (of type struct record * ), and the assignment would be invalid because the left operand is not an lvalue.

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

cppreference.com

Assignment operators.

Assignment operators modify the value of the object.

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

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 must have higher precedence than an assignment expression.
  • ↑ new-value cannot be a comma expression, because its precedence is lower.

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

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

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

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:

[ 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:

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:

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

[ edit ] Example

Possible output:

[ edit ] Defect reports

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

[ edit ] See also

Operator precedence

Operator overloading

  • 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 22:41.
  • This page has been accessed 410,142 times.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
  • Compound Statements in C++
  • Rethrowing an Exception in C++
  • Variable Shadowing in C++
  • Condition Variables in C++ Multithreading
  • C++23 <print> Header
  • Literals In C++
  • How to Define Constants in C++?
  • C++ Variable Templates
  • Introduction to GUI Programming in C++
  • Concurrency in C++
  • Hybrid Inheritance In C++
  • Dereference Pointer in C
  • shared_ptr in C++
  • Nested Inline Namespaces In C++20
  • C++20 std::basic_syncbuf
  • std::shared_mutex in C++
  • Partial Template Specialization in C++
  • Pass By Reference In C
  • Address Operator & in C

Assignment Operators In C++

In C++, the assignment operator forms the backbone of many algorithms and computational processes by performing a simple operation like assigning a value to a variable. It is denoted by equal sign ( = ) and provides one of the most basic operations in any programming language that is used to assign some value to the variables in C++ or in other words, it is used to store some kind of information.

The right-hand side value will be assigned to the variable on the left-hand side. The variable and the value should be of the same data type.

The value can be a literal or another variable of the same data type.

Compound Assignment Operators

In C++, the assignment operator can be combined into a single operator with some other operators to perform a combination of two operations in one single statement. These operators are called Compound Assignment Operators. 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 ( |= )
  • Bitwise XOR Assignment Operator ( ^= )
  • Left Shift Assignment Operator ( <<= )
  • Right Shift Assignment Operator ( >>= )

Lets see each of them in detail.

1. Addition Assignment Operator (+=)

In C++, the addition assignment operator (+=) combines the addition operation with the variable assignment allowing you to increment the value of variable by a specified expression in a concise and efficient way.

This above expression is equivalent to the expression:

2. Subtraction Assignment Operator (-=)

The subtraction assignment operator (-=) in C++ enables you to update the value of the variable by subtracting another value from it. This operator is especially useful when you need to perform subtraction and store the result back in the same variable.

3. Multiplication Assignment Operator (*=)

In C++, the multiplication assignment operator (*=) is used to update the value of the variable by multiplying it with another value.

4. Division Assignment Operator (/=)

The division assignment operator divides the variable on the left by the value on the right and assigns the result to the variable on the left.

5. Modulus Assignment Operator (%=)

The modulus assignment operator calculates the remainder when the variable on the left is divided by the value or variable on the right and assigns the result to the variable on the left.

6. Bitwise AND Assignment Operator (&=)

This operator performs a bitwise AND between the variable on the left and the value on the right and assigns the result to the variable on the left.

7. Bitwise OR Assignment Operator (|=)

The bitwise OR assignment operator performs a bitwise OR between the variable on the left and the value or variable on the right and assigns the result to the variable on the left.

8. Bitwise XOR Assignment Operator (^=)

The bitwise XOR assignment operator performs a bitwise XOR between the variable on the left and the value or variable on the right and assigns the result to the variable on the left.

9. Left Shift Assignment Operator (<<=)

The left shift assignment operator shifts the bits of the variable on the left to left by the number of positions specified on the right and assigns the result to the variable on the left.

10. Right Shift Assignment Operator (>>=)

The right shift assignment operator shifts the bits of the variable on the left to the right by a number of positions specified on the right and assigns the result to the variable on the left.

Also, it is important to note that all of the above operators can be overloaded for custom operations with user-defined data types to perform the operations we want.

Please Login to comment...

Similar reads.

  • Geeks Premier League 2023
  • Geeks Premier League
  • 10 Best Todoist Alternatives in 2024 (Free)
  • How to Get Spotify Premium Free Forever on iOS/Android
  • Yahoo Acquires Instagram Co-Founders' AI News Platform Artifact
  • OpenAI Introduces DALL-E Editor Interface
  • Top 10 R Project Ideas for Beginners in 2024

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

COMMENTS

  1. Assignment Statement in C Programming Language

    C provides an assignment operator for this purpose, assigning the value to a variable using assignment operator is known as an assignment statement in C. The function of this operator is to assign the values or values in variables on right hand side of an expression to variables on the left hand side. The syntax of the assignment expression

  2. Assignment Expressions (GNU C Language Manual)

    7 Assignment Expressions. As a general concept in programming, an assignment is a construct that stores a new value into a place where values can be stored—for instance, in a variable. Such places are called lvalues (see Lvalues) because they are locations that hold a value. An assignment in C is an expression because it has a value; we call it an assignment expression.

  3. What are Assignment Statement: Definition, Assignment Statement ...

    Assignment Statement. An Assignment statement is a statement that is used to set a value to the variable name in a program. Assignment statement allows a variable to hold different types of values during its program lifespan. Another way of understanding an assignment statement is, it stores a value in the memory location which is denoted.

  4. Assignment Operators in C

    Different types of assignment operators are shown below: 1. "=": This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. Example: 2. "+=": This operator is combination of '+' and '=' operators.

  5. Assignment Operators in C

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

  6. Assignment statements in C Language Skill UP

    1.Simple Assignment or Basic Form: Simple Assignment or Basic form is one of the common forms of Assignment Statements in C program. Simple Assignment allow the programmer to declare,define and initialize and assign a value in the same statement to a variable. This form is generally used when the programmer want to use the Variable a few times.

  7. Assignment

    Assignment Kenneth Leroy Busbee. Overview. 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. [1] Discussion. The assignment operator allows us to change the value of a modifiable data object (for beginning programmers this typically means a variable).

  8. c

    The rule is to return the right-hand operand of = converted to the type of the variable which is assigned to. int a; float b; a = b = 4.5; // 4.5 is a double, it gets converted to float and stored into b. // this returns a float which is converted to an int and stored in a. // the whole expression returns an int.

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

  10. Assignment and shorthand assignment operator in C

    Shorthand assignment operator combines one of the arithmetic or bitwise operators with assignment operator. For example, consider following C statements. int a = 5; a = a + 2; 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.

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

  12. Assignment Operator in C

    In C, the assignment operator serves the purpose of assigning a value to a variable. It is denoted by the equals sign (=) and plays a vital role in storing data within variables for further utilization in code. When using the assignment operator, the value present on the right-hand side is assigned to the variable on the left-hand side.

  13. Structure Assignment (GNU C Language Manual)

    15.13 Structure Assignment. Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example: Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

  14. Assignment Operator in C

    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 %=. Example of the Assignment Operators: A = 5; // use Assignment symbol to assign 5 to the operand A. B = A; // Assign operand A to the B.

  15. c

    For your specific example: while (c = getchar(), c != EOF && c != 'x') the following occurs: c = getchar() is executed fully (the comma operator is a sequence point). c != EOF && c != 'x' is executed. the comma operator throws away the first value (c) and "returns" the second. the while uses that return value to control the loop.

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

  17. Assignment Operators In C++

    In C++, the addition assignment operator (+=) combines the addition operation with the variable assignment allowing you to increment the value of variable by a specified expression in a concise and efficient way. Syntax. variable += value; This above expression is equivalent to the expression: variable = variable + value; Example.

  18. c

    The first getchar() loop gets a warning from GCC; the latter two do not because of the the explicit test of the value from the assignment. The people who write a condition like this: while ((c = getchar())) really annoy me. It avoids the warning from GCC, but it is not (IMNSHO) a good way of coding. edited May 30, 2012 at 5:00.

  19. Python's Assignment Operator: Write Robust Assignments

    To create a new variable or to update the value of an existing one in Python, you'll use an assignment statement. This statement has the following three components: A left operand, which must be a variable. The assignment operator ( =) A right operand, which can be a concrete value, an object, or an expression.

  20. Variable assignment inside a C++ 'if' statement

    A variable declaration statement isn't an expression, so you can't treat (int i = 5) as an expression. For the second one, I suspect you just need to update your compiler. g++ 5.6 is a fairly old version at this point, and I believe more updates versions of g++ will handle that code with no problem.

  21. C assignments in an 'if' statement

    Basically C evaluates expressions. In. s = data[q] The value of data[q] is the the value of expression here and the condition is evaluated based on that. The assignment. s <- data[q] is just a side-effect.