Introduction to Changed Assignments in C++:: Part-A-9

0

CHAINED ASSIGNMENTS

An assignment itself is an expression with a value. The value of the expression

       x = 22

is 22. And like any other value, the value of an assignment can be used in another assignment:

       y = (x = 22) ;

This is a chained assignment. First it assigns 22 to  x, and then it assigns 22 to y. Compound assignments are usually written without the parentheses:

       y = x = 22;

In general, the value of an assignment is the last value that it assigned.

EXAMPLE: Embedded Assignments

This shows how an assignment can be used within an expression:

            # include<iostream.h>

            // This shows that an assignment can be part of a larger expression:

             main ()

             {

                     int m,  n;

                     m =  (n = 66) + 9;  //  (n = 66) is an assignment expression

                      cout  << m  << ‘’, ‘’  << endl;

                      return 0;

             }

OUTPUT: 75, 66

The compound assignment first assigns the value 66 to n. Then it evaluates the expression (n = 66) + 9 obtaining the value 75. Then it assigns that value to m.

Embedded assignments can usually be avoided. For example, the first two lines in the program above would be better written as

              int n = 66;

              int m = n + 9;

This also illustrates the preferred practice of initializing variables as they are declared.

There are some situations in which embedded assignments do make a program more readable. For example, this single statement is better than 8 separate statements:

              n1 = n2 = n3 = n4 = n5 = n6 = n7 = n8 = 65535;

  A chained assignment cannot be used as an initialization in a declaration:

              int x = y = 22;  //  ERROR

The reason this is wrong is that initializations are not assignments. They are similar, but the compiler handles them differently. The correct way to do what was attempted above is

              int x = 22, y = 22; // OK

                                                     ——————- Thanks

Share.

About Author

TN365

Leave A Reply