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
99 views
in Technique[技术] by (71.8m points)

c++ - Why does return 0 or break not work with the comma operator?

I can write the code if(1) x++, y++; instead of if(1) {x++; y++;}, but in some cases it does not work (see below). It would be nice if you tell me about this.

int x = 5, y = 10;    
if (x == 5) x++, y++;  // It works

if (x == 5) x++, return 0; // It shows an error

The same applies to for loops:

for (int i = 0; i < 1; i++) y++, y += 5; // It works

for (int i = 0; i < 1; i++) y++, break; // Does not work
question from:https://stackoverflow.com/questions/51942943/why-does-return-0-or-break-not-work-with-the-comma-operator

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

1 Reply

0 votes
by (71.8m points)

That's because return and break are statements, not expressions. As such, you cannot use it in another expression in any way. if and the others are similarly also statements.

What you can do however is rewrite your expression (for return) so that it's not nested in an expression - not that I recommend writing code like that:

return x++, 0;

You can't do that for break because it doesn't accept an expression.


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

...