Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

?

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading