Why is (C ++) * (C ++) undefined behavior in C ++?

I got confused in the output of this code:

int c=3;
cout<<(c++)*(c++);

I use gcc, but the result 9, but someone said that this behavior is undefined, why?

+3
source share
5 answers

Problem: "Sequence Points":

http://en.wikipedia.org/wiki/Sequence_point

The point of sequence in imperative programming defines any point in the execution of a computer program at which it is guaranteed that all sides of the effects of previous evaluations will be fulfilled, and no side effects of subsequent evaluations have yet been performed.

, . C = ++, , -, i. , , , , . , undefined. C ++, undefined. [1]

, - "9" - MSVC (Windows), gcc (Linux). , gcc ( "C" ) g++ (++):

$ g++ -o tmp -Wall -pedantic tmp.cpp
tmp.cpp: In function "main(int, char**)":
tmp.cpp:7: warning: operation on "c" may be undefined
$ ./tmp
c=9...
+4

Undefined -.

9, 12, 0 2147483647.

+3

C spec undefined, , (.. ). undefined - .

, , ++ es, ++, , ++?

+1

, , , .., 9, 16, 20, . undefined. , .

0

unspecified behavior, undefined behavior, - , :

Such an implementation can handle the post-increment as follows:

tmp_1=c;              // read 'c'
tmp_2 = tmp_1 + 1;    // calculate the incremented value
c = tmp_2;            // write to 'c'
tmp_1;                // the result of the expression

The original expression (c++)*(c++)has two sequences:

lhs_1=c;              // read 'c'
lhs_2 = lhs_1 + 1;    // calculate the incremented value
c = lhs_2;            // write to 'c'
lhs_1;                // the resulting value of the expression

rhs_1=c;              // read 'c'
rhs_2 = rhs_1 + 1;    // calculate the incremented value
c = rhs_2;            // write to 'c'
rhs_1;                // the resulting value of the expression

The order may be:

lhs_1=c;              // read 'c'
lhs_2 = lhs_1 + 1;    // calculate the incremented value
c = lhs_2;            // write to 'c'

rhs_1=c;              // read 'c'
rhs_2 = rhs_1 + 1;    // calculate the incremented value
c = rhs_2;            // write to 'c'

lhs_1 * rhs_1         // (3 * 4) new value of 'c' is 5

Or:

lhs_1=c;              // read 'c'
rhs_1=c;              // read 'c'

lhs_2 = lhs_1 + 1;    // calculate the incremented value
c = lhs_2;            // write to 'c'

rhs_2 = rhs_1 + 1;    // calculate the incremented value
c = rhs_2;            // write to 'c'

lhs_1 * rhs_1         // (3 * 3) new value of 'c' is 4

Or:

rhs_1=c;              // read 'c'
rhs_2 = rhs_1 + 1;    // calculate the incremented value
c = rhs_2;            // write to 'c'

lhs_1=c;              // read 'c'
lhs_2 = lhs_1 + 1;    // calculate the incremented value
c = lhs_2;            // write to 'c'

lhs_1 * rhs_1         // (4 * 3) new value of 'c' is 5

.... etc.

unspecified behavioris that he can evaluate lhs or rhs first. undefined behaviorlies in the fact that we read and write in a csequence without intermediate points.

0
source

All Articles