简体   繁体   中英

Ternary operator with index++ gives “Only assignment, call, increment, decrement, await and new object expressions can be used as statement”

I don't get this hint text and the reason why the code doesn't compile:

int index = 0;
bool result = false;

result ? index++ : index--;

This is an increment/decrement isn't it?

Why does it give a compilation error: "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement"?

Ternary operator isn't a statement by itself. It doesn't matter what's inside it, it's about what it is itself. This would be a statement:

index += result ? 1 : -1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM