• 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

C Data Types

C operators.

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

C File Handling

  • C Cheatsheet

C Interview Questions

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

C Variables and Constants

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

C Input/Output

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

Assignment Operators in C

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

C Control Statements Decision-Making

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

C Arrays & Strings

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

C User-Defined Data Types

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

C Storage Classes

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

C Memory Management

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

C Preprocessor

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

Miscellaneous

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

assignment statement in c

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

Different types of assignment operators are shown below:

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

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

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

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

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

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

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

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

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

Below example illustrates the various Assignment Operators:

Please Login to comment...

Similar reads.

  • C-Operators
  • cpp-operator

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Assignment Statement in C

How to assign values to the variables? 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

Variable = constant / variable/ expression;

The data type of the variable on left hand side should match the data type of constant/variable/expression on right hand side with a few exceptions where automatic type conversions are possible.

Examples of assignment statements,

b = c ; /* b is assigned the value of c */ a = 9 ; /* a is assigned the value 9*/ b = c+5; /* b is assigned the value of expr c+5 */

The expression on the right hand side of the assignment statement can be:

An arithmetic expression; A relational expression; A logical expression; A mixed expression.

The above mentioned expressions are different in terms of the type of operators connecting the variables and constants on the right hand side of the variable. Arithmetic operators, relational

Arithmetic operators, relational operators and logical operators are discussed in the following sections.

For example, int a; float b,c ,avg, t; avg = (b+c) / 2; /*arithmetic expression */ a = b && c; /*logical expression*/ a = (b+c) && (b<c); /* mixed expression*/

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Facebook (Opens in new window)

Related Posts

  • #define to implement constants
  • Preprocessor in C Language
  • Pointers and Strings

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.

Notify me of follow-up comments by email.

Notify me of new posts by email.

This site uses Akismet to reduce spam. Learn how your comment data is processed .

CProgramming Tutorial

  • C Programming Tutorial
  • Basics of C
  • 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 - Type Casting
  • C - Booleans
  • Constants and Literals in C
  • C - Constants
  • C - Literals
  • C - Escape sequences
  • C - Format Specifiers
  • Operators in C
  • 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
  • Decision Making in C
  • 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
  • Functions in C
  • C - Functions
  • C - Main Function
  • 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
  • Scope Rules in C
  • C - Scope Rules
  • C - Static Variables
  • C - Global Variables
  • Arrays in C
  • C - Properties of Array
  • C - Multi-Dimensional Arrays
  • C - Passing Arrays to Function
  • C - Return Array from Function
  • C - Variable Length Arrays
  • Pointers in C
  • 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
  • Strings in C
  • C - Strings
  • C - Array of Strings
  • C - Special Characters
  • C Structures and Unions
  • 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 - Structure Padding and Packing
  • C - Nested Structures
  • C - Anonymous Structure and Union
  • C - Bit Fields
  • C - Typedef
  • File Handling in C
  • C - Input & Output
  • C - File I/O (File Handling)
  • C Preprocessors
  • C - Preprocessors
  • C - Pragmas
  • C - Preprocessor Operators
  • C - Header Files
  • Memory Management in C
  • C - Memory Management
  • C - Memory Address
  • C - Storage Classes
  • Miscellaneous Topics
  • C - Error Handling
  • C - Variable Arguments
  • C - Command Execution
  • C - Math Functions
  • C - Static Keyword
  • C - Random Number Generation
  • C - Command Line Arguments
  • C Programming Resources
  • C - Questions & Answers
  • C - Quick Guide
  • C - Cheat Sheet
  • 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 −

Next: Execution Control Expressions , Previous: Arithmetic , Up: Top   [ Contents ][ Index ]

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 . A simple assignment looks like

We say it assigns the value of the expression value-to-store to the location lvalue , or that it stores value-to-store there. You can think of the “l” in “lvalue” as standing for “left,” since that’s what you put on the left side of the assignment operator.

