Is using a predecrement operator on the right hand side of an assignment valid C++?-Collection of common programming errors

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 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!

  1. 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.

  2. 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.

Originally posted 2013-11-10 00:14:55.