Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...