简体   繁体   中英

Is using a predecrement operator on the right hand side of an assignment valid C++?

I almost never put a ++ or -- anywhere except on its own line. I know they can lead to undefined behavior and can be hell for debugging. But for verbosity purposes, I'm tempted. Is this valid code?

map<int, int> dict;

...

int key = ...;
if (dict.lower_bound(key) != dict.begin()) {
  int prevval = (--dict.lower_bound(key))->second;
  ...
}

I'd like to just do

int prevval = (dict.lower_bound(key)-1)->second;

but bidirectional iterators don't have operator-() defined.

Thanks!

Yes, it's perfectly valid and works as expected.

Undefined behavior when using these operators usually come from modifying a variable multiple times between sequence points, which is not your case.

Actually you are doing an initialization and not an assignment, but that doesn't change anything.

However, your code is valid, because there is no choice in the order of applying all the operators. You have to be careful if an expression can be split in subexpressions which could be evaluated in arbitrary order.

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