However, that’s not the only way to use an lvalue, and not all lvalues can be assigned to. To use the lvalue in the left side of an assignment, it has to be modifiable . In C, that means it was not declared with the type qualifier const (see const ).

The value of the assignment expression is that of lvalue after the new value is stored in it. This means you can use an assignment inside other expressions. Assignment operators are right-associative so that

is equivalent to

This is the only useful way for them to associate; the other way,

would be invalid since an assignment expression such as x = y is not valid as an lvalue.

Warning: Write parentheses around an assignment if you nest it inside another expression, unless that is a conditional expression, or comma-separated series, or another assignment.

  The basics of storing a value.
  Expressions into which a value can be stored.
  Shorthand for changing an lvalue’s contents.
  Shorthand for incrementing and decrementing an lvalue’s contents.
  Accessing then incrementing or decrementing.
  How to avoid ambiguity.
  Write assignments as separate statements.

Learn to Code, Prepare for Interviews, and Get Hired

01 Career Opportunities

  • Top 50 Mostly Asked C Interview Questions and Answers

02 Beginner

  • Understanding do...while loop in C
  • If...else statement in C Programming
  • If Statement in C
  • Understanding realloc() function in C
  • Understanding While loop in C
  • Why C is called middle level language?
  • Arithmetic Operators in C Programming
  • Relational Operators in C Programming

C Programming Assignment Operators

  • Logical Operators in C Programming
  • Understanding for loop in C
  • if else if statements in C Programming
  • 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

  • Getting Started with Data Structures in C
  • Constants in C language
  • 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 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

Generative AI For Software Developers Jul 14 SAT, SUN Filling Fast
Angular Certification Course Jul 14 SAT, SUN Filling Fast
ASP.NET Core Certification Training Jul 15 MON, WED, FRI Filling Fast
Advanced Full-Stack .NET Developer Certification Training Jul 15 MON, WED, FRI Filling Fast
Azure Master Class Jul 20 SAT, SUN Filling Fast
Azure Developer Certification Training Jul 21 SAT, SUN Filling Fast
Advanced Full-Stack .NET Developer Certification Training Jul 28 SAT, SUN Filling Fast
ASP.NET Core Certification Training Jul 28 SAT, SUN Filling Fast
Software Architecture and Design Training Jul 28 SAT, SUN Filling Fast
.NET Solution Architect Certification Training Jul 28 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.

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

This browser is no longer supported.

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

C Assignment Operators

  • 6 contributors

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

assignment-expression :   conditional-expression   unary-expression assignment-operator assignment-expression

assignment-operator : one of   = *= /= %= += -= <<= >>= &= ^= |=

The assignment operators in C can both transform and assign values in a single operation. C provides the following assignment operators:

Operator Operation Performed
Simple assignment
Multiplication assignment
Division assignment
Remainder assignment
Addition assignment
Subtraction assignment
Left-shift assignment
Right-shift assignment
Bitwise-AND assignment
Bitwise-exclusive-OR assignment
Bitwise-inclusive-OR assignment

In assignment, the type of the right-hand value is converted to the type of the left-hand value, and the value is stored in the left operand after the assignment has taken place. The left operand must not be an array, a function, or a constant. The specific conversion path, which depends on the two types, is outlined in detail in Type Conversions .

  • Assignment Operators

Was this page helpful?

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

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

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

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

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


It is the operator used to assign the right side operand or variable to the left side variable.

Let's create a program to use the simple assignment operator in C.

The operator is used to add the left side operand to the left operand and then assign results to the left operand.

Let's create a program to use the Plus and assign operator in C.

The operator is used to subtract the left operand with the right operand and then assigns the result to the left operand.

Let's create a program to use the Subtract and Assign (-=) operator in C.

The operator is used to multiply the left operand with the right operand and then assign result to the left operand.

Let's create a program to use the multiply and assign operator (*=) in C.

