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

#include <stdio.h>
int main(){
	int a,b,c;
	a=0; b=0; c=100;
	
	printf("Before Multiple Assignent a=%d,b=%d,c=%d\n",a,b,c);
	
	//Multiple Assignent
	a=b=c;
	printf("After Multiple Assignent a=%d,b=%d,c=%d\n",a,b,c);
	
	return 0;	
}

Output

Before Multiple Assignent a=0,b=0,c=100 
After Multiple Assignent a=100,b=100,c=100

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:

a=b=c=d=0;

Consider the following program

#include <stdio.h>
int main(){
	int a,b,c,d;
	
	a=b=c=d=0;
	printf("a=%d, b=%d, c=%d, d=%d\n",a,b,c,d);
	
	return 0;	
}

Output

a=0, b=0, c=0, d=0





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.