Multiple value assignment attempts – Computer Sir Ki Class Code Learning #CPP#5571   Multiple value assignment attempts

Here we demonstrate the treatment of precedence between comma, brackets and assignment operator in a multiple value assignment scenario.

Learning Objectives

• Learning assignments in relation with operator precedence with respect to comma and parentheses.

Source Code

 #include using namespace std; int main() { //int x=1,2,3 //Will give error int x=(1,2,3); cout<

3
1

Code Understanding

//int x=1,2,3 //Will give error
This assignment is not valid as = operator has higher precedence than , comma operator. So 1 would be assigned to x but then compiler will try to declare 2 and 3 as integer variable. This is not possible as a variable name can not begin with a number.

int x=(1,2,3);
This assignment will work as parentheses will be evaluated first. Then assignment will happen by evaluating each term from left to right. Since the expressions inside brackets are separated by commas the last one will be assigned to x.

cout<<x<<endl;
As per above logic last value has been assigned to x , so this will print 3.

x = 1,2,3;
This one is a case where declaration has already been done previously. Here we are only assigning values. Since assignment will have higher precedence from comma so x will be assigned as 1 here. Value 2 and 3 will just act as stray expressions and will not have any impact.

cout<<x<<endl;
As per logic given above this will print 1.

Notes

• The evaluation of such confusing expressions must be done purely on the basis of operator precedence rules.

Suggested Filename(s): assignmu.cpp, assign-multiple.cpp

CSKC| Created: 19-Dec-2018 | Updated: 19-Dec-2018|

×