C Functions

C structures, c reference, c declare multiple variables, declare multiple variables.

To declare more than one variable of the same type, use a comma-separated list:

You can also assign the same value to multiple variables of the same type:

C Exercises

Test yourself with exercises.

Fill in the missing parts to create three variables of the same type, using a comma-separated list :

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.

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

Assignment Operators in C

multiple assignments 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:

Similar Reads

  • C-Operators
  • cpp-operator

Please Login to comment...

  • Free Music Recording Software in 2024: Top Picks for Windows, Mac, and Linux
  • Best Free Music Maker Software in 2024
  • What is Quantum AI? The Future of Computing and Artificial Intelligence Explained
  • Noel Tata: Ratan Tata's Brother Named as a new Chairman of Tata Trusts
  • GeeksforGeeks Practice - Leading Online Coding Platform

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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: Conditional Expression , Previous: Logicals and Comparison , Up: Execution Control Expressions   [ Contents ][ Index ]

8.3 Logical Operators and Assignments

There are cases where assignments nested inside the condition can actually make a program easier to read. Here is an example using a hypothetical type list which represents a list; it tests whether the list has at least two links, using hypothetical functions, nonempty which is true if the argument is a nonempty list, and list_next which advances from one list link to the next. We assume that a list is never a null pointer, so that the assignment expressions are always “true.”

Here we take advantage of the ‘ && ’ operator to avoid executing the rest of the code if a call to nonempty returns “false.” The only natural place to put the assignments is among those calls.

It would be possible to rewrite this as several statements, but that could make it much more cumbersome. On the other hand, when the test is even more complex than this one, splitting it into multiple statements might be necessary for clarity.

If an empty list is a null pointer, we can dispense with calling nonempty :

multiple assignments c

  • Table of Contents
  • Course Home
  • Assignments
  • Peer Instruction (Instructor)
  • Peer Instruction (Student)
  • Change Course
  • Instructor's Page
  • Progress Page
  • Edit Profile
  • Change Password
  • Scratch ActiveCode
  • Scratch Activecode
  • Instructors Guide
  • About Runestone
  • Report A Problem
  • Coding Practice
  • Activecode Exercises
  • Mixed Up Code Practice
  • 6.1 Multiple assignment
  • 6.2 Iteration
  • 6.3 The while statement
  • 6.5 Two-dimensional tables
  • 6.6 Encapsulation and generalization
  • 6.7 Functions
  • 6.8 More encapsulation
  • 6.9 Local variables
  • 6.10 More generalization
  • 6.11 Glossary
  • 6.12 Multiple Choice Exercises
  • 6.13 Mixed-Up Code Exercises
  • 6.14 Coding Practice
  • 6. Iteration" data-toggle="tooltip">
  • 6.2. Iteration' data-toggle="tooltip" >

Before you keep reading...

Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

6.1. Multiple assignment ¶

I haven’t said much about it, but it is legal in C++ to make more than one assignment to the same variable. The effect of the second assignment is to replace the old value of the variable with a new value.

The active code below reassigns fred from 5 to 7 and prints both values out.

The output of this program is 57 , because the first time we print fred his value is 5, and the second time his value is 7.

The active code below reassigns fred from 5 to 7 without printing out the initial value.

However, if we do not print fred the first time, the output is only 7 because the value of fred is just 7 when it is printed.

This kind of multiple assignment is the reason I described variables as a container for values. When you assign a value to a variable, you change the contents of the container, as shown in the figure:

image

When there are multiple assignments to a variable, it is especially important to distinguish between an assignment statement and a statement of equality. Because C++ uses the = symbol for assignment, it is tempting to interpret a statement like a = b as a statement of equality. It is not!

An assignment statement uses a single = symbol. For example, x = 3 assigns the value of 3 to the variable x . On the other hand, an equality statement uses two = symbols. For example, x == 3 is a boolean that evaluates to true if x is equal to 3 and evaluates to false otherwise.

First of all, equality is commutative, and assignment is not. For example, in mathematics if \(a = 7\) then \(7 = a\) . But in C++ the statement a = 7; is legal, and 7 = a; is not.

Furthermore, in mathematics, a statement of equality is true for all time. If \(a = b\) now, then \(a\) will always equal \(b\) . In C++, an assignment statement can make two variables equal, but they don’t have to stay that way!

The third line changes the value of a but it does not change the value of b , and so they are no longer equal. In many programming languages an alternate symbol is used for assignment, such as <- or := , in order to avoid confusion.

Although multiple assignment is frequently useful, you should use it with caution. If the values of variables are changing constantly in different parts of the program, it can make the code difficult to read and debug.

  • Checking if a is equal to b
  • Assigning a to the value of b
  • Setting the value of a to 4

Q-4: What will print?

  • There are no spaces between the numbers.
  • Remember, in C++ spaces must be printed.
  • Carefully look at the values being assigned.

Q-5: What is the correct output?

  • Remember that printing a boolean results in either 0 or 1.
  • Is x equal to y?
  • x is equal to y, so the output is 1.

IncludeHelp_logo

  • Data Structure
  • Coding Problems
  • C Interview Programs
  • C++ Aptitude
  • Java Aptitude
  • C# Aptitude
  • PHP Aptitude
  • Linux Aptitude
  • DBMS Aptitude
  • Networking Aptitude
  • AI Aptitude
  • MIS Executive
  • Web Technologie MCQs
  • CS Subjects MCQs
  • Databases MCQs
  • Programming MCQs
  • Testing Software MCQs
  • Digital Mktg Subjects MCQs
  • Cloud Computing S/W MCQs
  • Engineering Subjects MCQs
  • Commerce MCQs
  • More MCQs...
  • Machine Learning/AI
  • Operating System
  • Computer Network
  • Software Engineering
  • Discrete Mathematics
  • Digital Electronics
  • Data Mining
  • Embedded Systems
  • Cryptography
  • CS Fundamental
  • More Tutorials...
  • Tech Articles
  • Code Examples
  • Programmer's Calculator
  • XML Sitemap Generator
  • Tools & Generators

IncludeHelp

  • C - Getting Started
  • C - Overview
  • C - Advantages & Disadvantages
  • C - Character Set
  • Gcc Vs. G++
  • Why We should Use C?
  • C - Basic Rules
  • C - Comments
  • C - Variable Naming Conventions
  • C - Variable Initialization
  • C - Constants
  • C - Character Constant
  • C - Octal Literals
  • C - Hexadecimal Literals
  • C - Automatic (auto) Variables
  • Local Vs. Global Variables
  • C - Access Global Variables
  • Is exit() & return Statements are Same?
  • C - Print Float Value
  • C - Print Multiple Lines Using printf()
  • C - Argument Index Specification
  • C - Value Returned by scanf()
  • C - Returned Values of printf() & scanf()
  • What do 'lvalue' & 'rvalue' Mean
  • Automatic (auto) Vs. Static Variables

