Domanda

In reading The C Programming Language, I noticed in the precedence of order of evaluation section it states that "...function calls, nested assignment statements, and increment and decrement operators cause "side effects"...".

I'm trying to find some examples of nested assignment statements that result in undefined behavior. In the book, it states the following is ok:

int nl, nw, nc;
nl = nw = nc = 0;

in that nl, nw, and nc will all be assigned 0.

Then, I came across this which states:

x = y = y = z/3;    

Is not "recommended". So my question is, what could go wrong with this statement? Assignments associate from the right so the statement would be equivalent to:

x = (y = (y = z/3));    

To me, it seems pretty clear that y = z/3 and x = z/3. So, if this is the case, then could anyone give me an example of a nested assignment statement that could result in undefined behavior, and if not, can you explain why the previous statement is undefined.

È stato utile?

Soluzione

Assignment statements are not limited to a single variable. Among other things, you can assign to elements of an array.

Consider this example of nested assignment:

int a[] = {100, 200};
a[a[1]] = a[1] = 0;

if you evaluate the sequence of assignments, it should work as follows:

a[1] = 0

After this assignment, a looks like this: {100, 0}

a[a[1]] = 0

Knowing that a[1] is zero, this is the same as a[0] = 0, so the array should look like this: {0, 0}

However, the problem is that you are now banking on the fact that the side effect of a[1] = 0 is complete by the time you get to the next assignment: otherwise, you are assigning zero to a[100], which is way past the end of the array.

Since the order of completion of side effects is not defined in the absence of sequence points, this is undefined behavior.

Altri suggerimenti

http://c-faq.com/expr/seqpoints.html has several points that touch on your question. In particular:

While y = y is probably fine in

x = y = y = z/3;

An expression like

y = y++

is undefined because the value of y is modified twice before a sequence point.

Nested assignments can only potentially result in undefined behavior when some of the expressions have side effects. In the examples you posted, there are no side effects, so no undefined behavior. However, the page you link to also gives an example of undefined behavior:

x = y = y++;

They're not saying that all nested assignments cause undefined behavior, but just that you should avoid them all to avoid possibly using the ones that do. It's more of a style recommendation.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top