Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

c++ - Why does ++x++ give compile error?

I am having confusion with the return value of post-increment and pre-increment operator.Whether it returns r-value or l-value.

    #include<iostream>
    using namespace std;
    int main(){
        int a=10;
        cout<<++a++<<"
";
    }

The following code give a compile error.

error: lvalue required as increment operator

Why is there an error?

How does the compiler evaluates the expression ++a++?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The result of the post-increment expression, a++ is an rvalue; a temporary with the value that a had before incrementing. As an rvalue, you can use its value, but you can't modify it. Specifically, you can't apply pre-increment it, as the compiler says.

If you were to change the precedence to do the pre-increment first:

(++a)++

then this would compile: the result of pre-increment is an lvalue denoting the object that's been modified. However, this might have undefined behaviour; I'm not sure whether the two modifications and the various uses of the value are sequenced.

Summary: don't try to write tricky expressions with multiple side-effects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...