C Data Types

  • C - Data Types & Operators
  • C - Basic Data Types
  • C - 'unsigned char' For Memory Optimization
  • short Vs. short int Vs. int
  • unsigned int Vs. size_t
  • C - Storage Classes Introduction
  • C - Storage Classes With Examples
  • C- Type Conversion
  • C - Type Qualifiers

C Input/Output

  • C - Read String With Spaces
  • C - Input String of Unknown Length
  • C - Disadvantages of scanf()
  • C - scanf() need '%lf' for doubles, when printf() is okay with just '%f'
  • C - Format Specifier for unsigned short int
  • C - printf() Format Specifier for bool
  • C - printf() Arguments for long
  • C - printf() Specifier for double
  • Is there a printf() converter to print in binary format?
  • C - Nested printf()
  • printf() Vs. puts()
  • printf() Vs. sprintf()
  • %d Vs. %i format Specifiers
  • C - Single Character Input & Output
  • C- Formatted Input & Output
  • C - Octal & Hex Escape Sequences
  • C - Convert Float to String
  • gets() Vs. fgets()
  • C - Input Unsigned Integer Value
  • C - Input Octal Value
  • C - Input Hex Value
  • C - Input Decimal, Octal & Hex in char Variables
  • C - Input With '%i'
  • C - Input Individual Characters
  • C - Skip characters While Reading Integers
  • C - Read Memory Address
  • C - Printing Variable's Address
  • C - printf() Examples & Variations

C Operators

  • C - Operators Precedence & Associativity
  • Operators Vs. Operands
  • C - Unary Operators
  • C - Equality Operators
  • C - Logical AND (&&) Operator
  • C - Logical OR (||) Operator
  • C - Logical NOT (!) Operator
  • C - Modulus on Negative Numbers
  • C - Expression a=b=c (Multiple Assignment) Evaluates
  • C - Expression a==b==c (Multiple Comparison) Evaluates
  • C - Complex Return Statement Using Comma Operator
  • C - Comma Operator
  • C - Bitwise Operators
  • C - Bitwise One's Compliment
  • C - Modulus of Float or Double Numbers

C Conditional Statements

  • C - If Else Statements
  • C - Switch Case
  • C - Switch Statements Features, Disadvantages
  • C - Using Range With Switch

C Control Statements

  • C - 'goto' Statement
  • C - break & continue
  • Print Numbers From 1 to N Using goto
  • C - Looping
  • C - Looping Programs
  • C - Nested Loops
  • C - Entry Controlled Vs. Exit Controlled Loops
  • C - Sentinel Vs. Counter Controlled Loops
  • C - Use for Loop as Infinite Loop
  • C - Strings in C language programming
  • C - string.h Functions
  • C - memcpy() Function
  • C - Write Your Own memcpy()
  • C - memset() Function
  • C - Write Your Own memset()

C Functions

  • C - Library & User-define Functions
  • C - Static Functions
  • C - Scope of Function Parameters
  • C - Recursion
  • C - Recursion Examples
  • More on Arrays
  • C - Properties/Characteristics of Array

C Structure and Unions

  • C Structures
  • C - Initialize a Structure in Accordance
  • C - Size of Structure With No Members
  • C -Pointer to Structure
  • C - Nested Structure Initialization
  • C - Nested Structure With Examples
  • C - Size of Structure
  • C - Copy Complete Structure in Byte Array
  • C - Pointer to Union
  • C - Pointers
  • C - Pointer Rules
  • C - Pointers Declarations
  • C - Pointer Address Operators
  • C - Accessing Variable Using Pointer
  • C - Address of (&) & Dereference (*) Operators
  • C - NULL Pointer
  • C - Pointers as Argument
  • C - Pointer Arithmetic
  • C - Pointer to an Array
  • C - Evaluation of Statement '*ptr++'
  • C - Pointer & Non-pointer Variables Declarations Together
  • C - Pointer to an Array of Integers
  • C - Pointer to Pointer
  • C - void Pointer as Function Argument
  • char s[] Vs. char *s
  • C - Copying Integer Value to Char Buffer & Vice Versa
  • C - Call by Reference Vs. Call by Value
  • C - Typedef Function Pointer

