Avoid "Unreachable code" warning for preprocessor-dependent code
Asked Answered
F

1

9

I'm trying to figure out if there's any way to avoid getting an "Unreachable code" warning for something that's caused by the preprocessor. I don't want to suppress all such warnings, only those which will be dependent on the preprocessor, e.g.

#if WINDOWS
    public const GamePlatform platform = GamePlatform.PC;
#else
    public const GamePlatform platform = GamePlatform.MAC;
#endif

And later on there's code that goes:

if (platform == GamePlatform.PC)
{
    ...
}
else
{
    ...
}

One of those two sections will always be detected as "Unreachable code", and we've got those all over the place. I'd like to try and get rid of the many warnings it creates, but I still want to get warnings for legitimately unreachable code. (In reality, there's more than just two platforms, so each chunk of platform-specific code creates a pile of unnecessary warnings.)

Footloose answered 26/7, 2013 at 21:7 Comment(2)
Use this question as reference. #1931293 Specifically look at Jason Down's answer.Kalakalaazar
I did do search for other questions first, didn't see any specifically dealing with the preprocessor regarding this issue. (There's a lot of questions regarding unreachable code, but none of the ones I checked seemed to be the same scenario.) Annoying that there isn't some way of dealing with this that doesn't either significantly uglify the code, reduce performance (slightly), or hide potentially useful warnings.Footloose
R
9

Option 1: Add the preprocessor macros wherever you have the if-statements. This will be more performant, but perhaps a bit uglier.

Option 2: Make the platform variable not const. Setting it to static readonly made the warning go away for me.

Rosabelle answered 26/7, 2013 at 21:13 Comment(3)
But with "option 2" the compiler will have to translate both "sections" or "branches" of the if into IL, and much of that IL will never be used, so that's one kind of waste (though not very important if you don't care about the size of the DLL file).Insomnolence
I agree that option 2 is probably not what I would do, but it's the easiest and sometimes that's important. It is worth mentioning that "unreachable code" is not translated into IL, so changing it to static readonly will be "worse" than your current predicament while option 1 will be the same minus the warning.Rosabelle
Hmm, the eternal dilemma of uglier code vs. slightly slower code - I know I should go with Option 1, but I really dislike polluting code with preprocessor-stuff all over the place. Makes it harder to read. Also, since the compiler ignores it, there may be bad code in the inactive code blocks that I'm missing which would only show up when the #defines are changed...Footloose

© 2022 - 2024 — McMap. All rights reserved.