Search code examples
c++if-statementlanguage-agnosticno-op

Meaning of weird side-effectless statement inside if


I was browsing through a project and came across this:

if(!StaticAnimatedEntities)
  int esko = esko = 2;

(The type of StaticAnimatedEntities here is a plain unsigned short.)

It struck me as very odd so I grepped the project for esko and found other similar ifs with nothing but that line inside them, f.ex. this:

if(ItemIDMap.find(ID) != ItemIDMap.end())
  int esko = esko = 2;

(Note that there are no other variables named esko outside those ifs.)

What is the meaning of this cryptic piece of code?


Solution

  • You can sometimes see code like this just to serve as an anchor location to put a breakpoint on in an interactive debugger in order to trap some "unusual" (most often - erroneous) conditions.

    Debugger-provided conditional breakpoints are usually very slow and/or primitive, so people often deliberately plan ahead and provide such conditional branches in order to create a compiled-in location for a breakpoint. Such a compiled-in conditional breakpoint does not slow down program execution nearly as much as a debugger-provided conditional breakpoint would.

    In many cases such code is surrounded by #ifndef NDEBUG/#endif to prevent it from getting into the production builds. In other cases people just leave it unprotected, believing that optimizing compiler will remove it anyway.

    In order for it to work the code under if should generate some machine code in debug builds. Otherwise, it would be impossible to put a breakpoint on it. Different people have different preferences in that regard, but the code virtually always looks weird and meaningless.

    It is the meaninglessness of that code that provides programmers with full freedom to write anything they want there. And I'd say that it often becomes a part of each programmer's signature style, a fingerprint of sorts. The guy in question does int esko = esko = 2;, apparently.