3

For example, in the code:

bool foo = bar || baz();

the function baz() may not be called. I've found that this is a common source of bugs for me and I'm wondering if there's a way for GCC to print a warning.

jhourback
  • 4,381
  • 4
  • 26
  • 31
  • 11
    in some sense this is like asking to get a warning for `if (condition) foo();` because `foo` might not be called. I would not expect a warning for that – 463035818_is_not_an_ai Sep 22 '19 at 19:08
  • 8
    Such warning would give you *a lot* of false positives on stuff like `if (ptr && ptr->foo())`... – HolyBlackCat Sep 22 '19 at 19:14
  • You might take a look at https://stackoverflow.com/questions/11714827/how-to-turn-on-literally-all-of-gccs-warnings and try to compile a simple test case with all possible warnings enabled. If you still don't get a warning, then you know the answer is "no, there is no such flag". – Nate Eldredge Sep 22 '19 at 19:18
  • I don't get a warning with `-Wall -W -Wextra`. Nor with clang 9.0.0 and `-Weverything`, see https://godbolt.org/z/QbKdA6. This strongly suggests there is no such flag. – Nate Eldredge Sep 22 '19 at 19:22
  • 1
    This would be something for `lint`-like or code quality tools. – meaning-matters Sep 22 '19 at 19:25
  • 3
    Changing the order to `bool foo = baz() || bar;` gurarantees `baz()` is always called. If you already know this, then I don't know what you are asking. – Ripi2 Sep 22 '19 at 19:38
  • @Ripi2: I think the question is how to have the compiler warn when you write `foo = bar || baz()`, on the grounds that you might really have meant `foo = baz() || bar`. – Nate Eldredge Sep 22 '19 at 19:47
  • Of course it may not be called. It would be very strange for issuing a warning for that. If you need warnings for stuff like that, avoid those constructs and write `foo = bar; if(!bar) foo = baz();` instead. – klutt Sep 22 '19 at 19:59
  • 2
    well, write `bool foo = bar | baz()` with a single `|` (bitwise or is not shortcutting) –  Sep 23 '19 at 00:44

1 Answers1

1

There is not a warning flag for this, it would generate a warning for too many common conditions (if(condition) bar();, if(foo && foo->bar) baz();, etc).

Instead, do something similar to this:

bool foo = baz() || bar;

or this:

bool foo = bar | baz();

These unconditionally call baz().

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76