Multiple assignment in one line

后端 未结 10 994
天涯浪人
天涯浪人 2020-11-30 04:22

I just come across the statement in embedded c (dsPIC33)

sample1 = sample2 = 0;

Would this mean

sample1 = 0;

sample2 = 0;
         


        
10条回答
  •  北海茫月
    2020-11-30 04:35

    Formally, for two variables t and u of type T and U respectively

    T t;
    U u;
    

    the assignment

    t = u = X;
    

    (where X is some value) is interpreted as

    t = (u = X);
    

    and is equivalent to a pair of independent assignments

    u = X;
    t = (U) X;
    

    Note that the value of X is supposed to reach variable t "as if" it has passed through variable u first, but there's no requirement for it to literally happen that way. X simply has to get converted to type of u before being assigned to t. The value does not have to be assigned to u first and then copied from u to t. The above two assignments are actually not sequenced and can happen in any order, meaning that

    t = (U) X;
    u = X;
    

    is also a valid execution schedule for this expression. (Note that this sequencing freedom is specific to C language, in which the result of an assignment in an rvalue. 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" assignment is actually perfectly good practice (I'd even say "recommended practice"). But when the variables are completely unrelated, then mixing them in a single "chained" assignment is definitely not a good idea. Especially if these variables have different types, which can lead to unintended consequences.

提交回复
热议问题