-2

I am looking for something like this:

int nVal = 130;
while(nVal % 6 != 0)
  nVal--;

in a while loop without body:

int nVal = 130;
while(nVal-- % 6 != 0)

Of course that way, the -- operator is called once too often. Any suggestions here or should I go with option #1?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
tzippy
  • 6,458
  • 30
  • 82
  • 151

3 Answers3

5

Use the first alternative as it is clearer and correct. It is never a good idea to show as many operators as possible into a single line. Particularly not the ++ and -- operators since those include a side effect, and are therefore notoriously dangerous to use together with other operators.

Lundin
  • 195,001
  • 40
  • 254
  • 396
2

You can do this: while((nVal-- -1) % 6 != 0) but, as Lundin said, the first example is clearer

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
0

After the optimization it should be the same code in asm. Probably it could be better to use --nVal instead of nVal-- but with -o3 it does not matter I think.

DenSumy
  • 143
  • 1
  • 9
  • I don't think the optimizer would be allowed to produce the same assembly for prefix/postfix in this case because they aren't semantically identical – awksp Sep 03 '15 at 15:04
  • 2nd option decreases the value even when the condition evaluates to 0, so they are not equivalent. – Lundin Sep 03 '15 at 15:04
  • If the optimizer is smart enough it will be reduced to `nVal=126`. – Eugene Sh. Sep 03 '15 at 15:05
  • @EugeneSh. Are loop bodies evaluated during optimization? I thought that this kind of thing normally wouldn't be done because in the majority of cases the code cannot be evaluated at compile time – awksp Sep 03 '15 at 15:08
  • @awksp You can't know for sure. Optimizers are getting better (worse?) in this type of things. They can even do strange things like [this](http://stackoverflow.com/questions/30262801/what-is-my-best-approach-to-determining-compiler-behaviour-for-empty-infinite-lo). – Eugene Sh. Sep 03 '15 at 15:10
  • I've looked at the asm code after Visual studio (don't remember version) there where too loops with ++i and i++ and optimized code were the same in both cases. – DenSumy Sep 04 '15 at 11:41