Is the behavior "++ l * = m" undefined?

I started to learn C ++ 0x. I came across the following expression:

int l = 1, m=2; ++l *= m; 

I have no idea whether the second expression has well-defined behavior or not. So I ask for it here.

Isn't that UB? I just want to know.

+16
c ++ c ++ 11
Dec 02 '10 at 15:50
source share
2 answers

In the above code, the ++ prefix takes precedence over *= , so it starts first. As a result, l is 4 .

UPDATE: This is truly undefined behavior. My guess is that the priority rule was false.

The reason is that l is both an lvalue and an rvalue in *= , as well as in ++ . These two operations are not sequenced. Consequently, l written (and read) twice "without a sequence point" (the old standard formulation), and the behavior is undefined.

As a side element, I assume that your question is related to changes in sequence points in C ++ 0x. C ++ 0x changed the wording regarding “sequence points” to “sequenced before” to make standard definition clear. As far as I know, this does not change the behavior of C ++.

UPDATE 2: It turns out that there is actually a well-defined sequence in accordance with sections 5.17 (1), 5.17 (7) and 5.3.2 (1) of N3126 draft for C ++ 0x . @Johannes Schaub's answer is correct, and documents the sequence of the statement. Of course, the loan should go to his answer.

+3
02 Dec '10 at 15:53
source share

The expression is well defined in C ++ 0x. Frequently asked questions about standard quoting are given by Prasoon here .

I am not sure that such a high ratio (literal citation standards: explanatory text) is preferable, so I give a little small explanation: remember that ++L equivalent to L += 1 , and that calculating the value of this expression is sequenced after incrementing L And at a *= b calculating the value of the expression a sequenced before assigning the result of the multiplication to a .

What side effects do you have?

  • Increasement
  • Multiplication Result Assignment

Both side effects are transiently sequenced by the aforementioned two sequenced sequences and previously sequenced.

+14
Dec 02 '10 at 19:04
source share



All Articles