Search code examples
cexpressionvariable-assignmentexpression-evaluation

C multiple variable assignment


I'm first year student in Software Engineering and in my last task I used (chain assignment) multiple assignment of values.

The lecturer claims that it is illegal to assign values in this way.

X = Y = Z;

(The three variables are declared in the beginning of the function).

I would be happy if you can explain to me if the assign is right action and if what the teacher claims is right.


Solution

  • It depends on whether all of the objects were correctly declared and Z was initialized or assigned with an appropriate value before this statement or not.

    You can even assign values of objects of different types due to implicit casting, but the object which is getting assigned needs to be capable of holding the value of the object which is assigned to this one.

    If Z was initialized or assigned before and all objects were correct declared, then:

    X = Y = Z;
    

    is completely correct and legal as it assigns the value held in Z to Y and X - the assignment takes place from right to left.

    For example:

    int X,Y,Z;      // All objects are declared.
    
    Z = 24;         // `Z` is assigned with the integer value 24.
    X = Y = Z;      // `X` and `Y` get assigned by 24 which is the value in `Z`.
    

    Else if Z has an indeterminate value (f.e. if it was not declared with the extern or static keyword or declared at global scope) and you would assign this value to Y and X with that statement. Although the assignment itself would be even then not illegal, if you would use one of the assigned objects the program would give undefined results/output.


    Speaking for the multiple assignments only, there is nothing illegal about it, you could even use:

    O = P = Q = R = S = T = U = V = W = X = Y = Z;
    

    if all objects used were correctly declared before and Z has an determined value.


    The lecturer claims that it is illegal to assign values in this way.

    If it is possible, I would ask her/him or your teacher, what s/he meant with that. Maybe there is something specific to your course you should care about.