This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Assignment operator

Anonymous
Anonymous
Guru 17045 points

Hi,

 

I would like to ask a question on assignment operators.

 

 

According to K&R, expr1 is computed only once. Is the difference between

  1. exp1 = exp1 op exp2
  2. exp1 op= exp2

 

as shown in the two trees above?

 

Additionally, for the computation to be done without a variable for temporary result storage, the ALU must support taking destination to be the same as one source. On ALUs that does NOT support this, would there still be any difference between (1) and (2)?

 

 

Zheng

 

 

  • The reason the text stresses that expr1 is evaluated only once is in case there are side effects, such as in the following code:

    int *function(int *a)
    {
        int *p = a;
        *p++ *= 5;
    return p; }

    The return value should be equal to (a+1), because "*p++" should be evaluated only once.

    This applies only to the expressions as viewed in the C context.  The machine need not support an assembly instruction which does "op=" directly; the compiler will use whatever instructions are necessary to translate the code, and it is free to to so as long as the function behaves as the C standard requires.

  • Anonymous
    0 Anonymous in reply to Archaeologist

    Archaeologist,

    I see it, it is like

     

    int a,b;

    a=4, b=7;   

    (a*=3,b) += 5;//a=12 after execution

    a=4, b=7;           

    (a*=3,b) = (a*=3,b) + 5;//a=36 after execution

     

    Thanks for explanation on side-effect.

     

    Zheng