Home > database >  K&R book states using assignment operator will only compute the expression once?
K&R book states using assignment operator will only compute the expression once?

Time:10-22

Hello everybody I am reading K&R The C Programming Language, and in Chapter 2.10 it states:

"If expr1 and expr2 are expressions, then

expr1 op= expr2 is equivalent to

expr1 = (expr1) op (expr2) except that expr1 is computed only once."

op= is referring to the binary operators you can use with assignment like =, - etc. (and in the 2nd line op just means a binary operator like )

My first minor confusion is that expr1 must be only a variable? (an "lvalue"?) Or else how can we assign a result to a larger expression? But my main question is what is meant by expr1 is computed only once? Would something have been computed twice if we wrote:

expr1 = (expr1) op (expr2)

instead of

expr1 op= expr2

?

CodePudding user response:

This feels contrived, but consider:

#include <stdio.h>

int x = 0;

int *f(void) { printf("f is called\n"); return &x; }

int
main(int argc, char **argv)
{
    printf(" x = %d\n", x);
    *f()  = 1;  /* Calls f once */
    printf(" x = %d\n", x);
    *f() = *f()   1;  /* Calls f twice */
    printf(" x = %d\n", x);
    return 0;
}

A less contrived example would be something like:

a[i  ]  = 1;
  •  Tags:  
  • c
  • Related