Search code examples
c++xcodecompiler-warningsdead-code

Xcode offers strange solution for explicitly dead code in c++?


I'm writing a program that is supposed to solve a sudoko-like puzzle, Hashiwokakero. I have some code that looks like this:

if (bridgesLeft[row][col] == 1)
{
   doSomething();
}
else if (bridgesLeft[row][col] == 2)
{
   doSomethingElse();
}
else if (bridgesLeft[row][col] == 3)
{
   doAnotherThing();
}
...

I realized that I put a bug in the doSomethingElse() function, so rather than deleting that block, I added else if (bridgesLeft[row][col] == 2 && false) to guarantee that the buggy function wouldn't run, just to make sure that was where my bug was coming from. Xcode gave me a warning, saying my doSomethingElse() code would never run. It also gave me this option:

fix-it: Silence by adding parentheses to mark code as explicitly dead.

Clicking on this button changes

else if (bridgesLeft[row][col] == 2 && false)

to

else if (bridgesLeft[row][col] == /* DISABLES CODE */ (2) && false)

How do parentheses around the '2' mark this code as explicitly dead? What does this mean? If I leave the parentheses in, but take the && false part out, the code block is still executed, so it's not actually making the code dead.


Solution

  • This does not fix the problem as much as silence the warning by telling clang that the code is meant to be dead, we can see this by reading Improve -Wunreachable-code to provide a means to indicate code is intentionally marked dead via if((0)) which says:

    Log: Improve -Wunreachable-code to provide a means to indicate code is intentionally marked dead via if((0)).

    Taking a hint from -Wparentheses, use an extra '()' as a sigil that a dead condition is intentionally dead. For example:

    if ((0)) { dead }
    

    When this sigil is found, do not emit a dead code warning. When the analysis sees:

    if (0)
    

    it suggests inserting '()' as a Fix-It.

    From what I can tell it is just looking for an integer literal in (), which in your case the (2) fits this case and silences the warning.