An operator is used between the left and right operands, which divides the first number by the second number to return the result in the left operand.

Let's create a program to use the divide and assign operator (/=) in C.

An operator used between the left operand and the right operand divides the first number (n1) by the second number (n2) and returns the remainder in the left operand.

Let's create a program to use the divide and assign operator (%=) in C.





Youtube

  • Send your Feedback to [email protected]

Help Others, Please Share

facebook

Learn Latest Tutorials

Splunk tutorial

Transact-SQL

Tumblr tutorial

Reinforcement Learning

R Programming tutorial

R Programming

RxJS tutorial

React Native

Python Design Patterns

Python Design Patterns

Python Pillow tutorial

Python Pillow

Python Turtle tutorial

Python Turtle

Keras tutorial

Preparation

Aptitude

Verbal Ability

Interview Questions

Interview Questions

Company Interview Questions

Company Questions

Trending Technologies

Artificial Intelligence

Artificial Intelligence

AWS Tutorial

Cloud Computing

Hadoop tutorial

Data Science

Angular 7 Tutorial

Machine Learning

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures

DAA tutorial

Operating System

Computer Network tutorial

Computer Network

Compiler Design tutorial

Compiler Design

Computer Organization and Architecture

Computer Organization

Discrete Mathematics Tutorial

Discrete Mathematics

Ethical Hacking

Ethical Hacking

Computer Graphics Tutorial

Computer Graphics

Software Engineering

Software Engineering

html tutorial

Web Technology

Cyber Security tutorial

Cyber Security

Automata Tutorial

C Programming

C++ tutorial

Control System

Data Mining Tutorial

Data Mining

Data Warehouse Tutorial

Data Warehouse

RSS Feed

C Functions

C structures, c reference, c operators.

Operators are used to perform operations on variables and values.

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

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

C divides the operators into the following groups:

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

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

Operator Name Description Example Try it
+ Addition Adds together two values x + y
- Subtraction Subtracts one value from another x - y
* Multiplication Multiplies two values x * y
/ Division Divides one value by another x / y
% Modulus Returns the division remainder x % y
++ Increment Increases the value of a variable by 1 ++x
-- Decrement Decreases the value of a variable by 1 --x

Assignment Operators

Assignment operators are used to assign values to variables.

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

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

A list of all assignment operators:

Operator Example Same As Try it
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/= x /= 3 x = x / 3
%= x %= 3 x = x % 3
&= x &= 3 x = x & 3
|= x |= 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

Comparison Operators

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

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

Comparison operators are used to compare two values.

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

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

A list of all comparison operators:

Operator Name Example Description Try it
== Equal to x == y Returns 1 if the values are equal
!= Not equal x != y Returns 1 if the values are not equal
> Greater than x > y Returns 1 if the first value is greater than the second value
< Less than x < y Returns 1 if the first value is less than the second value
>= Greater than or equal to x >= y Returns 1 if the first value is greater than, or equal to, the second value
<= Less than or equal to x <= y Returns 1 if the first value is less than, or equal to, the second value

Logical Operators

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

Logical operators are used to determine the logic between variables or values, by combining multiple conditions:

Operator Name Example Description Try it
&&  AND x < 5 &&  x < 10 Returns 1 if both statements are true
||  OR x < 5 || x < 4 Returns 1 if one of the statements is true
! NOT !(x < 5 && x < 10) Reverse the result, returns 0 if the result is 1

C Exercises

Test yourself with exercises.

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

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

What exactly are C++ definitions, declarations and assignments?

I tend to use the words define, declare and assign interchangeably but this seems to cause offense to some people. Is this justified? Should I only use the word declare for the first time I assign to a variable? Or is there more to it than that?

  • variable-assignment
  • terminology

Brian Tompsett - 汤莱恩's user avatar

8 Answers 8

