Home > OS >  Is there any penalty for empty statements in C/C ?
Is there any penalty for empty statements in C/C ?

Time:09-21

I have recently joined the team that has a very peculiar coding guidance: Whenever they have an if block not followed by "else", they put a semicolone after the closing brace. The rationale is that it would signal to the reader that if there is an "else" below it, it belongs to the outer level "if" (in case the indentation is wrong). A small example:

if (condition1)
{
   //do something
   if (condition2)
   {
      // do something else
   };
}
else
{
  // do something as a negative response to the first if
}

I have not seen it before, so my question is - other than being an eyesore, is there any performance penalty for these empty statements at the end of the block, or they are just being ignored by the compilers? This is not a single or rare occasion, I am seeing these empty statements all over a file I am supposed to modify, one among many similarly coded...

CodePudding user response:

No, there is no runtime performance penalty for empty statements in C/C assuming optimizations are enabled or a mainstream compiler is used.

Basic optimizations are enough to remove any runtime overhead of the generated program. Mainstream compilers like Clang, GCC and MSVC remove such useless statements very early in the front-end part of the compilation stage. For example, Clang generates a Null statement during the generation of the Abstract Syntax Tree (AST), but it does not generate Intermediate Representation (IR) instruction related to the useless statements. The IR code is then used to optimize the output program and generate the assembly code. Note that this introduces some (small) overhead during the compilation though since compiler generate useless temporary data that should be stored and processed.

  • Related