-1

Is there a general rule about disabling warnings in your code?

In my particular case, an unreachable code warning was issued because of an if statement testing a constant value, where it could be replaced with a compilation directive.

I believe that code where you have 100% of control over should never require #pragma warning disable XXXX.

Doc Brown
  • 199,015
  • 33
  • 367
  • 565
Roberto
  • 193
  • 6

1 Answers1

3

Use #pragma warning disable XXXX when:

  1. You have a legitimate reason for the warning appearing, and
  2. You don't want to see the warning, and
  3. You document your legitimate reason.

An illustrative example might be a try statement with an empty catch block, where the catch block is there to intentionally swallow an exception that is thrown by some library you can't control, and swallowing the exception is the only reasonable course of action.

Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
  • I guess my question was around considering what is a "legitimate reason". Is this so subjective that there's no way to better describe if one should or not use it? – Roberto Oct 31 '19 at 02:57
  • Each warning addresses a different problem, so they have to be evaluated on a case-by-case basis. In the example you provided in your question, was there a legitimate reason for an `if` statement testing a constant value? – Robert Harvey Oct 31 '19 at 16:17
  • The full story is: a colleague wanted to replace our compilation directives that is used to define environments/platforms with `if`s so the whole code can be inspected by the IDE for errors and warnings without needing to change the environment/platform (which we have many: android, iOS, dev, prod, server, client... multiple combinations). I didn't agree because of the warnings, there would be too many `#pragma warning disable`/`restore`. – Roberto Oct 31 '19 at 22:42
  • @Roberto: I guess one need to see the actual code, how a replacement of one preprocessor `#ifdef` by regular conditional lead to which warning precisely, and maybe think about alternatives. Maybe there is a solution which can solve the issue of not-switching the environments without disabling the warnings? – Doc Brown Nov 02 '19 at 09:39