A definition is where a value or function is described, i.e. the compiler or programmer is told precisely what it is, e.g.

A declaration tells the compiler, or programmer that the function or variable exists. e.g.

An assignment is when a variable has its value set, usually with the = operator. e.g.

jheriko's user avatar

  • 3 Actually I would consider "int var;" to be definition, "int var = 5;" is a combined def/ass. Basically, in C, definition is anything that creates space for an object. I'll upvote anyway, maybe you'll change the answer, maybe not, but it's the best to date. –  paxdiablo Commented Mar 23, 2009 at 1:09

Define and declare are similar but assign is very different.

Here I am declaring (or defining) a variable:

Here I am assigning a value to that variable:

Here I am doing both in one statement:

Not all languages support declaration and assignment in one statement:

Some languages require that you assign a value to a variable upon declaration. This requirement allows the compiler or interpreter of the language to infer a type for the variable:

Andrew Hare's user avatar

  • I'll split a hair -- Python has no "declaration" of any kind. Classes and functions are "defined", variables are created when they assigned. You don't really "declare" variables, since they're just names assigned to objects. –  S.Lott Commented Mar 23, 2009 at 0:58
  • That is a good point - from one pedant to another I appreciate the distinction :) –  Andrew Hare Commented Mar 23, 2009 at 1:02
  • More nitpicking: Python does not really do any type inference, it's dynamically typed. Type inference is only required when the variable has a type. This is valid Python and illustrates the effects of my point: x = 5 ; x = "str" –  Magnus Hoff Commented Mar 23, 2009 at 13:24
  • I suggest either using a different language as an example (Haskell or C# with var), or just remove the "inference"-sentence. Anyway, this is just nitpicking :) –  Magnus Hoff Commented Mar 23, 2009 at 13:24
  • 2 -1 for being the accepted answer yet being wrong: declare and define are not at all similar (even if in some languages the distinction is not made). See jheriko's answer below. –  Ian Goldby Commented Nov 4, 2011 at 15:05

It is important to use the correct terminology, otherwise people will not know what you are talking about, or incorrectly assume that you don't know what you are talking about.

1800 INFORMATION's user avatar

These terms often have precise meanings in the standards for various languages. When that is the case they should not be conflated.

In c for instance:

a function may be defined only once (when you say what it does), but it may also be declared before that (when you say what arguments it takes and what type it returns).

likewise a variable is declared when you say what type it is, and this happens only once for each scope. But you may assign a value repeatedly. (Some languages also differentiate between initialization (giving a variable a value at declaration time) and assignment (changing the value later).)

dmckee --- ex-moderator kitten's user avatar

General Role: Definition = declaration + reserved space.

Definition, declaration, and assignment have two cases:

  • for Variables.
  • for Functions.

For Variables :

-- Definition: To tell the compiler to reserve memory for the variable.

-- Declaration: To tell the compiler that the variable defined in somewhere else.

-- Assignment: To tell the compiler to put the value in the variable.

For Functions :

-- Definition:

-- Declaration: It is just the prototype of the function.

Amr Tarek Abdelghafar's user avatar

The differences can seem subtle, but they are important. Not every language makes the same distinctions, but in C++ a variable declaration makes the type and name of the variable known to the compiler

A variable definition allocates storage and specifies an initial value for the variable.

You can combine a variable declaration and definition into one statement, as is commonly done.

Declaring a variable inside a function will also set aside memory for the variable, so the following code implicitly defines variable a as a part of its declaration.

Since variable a is automatically defined by the compiler, it will contain whatever value was in the memory location that was allocated for it. This is why it is not safe to use automatic variables until you've explicitly assigned a known value to them.

An assignment takes place any time you change the value of a variable in your program.

A function declaration , similar to the variable declaration, makes the function signature known to the compiler. This allows you to call a function in your source code before it is defined without causing a compiler error.

A function definition specifies the return type, name, parameter list, and instructions for a function. The first three of these elements must match the function declaration. A function must only be defined once in a given program.

You can combine the function decalartion and definition into one, but you must do so before the function is called anywhere in your program.

Bill the Lizard's user avatar

  • I thought a variable declaration assigned storage space. You just get garbage in that space unless you also provide an initialisation, or until you assign a new value. You can only initialise a variable whilst declaring it. –  Artelius Commented Mar 23, 2009 at 1:44
  • @Artelius: In most cases declaration includes an implicit definition by the compiler, which makes it appear that declaration assigns storage space. I made a (hopefully) clarifying addition to include this in my answer. Thanks for pointing it out. –  Bill the Lizard Commented Mar 23, 2009 at 13:50
  • I voted this answer up as it is correct as I've learned it. If not, I'd really like to know why. The answers above have declaration and definition backwards. –  lakeweb Commented Jan 29, 2017 at 17:31
  • i = 1 is an assignment, not a definition. To be a definition (e.g. of a previously declared extern variable in its defining translation unit), it would need the type (and the assignment component is optional). –  underscore_d Commented Jun 29, 2017 at 16:17

It might depend on the language, as has been said. I think it really depends on whether the words are used for things like classes. For most of the data types discussed here, the question might not have much relevance. In C++ (see c++ - What is the difference between a definition and a declaration? ), a class or struct always has precisely one definition but can be declared zero or more times. A class cannot be declared without a definition. So "declared" might be synonymous with "used".

In most languages, simple types such as integers do not need definitions in the manner that classes do.

Community's user avatar

The correct answer depends on which language you're talking about. Computer languages often have specific terminology, either because of the language specification or the community grown up around the language. COBOL, back when I used it, had a much different terminology than more mainstream languages (in the sense of languages closer to the mainstream of language development, not mainstream business). Forth developed some strange terminology.

If you know English, you can usually get a good idea as to what a word means from its normal meaning, but never count on it too much. The same is true with specific words across languages or language communities.

David Thornley's user avatar

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • An adjective for something peaceful but sad?
  • What does this “Imo” sign mean?
  • In the travel industry, why is the "business" term coined in for luxury or premium services?
  • How can I write a std::apply on a std::expected?
  • Are there any reasons I shouldn't remove this odd nook from a basement room?
  • What side-effects, if any, are okay when importing a python module?
  • Why do "dual frequency" or low frequency switching regulators exist when higher frequency is better?
  • Using grout that had hardened in the bag
  • Of "ils" and "elles", which pronoun is, grammatically speaking, used to refer to a group with an overwhelming female majority?
  • Reading strategies
  • The meaning of "tarmac ticket"
  • Does the oven temperature for a lasagna really matter?
  • Linux disk space running full
  • Any philosophical works that explicitly address the heat death of the Universe and its philosophical implications?
  • Why does Macbeth well deserve his name?
  • How to choose between 3/4 and 6/8 time?
  • Draw a Regular Reuleaux Polygon
  • Story about Jesus being kidnapped by the church
  • Using `Scaled` in an `Epilog` to `Plot`
  • Continued calibration of atomic clocks
  • What events between India and Myanmar relations happened in 1962 that led Myanmar to support separatism in India?
  • How does anyone know for sure who the Prime Minister is?
  • Why were early (personal) computer connectors so bulky?
  • Implementation of Euler-Maruyama numerical solver

assignment statement in c

COMMENTS

  1. What are Assignment Statement: Definition, 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.

  2. 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: a = 10; b = 20; ch = 'y'; 2. "+=": This operator is combination of '+' and '=' operators. This operator first adds the current ...

  3. Assignment Statement in C Programming Language

    Learn how to assign values to variables using the assignment operator in C. See the syntax, examples and types of expressions that can be used on the right hand side of the assignment statement.

  4. Assignment Operators in C

    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.

  5. Assignment Expressions (GNU C Language Manual)

    An assignment in C is an expression because it has a value; we call it an assignment expression. A simple assignment looks like. lvalue = value-to-store. We say it assigns the value of the expression value-to-store to the location lvalue, or that it stores value-to-store there. You can think of the "l" in "lvalue" as standing for ...

  6. c

    An assignment expression has the value of the left operand after the assignment. It's to allow things like this: a = b = c; (although there's some debate as to whether code like that is a good thing or not.) Incidentally, this behaviour is replicated in Java (and I would bet that it's the same in C# too). edited Feb 20, 2017 at 8:59.

  7. C Programming Assignment Operators

    Assignment Operators in C are used to assign values to the variables. 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 "=". In this C tutorial, we'll understand the types of C programming assignment operators with examples.

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

  9. Assignment Operators in C with Examples

    Assignment operators are used to assign value to a variable. The left side of an assignment operator is a variable and on the right side, there is a value, variable, or an expression. It computes the outcome of the right side and assign the output to the variable present on the left side. C supports following Assignment operators:

  10. PDF The assignment statement

    The assignment statement. The assignment statement is used to store a value in a variable. As in most programming languages these days, the assignment statement has the form: <variable>= <expression>; For example, once we have an int variable j, we can assign it the value of expression 4 + 6: int j; j= 4+6; As a convention, we always place a ...

  11. Assignment operators

    Move assignment 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 move assignment operator . (since C++11)

  12. C Assignment Operators

    The assignment operators in C can both transform and assign values in a single operation. C provides the following assignment operators: | =. In assignment, the type of the right-hand value is converted to the type of the left-hand value, and the value is stored in the left operand after the assignment has taken place.

  13. What is the result of an assignment expression in C?

    2 Assignment returns with the assigned value. In case c=10 is 10. Since 10!=0, in c it means also true so this is an infinite loop.

  14. Assignment statements in C/C++

    Assignment statement in C/C++: The assignment statement is used to assign a value (computed from an expression) to a variable Syntax:

  15. Assignment statements in C/C++

    Assignment statement in C/C++: The assignment statement is used to assign a value (computed from an expression) to a variable Syntax: Variable = Expression ; Notice The expression (value) has a type , and The variable has a type , and The variable can have a different type than the value assigned !!!

  16. Difference between declaration statement and assignment statement in C

    15. Declaration: Assignment: Declaration and assignment in one statement: Declaration says, "I'm going to use a variable named " a " to store an integer value." Assignment says, "Put the value 3 into the variable a ." (As @delnan points out, my last example is technically initialization, since you're specifying what value the variable starts ...

  17. Assignment statements in C Language Skill UP

    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.

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

  19. Assignment Operator in C

    Assignment Operator in C is a tutorial that explains how to use the operator that assigns a value to a variable in C programming language. It covers the syntax, types, and examples of assignment operator in C. It also provides a quiz and interview questions to test your knowledge. Learn assignment operator in C from javatpoint, a leading online platform for learning various technologies.

  20. C Operators

    Try it Yourself ». C divides the operators into the following groups: Arithmetic operators. Assignment operators. Comparison operators. Logical operators.

  21. C assignments in an 'if' statement

    Your code is assigning data[q] to s and then returns s to the if statement. In the case when s is not equal to 0 your code returns s otherwise it goes to the next instruction.

  22. PDF Chapter 7

    Assignment Statements The general syntax <target_var> <assign_operator> <expression> The assignment operator = Fortran, BASIC, the C-based languages := Ada = can be bad when it is overloaded for the relational operator for equality (that's why the C-based languages use == as the relational operator) Assignment Statements: Conditional Targets

  23. What exactly are C++ definitions, declarations and assignments?

    A declaration tells the compiler, or programmer that the function or variable exists. e.g. An assignment is when a variable has its value set, usually with the = operator. e.g. Actually I would consider "int var;" to be definition, "int var = 5;" is a combined def/ass.