C Preprocessor Directives

  • Recommendation for defining a macro in C language
  • Macro expansion directives (#define, #undef) in C language
  • Complex macro with arguments (function like macro) in C language
  • C language #ifdef, #else, #endif Pre-processor with Example
  • C language #if, #elif, #else, #endif Pre-processor with Example
  • Parameterized Macro - we cannot use space after the Macro Name
  • Stringizing Operator (#) in C
  • Token Pasting Directive Operator (##) in C

C Command-line Arguments

  • C language Command Line Arguments

C File Handlings

  • C - Basics of File Handling
  • C - File Handling Programs
  • C - Graphics Modes
  • C - Using Colors in Text Mode
  • C - More on Graphics Modes
  • C - OUTTEXTXY() & SETTEXTSTYLE() Functions
  • C - Draw Circle & Rectangle
  • C - graphics.h Functions
  • C - More Graphics-related Interesting Functions

C Advance Topics

  • C - Process Identification (pid_t)
  • C - getpid() & getppid()
  • C - Rrules For Writing C/C++ Program
  • C - Tips For Embedded Development
  • C - Optimization Techniques
  • C Vs. Embedded C
  • C- File Management System Calls
  • C/C++ Multithreading
  • C/C++ - Sum of Array Using Multithreading

C Tips and Tricks

  • C - Copy Two Bytes Int. to Byte Buffer
  • C - Is Pre-increment Faster than Post-increment?
  • C - Create Delay Function
  • Why should We use 'f' With Float Literal in C?
  • C - Replacing a Part of String
  • C- Comparing Number of Characters of Two Strings
  • C - Safest Way to Check Value Using ==
  • C- Check EVEN or ODD W/O % Operator
  • C- Use Single Byte to Store 8 Values
  • C- Funny Trick to Use C++ in C
  • C - Trick to Print Maximum Value of an unsigned int
  • C - Print Maximum Value of an unsigned int using One's Compliment (~) Operator in C
  • Why we should use switch instead of if else?
  • How to initialize array elements with hexadecimal values in C?
  • How should we declare/define a pointer variable?

C Important Topics

  • C - Working With Hexadecimal
  • C - Working With octal
  • C - Convert ASCII String (char[]) to BYTE Array
  • C - Convert ASCII String (char[]) to Octal String
  • C - Convert ASCII String (char[]) to Hex String
  • C - Assign Binary Calue in a Variable Directly
  • C - Check Particular Bit is SET or Not
  • C- Set, Clear, & Toggle a Bit
  • C - Value of 'EOF'
  • C - Print printf("Hello world."); Using printf()
  • C - Print Text in New Line w/O Using '\n'
  • C - Return 0 From int main()
  • 'Super Loop' Architecture for Embedded C
  • C - Executing System Commands
  • C - Infix To Postfix Conversion Using Stack
  • C - Evaluation of Postfix Expressions Using Stack
  • C - Polynomial Addition Using Structure
  • C - conio.h Functions
  • SQLite with C language
  • C - SQL Table Creation, Insertion
  • C - Aptitude Questions
  • C - Interview Questions
  • C - Find Output Programs

Home » C programming language

How expression a=b=c (Multiple Assignment) evaluates in C programming?

Since C language does not support chaining assignment like a=b=c ; each assignment operator ( = ) operates on two operands only. Then how expression a=b=c evaluates?

According to operators associativity assignment operator ( = ) operates from right to left, that means associativity of assignment operator ( = ) is right to left.

Expression a=b=c is actually a=(b=c) , see how expression a=(b=c) evaluates?

  • Value of variable c will be assigned into variable b first.
  • Then value of variable b will be assigned into variable a .

Finally value of variables a and b will be same as the value of variable c .

Consider the following program

Assigning a value to multiple variables of same type

By using such kind of expression we can easily assign a value to multiple variables of same data type, for example - if we want to assign 0 to integer variables a , b , c and d ; we can do it by following expression:

Related Tutorials

  • Precedence and associativity of Arithmetic Operators
  • Difference b/w operators and operands in C
  • Unary Operators in C with Examples
  • Equality Operators in C,C++
  • Logical AND (&&) operator with example
  • Logical OR (||) operator with example
  • Logical NOT (!) operator with example
  • Modulus on negative numbers in C language
  • How expression a==b==c (Multiple Comparison) evaluates in C programming?
  • Complex return statement using comma operator in c programming language
  • Explain comma operator with an example
  • Bitwise Operators and their working
  • Bitwise One's Compliment (Bitwise NOT Operator) in C
  • Modulus of two float or double numbers in C language
  • Switch Case Tutorial, Syntax, Examples and Rules in C language
  • Switch Statements (features, disadvantages and difference with if else)
  • Using range with switch case statement
  • 'goto' Statement in C language
  • Use of break and continue within the loop in c
  • Print numbers from 1 to N using goto statement
  • Looping Tutorial in C programming
  • Nested Loops in C programming language
  • How to use for loop as infinite loop in C?

Comments and Discussions!

Load comments ↻

  • Marketing MCQs
  • Blockchain MCQs
  • Artificial Intelligence MCQs
  • Data Analytics & Visualization MCQs
  • Python MCQs
  • C++ Programs
  • Python Programs
  • Java Programs
  • D.S. Programs
  • Golang Programs
  • C# Programs
  • JavaScript Examples
  • jQuery Examples
  • CSS Examples
  • C++ Tutorial
  • Python Tutorial
  • ML/AI Tutorial
  • MIS Tutorial
  • Software Engineering Tutorial
  • Scala Tutorial
  • Privacy policy
  • Certificates
  • Content Writers of the Month

Copyright © 2024 www.includehelp.com. All rights reserved.

cppreference.com

Assignment operators.

(C11)
Miscellaneous
General
(C11)
(C99)

Assignment and compound assignment operators are binary operators that modify the variable to their left using the value to their right.

Operator Operator name Example Description Equivalent of
= basic assignment a = b becomes equal to
+= addition assignment a += b becomes equal to the addition of and a = a + b
-= subtraction assignment a -= b becomes equal to the subtraction of from a = a - b
*= multiplication assignment a *= b becomes equal to the product of and a = a * b
/= division assignment a /= b becomes equal to the division of by a = a / b
%= modulo assignment a %= b becomes equal to the remainder of divided by a = a % b
&= bitwise AND assignment a &= b becomes equal to the bitwise AND of and a = a & b
|= bitwise OR assignment a |= b becomes equal to the bitwise OR of and a = a | b
^= bitwise XOR assignment a ^= b becomes equal to the bitwise XOR of and a = a ^ b
<<= bitwise left shift assignment a <<= b becomes equal to left shifted by a = a << b
>>= bitwise right shift assignment a >>= b becomes equal to right shifted by a = a >> b
Simple assignment Notes Compound assignment References See Also See also

[ edit ] Simple assignment

The simple assignment operator expressions have the form

lhs rhs
lhs - expression of any complete object type
rhs - expression of any type to lhs or with lhs

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-lvalue (so that expressions such as ( a = b ) = c are invalid).

rhs and lhs must satisfy one of the following:

  • both lhs and rhs have compatible struct or union type, or..
  • rhs must be implicitly convertible to lhs , which implies
  • both lhs and rhs have arithmetic types , in which case lhs may be volatile -qualified or atomic (since C11)
  • both lhs and rhs have pointer to compatible (ignoring qualifiers) types, or one of the pointers is a pointer to void, and the conversion would not add qualifiers to the pointed-to type. lhs may be volatile or restrict (since C99) -qualified or atomic (since C11) .
  • lhs is a (possibly qualified or atomic (since C11) ) pointer and rhs is a null pointer constant such as NULL or a nullptr_t value (since C23)
has type (possibly qualified or atomic(since C11)) _Bool and rhs is a pointer or a value(since C23) (since C99)
has type (possibly qualified or atomic) and rhs has type (since C23)

[ edit ] Notes

If rhs and lhs overlap in memory (e.g. they are members of the same union), the behavior is undefined unless the overlap is exact and the types are compatible .

Although arrays are not assignable, an array wrapped in a struct is assignable to another object of the same (or compatible) struct type.

The side effect of updating lhs is sequenced after the value computations, but not the side effects of lhs and rhs themselves and the evaluations of the operands are, as usual, unsequenced relative to each other (so the expressions such as i = ++ i ; are undefined)

Assignment strips extra range and precision from floating-point expressions (see FLT_EVAL_METHOD ).

In C++, assignment operators are lvalue expressions, not so in C.

[ edit ] Compound assignment

The compound assignment operator expressions have the form

lhs op rhs
op - one of *=, /= %=, += -=, <<=, >>=, &=, ^=, |=
lhs, rhs - expressions with (where lhs may be qualified or atomic), except when op is += or -=, which also accept pointer types with the same restrictions as + and -

The expression lhs @= rhs is exactly the same as lhs = lhs @ ( rhs ) , except that lhs is evaluated only once.

If lhs has type, the operation behaves as a single atomic read-modify-write operation with memory order .

For integer atomic types, the compound assignment @= is equivalent to:

addr = &lhs; T2 val = rhs; T1 old = *addr; T1 new; do { new = old @ val } while (! (addr, &old, new);
(since C11)

[ edit ] References

  • C17 standard (ISO/IEC 9899:2018):
  • 6.5.16 Assignment operators (p: 72-73)
  • C11 standard (ISO/IEC 9899:2011):
  • 6.5.16 Assignment operators (p: 101-104)
  • C99 standard (ISO/IEC 9899:1999):
  • 6.5.16 Assignment operators (p: 91-93)
  • C89/C90 standard (ISO/IEC 9899:1990):
  • 3.3.16 Assignment operators

[ edit ] See Also

Operator precedence

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->b
a.b

a(...)
a, b
(type) a
a ? b : c
sizeof


_Alignof
(since C11)

[ edit ] See also

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 19 August 2022, at 09:36.
  • Privacy policy
  • About cppreference.com
  • Disclaimers

Powered by MediaWiki

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively.

The best way to learn C programming is by practicing examples. The page contains examples on basic concepts of C programming. You are advised to take the references from these examples and try them on your own.

All the programs on this page are tested and should work on all platforms.

Want to learn C Programming by writing code yourself? Enroll in our Interactive C Course for FREE.

  • C Program to Create Pyramids and Patterns
  • C Program to Check Prime Number
  • C Program to Check Palindrome Number
  • C Program to Print Hello World
  • C "Hello, World!" Program
  • C Program to Print an Integer (Entered by the User)
  • C Program to Add Two Integers
  • C Program to Multiply Two Floating-Point Numbers
  • C Program to Find ASCII Value of a Character
  • C Program to Compute Quotient and Remainder
  • C Program to Find the Size of int, float, double and char
  • C Program to Demonstrate the Working of Keyword long
  • C Program to Swap Two Numbers
  • C Program to Check Whether a Number is Even or Odd
  • C Program to Check Whether a Character is a Vowel or Consonant
  • C Program to Find the Largest Number Among Three Numbers
  • C Program to Find the Roots of a Quadratic Equation
  • C Program to Check Leap Year
  • C Program to Check Whether a Number is Positive or Negative
  • C Program to Check Whether a Character is an Alphabet or not
  • C Program to Calculate the Sum of Natural Numbers
  • C Program to Find Factorial of a Number
  • C Program to Generate Multiplication Table
  • C Program to Display Fibonacci Sequence
  • C Program to Find GCD of two Numbers
  • C Program to Find LCM of two Numbers
  • C Program to Display Characters from A to Z Using Loop
  • C Program to Count Number of Digits in an Integer
  • C Program to Reverse a Number
  • C Program to Calculate the Power of a Number
  • C Program to Check Whether a Number is Palindrome or Not
  • C Program to Check Whether a Number is Prime or Not
  • C Program to Display Prime Numbers Between Two Intervals
  • C Program to Check Armstrong Number
  • C Program to Display Armstrong Number Between Two Intervals
  • C Program to Display Factors of a Number
  • C Program to Make a Simple Calculator Using switch...case
  • C Program to Display Prime Numbers Between Intervals Using Function
  • C Program to Check Prime or Armstrong Number Using User-defined Function
  • C Program to Check Whether a Number can be Expressed as Sum of Two Prime Numbers
  • C Program to Find the Sum of Natural Numbers using Recursion
  • C Program to Find Factorial of a Number Using Recursion
  • C Program to Find G.C.D Using Recursion
  • C Program to Convert Binary Number to Decimal and vice-versa
  • C Program to Convert Octal Number to Decimal and vice-versa
  • C Program to Convert Binary Number to Octal and vice-versa
  • C Program to Reverse a Sentence Using Recursion
  • C program to calculate the power using recursion
  • C Program to Calculate Average Using Arrays
  • C Program to Find Largest Element in an Array
  • C Program to Calculate Standard Deviation
  • C Program to Add Two Matrices Using Multi-dimensional Arrays
  • C Program to Multiply Two Matrices Using Multi-dimensional Arrays
  • C Program to Find Transpose of a Matrix
  • C Program to Multiply two Matrices by Passing Matrix to a Function
  • C Program to Access Array Elements Using Pointer
  • C Program Swap Numbers in Cyclic Order Using Call by Reference
  • C Program to Find Largest Number Using Dynamic Memory Allocation
  • C Program to Find the Frequency of Characters in a String
  • C Program to Count the Number of Vowels, Consonants and so on
  • C Program to Remove all Characters in a String Except Alphabets
  • C Program to Find the Length of a String
  • C Program to Concatenate Two Strings
  • C Program to Copy String Without Using strcpy()
  • C Program to Sort Elements in Lexicographical Order (Dictionary Order)
  • C Program to Store Information of a Student Using Structure
  • C Program to Add Two Distances (in inch-feet system) using Structures
  • C Program to Add Two Complex Numbers by Passing Structure to a Function
  • C Program to Calculate Difference Between Two Time Periods
  • C Program to Store Information of Students Using Structure
  • C Program to Store Data in Structures Dynamically
  • C Program to Write a Sentence to a File
  • C Program to Read the First Line From a File
  • C Program to Display its own Source Code as Output
  • C Program to Print Pyramids and Patterns

multiple assignments c

  • Table of Contents
  • Scratch ActiveCode
  • Scratch Activecode
  • 5. Iteration" data-toggle="tooltip">
  • 5.2. Iteration' data-toggle="tooltip" >

5.1. Multiple assignment ¶

I haven’t said much about it, but it is legal in C++ to assign to the same variable more than once. The effect of the second assignment is to replace the old value of the variable with a new value.

The code below reassigns fred from 5 to 7 and prints both values out.

The output of this program is 57 , because the first time we print fred his value is 5, and the second time his value is 7.

The active code below reassigns fred from 5 to 7 without printing out the initial value.

However, if we do not print fred the first time, the output is only 7 because the value of fred is just 7 when it is printed.

This kind of multiple assignment is the reason I described variables as a container for values. When you assign a value to a variable, you change the contents of the existing storage location, as shown in the codelens below. Step through the code one line at a time and notice how the value assigned to fred changes even when no output is created.

Activity: CodeLens Reassigning values to fred (multiple_assignment_CL)

When there are multiple assignments to a variable, it is especially important to distinguish between an assignment statement and a statement of equality. Because C++ uses the = symbol for assignment, it is tempting to interpret a statement like a = b as a statement of equality. It is not!

An assignment statement uses a single = symbol. For example, x = 3 assigns the value of 3 to the variable x . On the other hand, an equality statement uses two = symbols. For example, x == 3 is a boolean that evaluates to true if x is equal to 3 and evaluates to false otherwise.

This is a common source of error.

First of all, equality is commutative, and assignment is not. For example, in mathematics if \(a = 7\) then \(7 = a\) . But in C++ the statement a = 7; is legal, and 7 = a; is not.

Furthermore, in mathematics, a statement of equality is true for all time. If \(a = b\) now, then \(a\) will always equal \(b\) . In C++, an assignment statement can make two variables equal, but they don’t have to stay that way!

The third line changes the value of a but it does not change the value of b , and so they are no longer equal. In many programming languages an alternate symbol is used for assignment, such as <- or := , in order to avoid confusion.

Although multiple assignment is frequently useful, you should use it with caution. If the values of variables are changing constantly in different parts of the program, it can make the code difficult to read and debug.

  • Checking if a is equal to b
  • Assigning a to the value of b
  • Setting the value of a to 4

Q-5: What will print?

  • There are no spaces between the numbers.
  • Remember, in C++ spaces must be printed.
  • Carefully look at the values being assigned.

Q-6: What is the correct output?

  • Remember that printing a boolean results in either 0 or 1.
  • Is x equal to y?
  • x is equal to y, so the output is 1.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

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

Why declare a variable in one line, and assign to it in the next?

I often see in C and C++ code the following convention:

I initially assumed that this was a habit left over from the days when you had to declare all local variables at the top of the scope. But I've learned not to dismiss so quickly the habits of veteran developers. So, is there a good reason for declaring in one line, and assigning afterwards?

Robert Harvey's user avatar

  • 15 +1 for "I've learned not to dismiss so quickly the habits of veteran developers." That's a wise lesson to learn. –  Wildcard Commented Nov 30, 2015 at 15:56

7 Answers 7

In C89 all declarations had to be be at the beginning of a scope ( { ... } ), but this requirement was dropped quickly (first with compiler extensions and later with the standard).

These examples are not the same. some_type val = something; calls the copy constructor while val = something; calls the default constructor and then the operator= function. This difference is often critical.

Some people prefer to first declare variables and later define them, in the case they are reformatting their code later with the declarations in one spot and the definition in an other.

About the pointers, some people just have the habit to initialize every pointer to NULL or nullptr , no matter what they do with that pointer.

orlp's user avatar

  • 1 Great distinction for C++, thanks. What about in plain C? –  Jonathan Sterling Commented May 7, 2011 at 20:35
  • 14 The fact that MSVC still doesn't support declarations except at the beginning of a block when it's compiling in C mode is the source of endless irritation for me. –  Michael Burr Commented May 7, 2011 at 22:03
  • 5 @Michael Burr: This is because MSVC doesn't support C99 at all. –  orlp Commented May 7, 2011 at 22:05
  • 4 "some_type val = something; calls the copy constructor": it may call the copy constructor, but the Standard allows the compiler to elide the default-construction of a tempory, copy construction of val and destruction of the temporary and directly construct val using a some_type constructor taking something as sole argument. This is a very interesting and unusual edge case in C++... it means there's a presumption about the semantic meaning of these operations. –  Tony Commented May 9, 2011 at 9:15
  • 2 @Aerovistae: for built-in types they are the same, but the same can not always be said for user-defined types. –  orlp Commented Oct 11, 2012 at 18:48

You have tagged your question C and C++ at the same time, while the answer is significantly different in these languages.

Firstly, the wording of the title of your question is incorrect (or, more precisely, irrelevant to the question itself). In both of your examples the variable is declared and defined simultaneously, in one line. The difference between your examples is that in the first one the variables are either left uninitialized or initialized with a dummy value and then it is assigned a meaningful value later. In the second example the variables are initialized right away.

Secondly, in C++ language, as @nightcracker noted in his answer these two constructs are semantically different. The first one relies on initialization while the second one - on assignment. In C++ these operations are overloadable and therefore can potentially lead to different results (although one can note that producing non-equivalent overloads of initialization and assignment is not a good idea).

In the original standard C language (C89/90) it is illegal to declare variables in the middle of the block, which is why you might see variables declared uninitialized (or initialized with dummy values) at the beginning of the block and then assigned meaningful values later, when those meaningful values become available.

In C99 language it is OK to declare variables in the middle of the block (just like in C++), which means that the first approach is only needed in some specific situations when the initializer is not known at the point of declaration. (This applies to C++ as well).

AnT stands with Russia's user avatar

  • 2 @Jonathan Sterling: I read your examples. You probably need to brush up on the standard terminology of C and C++ languages. Specifically, on the terms declaration and definition , which have specific meanings in these languages. I'll repeat it again: in both of your examples the variables are declared and defined in one line. In C/C++ the line some_type val; immediately declares and defines the variable val . This is what I meant in my answer. –  AndreyT Commented May 7, 2011 at 20:53
  • 1 I see what you mean there. You're definitely right about declare and define being rather meaningless the way I used them. I hope you accept my apologies for the poor wording, and poorly-thought-out comment. –  Jonathan Sterling Commented May 7, 2011 at 20:55
  • 1 So, if the consensus is that “declare” is the wrong word, I'd suggest that someone with a better knowledge of the standard than me edit the Wikibooks page. –  Jonathan Sterling Commented May 7, 2011 at 21:11
  • 2 In any other context declare would be the right word, but since declare is a well-defined concept , with consequences, in C and C++ you can not use it as loosely as you could in other contexts. –  orlp Commented May 7, 2011 at 21:15
  • 2 @ybungalobill: You are wrong. Declaration and definition in C/C++ is not mutually exclusive concepts. Actually, definition is just a specific form of declaration . Every definition is a declaration at the same time (with few exceptions). There are defining declarations (i.e. definitions) and non-defining declarations. Moreover, normally the therm declaration is used all the time (even if it is a definition), except for the contexts when the distinction between the two is critical. –  AndreyT Commented May 7, 2011 at 21:52

I think it's an old habit, leftover from "local declaration" times. And therefore as answer to your question: No I don't think there's a good reason. I never do it myself.

I said something about that in my answer to a question by Helium3 .

Basically, I say it's a visual aid to easily see what is changed.

Community's user avatar

The other answers are pretty good. There's some history around this in C. In C++ there's the difference between a constructor and an assignment operator.

I'm surprised no one mentions the additional point: keeping declarations separate from use of a variable can sometimes be a lot more readable.

Visually speaking, when reading code, the more mundane artifacts, such as the types and names of variables, are not what jump out at you. It's the statements that you're usually most interested in, spend most time staring at, and so there's a tendency to glance over the rest.

If I have some types, names, and assignment all going on in the same tight space, it's a bit of information overload. Further, it means that something important is going on in the space that I usually glance over.

It may seem a bit counter-intuitive to say, but this is one instance where making your source take up more vertical space can make it better. I see this as akin to why you shouldn't write jam-packed lines which do crazy amounts of pointer arithmetic and assignment in a tight vertical space -- just because the language lets you get away with such things doesn't mean you should do it all the time. :-)

asveikau's user avatar

In C, this was the standard practice because variables had to be declared at the start of the function, unlike in C++, where it could be declared anywhere in the function body to be used thereafter. Pointers were set to 0 or NULL, because it just made sure that the pointer pointed to no garbage. Otherwise, there's no significant advantage that I can think of, which compels anyone to do like that.

Vite Falcon's user avatar

Pros for localising variable definitions and their meaningful initialisation:

if variables are habitually assigned a meaningful value when they first appear in the code (another perspective on the same thing: you delay their appearance until a meaningful value is avaialable) then there's no chance of them accidentally being used with a meaningless or uninitialised value (which can easily happen is some initialisation is accidentally bypassed due to conditional statements, short-circuit evaluation, exceptions etc.)

can be more efficient

  • avoids overheads of setting initial value (default construction or initialisation to some sentinel value like NULL)
  • operator= can sometimes be less efficient and require a temporary object
  • sometimes (esp. for inline functions) the optimiser can remove some/all inefficiencies

minimising the scope of variables in turn minimises average number of variables concurrently in scope : this

  • makes it easier to mentally track the variables in scope, the execution flows and statements that might affect those variables, and the import of their value
  • at least for some complex and opaque objects, this reduces resource usage (heap, threads, shared memory, descriptors) of the program

sometimes more concise as you're not repeating the variable name in a definition then in an initial meaningful assignment

necessary for certain types such as references and when you want the object to be const

Arguments for grouping variable definitions:

sometimes it's convenient and/or concise to factor out the type of a number of variables:

the_same_type v1, v2, v3;

(if the reason is just that the type name is overly long or complex, a typedef can sometimes be better)

sometimes it's desirable to group variables independently of their usage to emphasise the set of variables (and types) involved in some operation:

type v1; type v2; type v3;

This emphasises the commonality of type and makes it a little easier to change them, while still sticking to a variable per line which facilitates copy-paste, // commenting etc..

As is often the case in programming, while there can be a clear empirical benefit to one practice in most situations, the other practice really can be overwhelmingly better in a few cases.

Tony's user avatar

  • I wish more languages would distinguish the case where code declares and sets the value of a variable which would never be written elsewhere, though new variables could use the same name [i.e. where behavior would be the same whether the later statements used the same variable or a different one], from those where code creates a variable that must be writable in multiple places. While both use cases will execute the same way, knowing when variables may change is very helpful when trying to track down bugs. –  supercat Commented Apr 28, 2014 at 22:50

Not the answer you're looking for? Browse other questions tagged c++ c or ask your own question .

  • The Overflow Blog
  • What launching rockets taught this CTO about hardware observability
  • The team behind Unity 6 explains the new features aimed at helping developers
  • Featured on Meta
  • Preventing unauthorized automated access to the network
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...

Hot Network Questions

  • How to measure objects in Blender 4.2
  • Can I enter China several times from Hong Kong and benefit multiple 15 day visa-free?
  • The answer is a highly composite number
  • Can the headphone jack of a laptop send MIDI signals with a Jack TRS cable?
  • Is entropy real or just a consequence of the way we choose to examine a physical system?
  • Can I become a software programmer with an Information Sciences degree?
  • I have two different statements for the t test and the single tail test
  • Why does Windows 11 display a different ethernet MAC (hardware) address than Linux?
  • Card design with long and short text options
  • What was the first game to implement ADS?
  • How to shade areas between three cycles?
  • Does anyone know what the Starship 5 fins are made of?
  • Why does Alien B, who can't see Alien A (and vice versa), crash their ship specifically into Alien A?
  • Can you (and has anyone) answer correctly and still get 100 points?
  • What is the difference between Pantheism and Atheism?
  • Under what circumstances is the observation of X proof of the existence of X?
  • Inserting special characters like x̄ X̄ that aren't in the digraph table?
  • Can every finite metric space be approximated by a distinct distance space?
  • Is it legal (US) to target drunk people and interview them to create (commercial) content a.k.a. street interviews?
  • Is this baseboard installation a good job?
  • Determining the absolute configurations of stereocenters in cyclic compounds
  • Are Vcc and Vin the same thing for logic gates?
  • Disadvantages of posting on arXiv when submitting to Nature or Science?
  • Complex conjugation can define the reals. What about vice versa?

multiple assignments c

  • Windows Programming
  • UNIX/Linux Programming
  • General C++ Programming
  • Multiple Assignment

  Multiple Assignment

multiple assignments c

No, that assigns a, b, and c to c+5.
Xerzi's way is better. Mines is a sloppy version to do that. Pretty sure it doesn't get easier than that but if anyone finds a better solution i'll be curious to see it.
elipses( count, ...) { (count<=0) { 0; } va_list arg_ptr; va_start(arg_ptr, count); sum=0; ( i=0; i<count; i++) sum += va_arg(arg_ptr, ); va_end(arg_ptr); sum; }

C++ Operators Introduction

C++ multiple assignments, c++ arithmetic operators, c++ relational operators, c++ logical operators, c++ relational logical precedence, c++ increment and decrement, c++ assignment operator, c++ compound assignment, c++ conditional operator, c++ logical operators in if, c++ bitwise operators introduction, c++ bitwise shift operators, c++ bitwise operators usage, c++ comma operator, c++ operator precedence, c++ sizeof operator, c++ operators new and delete, c++ allocating arrays, c++ memory initializing, c++ malloc() and free(), c++ operator exercise 1.

C++ allows a very convenient method of assigning many variables the same value: using multiple assignments in a single statement.

For example, this fragment assigns count, incr, and index the value 10:

In professionally written programs, you will often see variables assigned a common value using this format.

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

Staging Ground badges

Earn badges by improving or asking questions in Staging Ground.

c# multi assignment

This sort of thing would be really helpfull in C#. In this example 'a' and 'b' arn't encapsulated together such as the X and Y of a position might be. Does this exist in some form?

Below is a less trivial example.

Adam Maras shows in the comments that:

Sort of works for the example above however as he then points out it creates a new truple instead of changing the specified values.

Eric Lippert asks for use cases, therefore perhaps:

notallama also has use cases, they are in his answer below.

  • variable-assignment

alan2here's user avatar

  • 11 The last statement looks really unreadable to me. –  BoltClock Commented Nov 28, 2011 at 17:40
  • 1 I think this is more readable int a = 2; int b = 3; –  JonH Commented Nov 28, 2011 at 17:42
  • 1 @JonH: int a = 2, b = 3; optionally replacing the space after the comma with a line break. –  BoltClock Commented Nov 28, 2011 at 17:42
  • 4 Use F#, it's more suited for this kind of things –  Nasreddine Commented Nov 28, 2011 at 17:47
  • 1 Hey, I like this idea! Especially for out vars! –  Arlen Beiler Commented May 9, 2013 at 19:40

7 Answers 7

We have considered supporting a syntactic sugar for tuples but it did not make the bar for C# 4.0. It is unlikely to make the bar for C# 5.0; the C# 5.0 team is pretty busy with getting async/await working right. We will consider it for hypothetical future versions of the language.

If you have a really solid usage case that is compelling, that would help us prioritize the feature.

Eric Lippert's user avatar

  • 6 Most methods that use 'out' parameters would be more readable and concise if they were re-written using multiple assignment. The compiler warning "The out parameter 'x' must be assigned to before control leaves the current method" indicates how error-prone out vars can be—if you instead had to specify all the return vars in the return statement that would be a nice, self-reinforcing way for programmers to know they're doing the right thing. –  user87453 Commented Mar 26, 2012 at 0:12
  • 2 IMHO, after playing with Scala a bit and having read about how other languages deal with this, I now find the C# approach on tuples really cheap and ugly. I'm really looking forward to see this feature fully implemented in the language or at least some syntactic sugar added. As it stands now it feels like a half baked feature to me. –  Trap Commented Oct 15, 2012 at 11:42
  • 2 Those of us whose programming is more mathematical in nature very much appreciate multiple assignment / tuple support in the language. I recently made extensive use of F# because of this, using only C# in places where I had to interact with COM code, because F# let us more or less transliterate the formalisms from our paper straight into code. I would love to have these features in C#, as would my collaborators who are less comfortable in functional languages than I am. –  Dan Barowy Commented Jul 19, 2013 at 21:11
  • 2 @DanBarowy: Indeed, F# is often praised for exactly this property; C# by contrast has much more "ceremony" around it. I am no longer in a position to strongly influence the feature set for hypothetical future versions, but I do know that Anders and Mads and the other designers are aware that this is a pain point. –  Eric Lippert Commented Jul 19, 2013 at 22:39
  • 1 "it did not make the bar for C# 4.0". "pretty busy with getting async/await working right". double baffle. –  nicolas Commented Oct 16, 2013 at 14:30

it'd be really nice for working with IObservables, since those have only one type parameter. you basically want to subscribe with arbitrary delegates, but you're forced to use Action, so that means if you want multiple parameters, you have to either use tuples, or create custom classes for packing and unpacking parameters.

example from a game:

which i think is cleaner.

also, presumably IAsyncResult will have similar issues when you want to pass several values. sometimes it's cumbersome to create classes just to shuffle a bit of data around, but using tuples as they are now reduces code clarity. if they're used in the same function, anonymous types fit the bill nicely, but they don't work if you need to pass data between functions.

also, it'd be nice if the sugar worked for generic parameters, too. so:

would desugar to

notallama's user avatar

The behavior that you're looking for can be found in languages that have support or syntactic sugar for tuples . C# is not among these langauges; while you can use the Tuple<...> classes to achieve similar behavior, it will come out very verbose (not clean like you're looking for.)

Adam Maras's user avatar

  • 1 var tuple = Tuple.Create(2, 3); It's not too terrible. –  Dismissile Commented Nov 28, 2011 at 17:51
  • 1 No, but it's not as fluent as (for example) a lot of functional languages make working with tuples. –  Adam Maras Commented Nov 28, 2011 at 17:54
  • Can you rewrite the 2nd example using tuple and var? –  alan2here Commented Nov 28, 2011 at 17:58
  • 2 var result = n == 4 ? Tuple.Create(2, 3) : Tuple.Create(3, n % 2 == 0 ? 1 : 2); (off the top of my head, might not be quite right) –  Adam Maras Commented Nov 28, 2011 at 18:06
  • 1 Mind you, that's not congruent to your sample, as you're creating a new tuple instead of considering a and b as parts of an implicit tuple. You'd then have to assign the result of each part of the tuple to a and b afterwards, or just reference the tuple instead. –  Adam Maras Commented Nov 28, 2011 at 18:08

Deconstruction was introduced in C# 7.0: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/#user-content-deconstruction

paulie4's user avatar

The closest structure I can think of is the Tuple class in version 4.0 of the framework.

Yuck's user avatar

As others already wrote, C# 4 Tuples are a nice addition, but nothing really compelling to use as long as there aren't any unpacking mechanisms. What I really demand of any type I use is clarity of what it describes, on both sides of the function protocol (e.g. caller, calle sides)... like

This is obvious and clear at both caller and callee side. However this

Doesn't leave the slightest clue about what that solution actually is (ok, the string and the method name make it pretty obvious) at the call site. Item1 and Item2 are of the same type, which renders tooltips useless. The only way to know for certain is to "reverse engineer" your way back through SolvePQ .

Obivously, this is far fetched and everyone doing serious numerical stuff should have a Complex type (like that in the BCL). But everytime you get split results and you want give those results distinct names for the sake of readability , you need tuple unpacking. The rewritten last two lines would be:

This leaves no room for confusion, except for getting used to the syntax.

Sebastian Graf's user avatar

Creating a set of Unpack<T1, T2>(this Tuple<T1, T2>, out T1, out T2) methods would be a more idiomatic c# way of doing this.

Your example would then become

which is no more complex than your proposal, and a lot clearer.

Ivy Gorven's user avatar

  • 2 First, with that technique you can't use var to infer the type of a and b, and secondly it's a whole lot more verbose than just (a, b) = (2, 3) . Not saying your proposal is bad, just that it's not as good as what a full language integration of tuples could be. –  Suzanne Soy Commented Jun 30, 2014 at 14:56
  • Languages with integral support for tuples are really nice to work with, but I don't believe that c# should be such a language. In my opinion, the added verbosity is desirable, because any programmer with even a basic understanding of c# syntax (or rusty, inattentive, etc) instantly and intuitively knows what that line means. –  Ivy Gorven Commented Jul 13, 2014 at 10:12

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 .

Not the answer you're looking for? Browse other questions tagged c# .net tuples variable-assignment or ask your own question .

  • The Overflow Blog
  • What launching rockets taught this CTO about hardware observability
  • The team behind Unity 6 explains the new features aimed at helping developers
  • Featured on Meta
  • Preventing unauthorized automated access to the network
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Feedback Requested: How do you use the tagged questions page?
  • Proposed designs to update the homepage for logged-in users

Hot Network Questions

  • Is it possible to build a Full-Spectrum White Laser?
  • How to shade areas between three cycles?
  • Is there a link in theme, between Lev.16.8-22; with Rev.12; concerning the scape goat ceremony, and the cleansing of the sanctuary?
  • Will this radio receiver work?
  • Why does Alien B, who can't see Alien A (and vice versa), crash their ship specifically into Alien A?
  • Why do some of the Galilean moons have so much less radiation than others?
  • Crocodile paradox
  • Otherworldly – Numberlink / Marching Bands
  • I have two different statements for the t test and the single tail test
  • If the categorical variable is retained in my final model in R, then why does the post hoc analysis say the levels do not differ?
  • Does a vector change under coordinate transformation?
  • Is this baseboard installation a good job?
  • The shortcut hint
  • Under what circumstances is the observation of X proof of the existence of X?
  • What part of Homer is Pliny the Elder referring to in Natural History? (On the Use of Paper)
  • PCB design review of my line following robot
  • How can I seal the joint between my wall tile and bathroom countertop?
  • What was Adam Smith's position on the American Revolution?
  • 50s B&W sci-fi movie about an alien(s) that was eventually killed by cars' headlights
  • How to distinguish contrast from simultaneity when using the connective "while"?
  • How did the money go from buyers to the firm's account?
  • How to measure objects in Blender 4.2
  • Is the Hilbert Mumford Criterion true over the reals?
  • Complex conjugation can define the reals. What about vice versa?

multiple assignments c

IMAGES

  1. C++ Multiple and Combined Assignment Explained: Tips and Examples [5]

    multiple assignments c

  2. Assignment Operators in C Programming

    multiple assignments c

  3. Submitting C++ Assignments

    multiple assignments c

  4. C Programming Tutorial

    multiple assignments c

  5. Assignment Operators in C with Examples

    multiple assignments c

  6. Assignment Operators in C

    multiple assignments c

VIDEO

  1. Assignment Operator in C Programming

  2. Alternative Solution in Assignment Problem

  3. Augmented assignment operators in C

  4. VHDL BASIC Tutorial

  5. Identifier in C Programming (Hindi)

  6. ABS-CBN

COMMENTS

  1. c

    In C++ assignment evaluates to an lvalue, which requires "chained" assignments to be sequenced.) There's no way to say whether it is a good or bad programming practice without seeing more context. In cases when the two variables are tightly related (like x and y coordinate of a point), setting them to some common value using "chained ...

  2. c

    C - Multiple assignments to same variable in one line. 1. Allocating more than needed. 4. Multiple Assignments in C? 2. Proper way to assign single value to multiple variables. 1. Multiple assignment of single variable in a single line of code. Hot Network Questions Why does the Fisker Ocean have such a low top speed?

  3. C Exercises

    C Programming Exercises. The following are the top 30 programming exercises with solutions to help you practice online and improve your coding efficiency in the C language. You can solve these questions online in GeeksforGeeks IDE. Q1: Write a Program to Print "Hello World!" on the Console. In this problem, you have to write a simple ...

  4. C Declare Multiple Variables

    C Exercises. Test Yourself With Exercises. Exercise: Fill in the missing parts to create three variables of the same type, using a comma-separated list: myNum1 = 10 myNum2 = 15 myNum3 = 25; printf("%d", myNum1 + myNum2 + myNum3); Submit Answer ». Start the Exercise. Previous Next .

  5. Assignment Operators in C

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

  6. 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 ; ... Multiple assignment statements: C/C++ is one the few languages when you can assign the same value (from some expression) to multiple variables in one statement: ...

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

  8. Logicals and Assignments (GNU C Language Manual)

    8.3 Logical Operators and Assignments. There are cases where assignments nested inside the condition can actually make a program easier to read. Here is an example using a hypothetical type list which represents a list; it tests whether the list has at least two links, using hypothetical functions, nonempty which is true if the argument is a nonempty list, and list_next which advances from one ...

  9. 6.1. Multiple assignment

    6.1. Multiple assignment ¶. I haven't said much about it, but it is legal in C++ to make more than one assignment to the same variable. The effect of the second assignment is to replace the old value of the variable with a new value. The active code below reassigns fred from 5 to 7 and prints both values out. Save & Run.

  10. How expression a=b=c (Multiple Assignment) evaluates in C programming?

    Since C language does not support chaining assignment like a=b=c; each assignment operator (=) operates on two operands only. Then how expression a=b=c evaluates? According to operators associativity assignment operator ( = ) operates from right to left, that means associativity of assignment operator ( = ) is right to left.

  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. C Examples

    Program. C Program to Print an Integer (Entered by the User) C Program to Add Two Integers. C Program to Multiply Two Floating-Point Numbers. C Program to Find ASCII Value of a Character. C Program to Compute Quotient and Remainder. C Program to Find the Size of int, float, double and char. C Program to Demonstrate the Working of Keyword long.

  13. 5.1. Multiple assignment

    When there are multiple assignments to a variable, it is especially important to distinguish between an assignment statement and a statement of equality. Because C++ uses the = symbol for assignment, it is tempting to interpret a statement like a = b as a statement of equality. It is not!

  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: ... Multiple assignment statements: C/C++ is one the few languages when you can assign the same value (from some expression) to multiple variables in one statement: ...

  15. c++

    C. In C89 all declarations had to be be at the beginning of a scope ({ ... }), but this requirement was dropped quickly (first with compiler extensions and later with the standard).. C++. These examples are not the same. some_type val = something; calls the copy constructor while val = something; calls the default constructor and then the operator= function.

  16. Multiple Assignment

    No, that assigns a, b, and c to c+5. try parenthesizing the "c+=5". No, that assigns a, b, and c to c+5. I did it that way because you were adding the same values to them (5) and they all started with the same values (10) That is starting to look more like a recursive operation than variable assignment.

  17. [MFCS] Multiple Duplication When Generating Assignments

    Oracle Retail Merchandising Foundation Cloud Service - Version NA and later: [MFCS] Multiple Duplication When Generating Assignments [MFCS] Multiple Duplication When Generating Assignments ... When the user makes a transfer of merchandise between warehouses and then the assignments to stores, you are detecting that when creating the assignments ...

  18. C++ Multiple Assignments

    C++ Multiple Assignments. C++ allows a very convenient method of assigning many variables the same value: using multiple assignments in a single statement. For example, this fragment assigns count, incr, and index the value 10: In professionally written programs, you will often see variables assigned a common value using this format.

  19. Parallel assignment in C++

    The proper way doing this is just. std::swap(a, b); Boost includes a tuple class with which you can do. tie(a, b) = make_tuple(b, a); It internally creates a tuple of references to a and b, and then assigned to them a tuple of b and a. answered Nov 8, 2008 at 20:27. Johannes Schaub - litb. 505k 131 913 1.2k.

  20. Multiple assignment and evaluation order in Python

    a, b = 0, 1. while a < 10: print(a) a, b = b, a+b. With the multiple assignment, set initial values as a=0, b=1. In the while loop, both elements are assigned new values (hence called 'multiple' assignment). View it as (a,b) = (b,a+b). So a = b, b = a+b at each iteration of the loop. This continues while a<10.

  21. .net

    Those of us whose programming is more mathematical in nature very much appreciate multiple assignment / tuple support in the language. I recently made extensive use of F# because of this, using only C# in places where I had to interact with COM code, because F# let us more or less transliterate the formalisms from our paper straight into code.