1

Following code in MSVC generates warning about assignment in conditional expression. https://godbolt.org/z/i_rwY9

int main()
{
    int a;
    if ((a = 5)) {
        return 1;
    }
    return a;
}

Note that I tried to use the double () around if since that makes the warning go away with g++, but I do not know how to make it go away in msvc without extracting the assignment from condition. Is there a way to nudge msvc to figure out that this assignment is intentional?

I know I can use pragmas to disable this warning, but pattern is very common so I would like to get a solution without pragmas if one exists.

NoSenseEtAl
  • 28,205
  • 28
  • 128
  • 277
  • That code is behind the [door on the right](https://mk0osnewswb2dmu4h0a.kinstacdn.com/images/comics/wtfm.jpg). – Hans Passant Dec 31 '19 at 08:32
  • @HansPassant in some cases it is unfeasible to change 500 occurrences of this pattern. :) – NoSenseEtAl Dec 31 '19 at 08:38
  • I'm glad you think it is funny, few programmers would think it is. Disabling the warning is the obvious way, given that the original programmer didn't get the benefit from the warning either. The compile option can be set per source file, use Shift+Click to select multiple. – Hans Passant Dec 31 '19 at 08:51

1 Answers1

2

The MSVC compiler will give this warning unless you can convince it that you really do know what you're doing. Adding at least one 'real' logical test will achieve this:

int main()
{
    int a;
    if ((a = 5) != 0) {
        return 1;
    }
    return a;
}

Note that the constant 5 can readily be replaced with any variable or valid expression: adding the explicit != 0 test does nothing to actually change the outcome of the code (and it is unlikely to change the generated assembly).

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • 1
    I would like to find something nicer and something that works for nondeterministic assignment, since this is quite ugly, but it is nicer than pragma so I gave you an upvote. – NoSenseEtAl Dec 31 '19 at 08:19
  • 1
    @NoSenseEtAl Not sure if you saw my original post (you can inspect the edit changes, I guess) but maybe the "comma operator" approach I first suggested will suit your needs? (It's even uglier, IMHO, and `clang` doesn't like it, but that may work for your 'non-deterministic' cases.) – Adrian Mole Dec 31 '19 at 08:22
  • 1
    I was refering to original post, this is nicer, but still I prefer the gcc way... but I am afraid this is the best way. Will accept if nobody comes with a better way. – NoSenseEtAl Dec 31 '19 at 08:37