Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if 0 is compiled in c program

Tags:

c

compilation

I'm trying to removed unused code from my program - I can't delete the code for now, I just want to disable it for a start.

Let's say that I have the following code:

if (cond){
  doSomething()
}

and cond is always false so doSomething is never called.

I want to do something like:

#define REMOVE_UNUSED_CODE 0
if (cond && REMOVE_UNUSED_CODE){
  doSomething()
}

Now this is obvious to us (and hopefully for the compiler) that this code is unused.

Will the compiler remove all this if condition or it will leave it and never get in?

P.S.: I can't use #if 0 for this purpose

like image 660
Shai Zarzewski Avatar asked Mar 21 '26 09:03

Shai Zarzewski


2 Answers

GCC will explicitly remove conditional blocks that have a constant expression controlling them, and the GNU coding standards explicitly recommend that you take advantage of this, instead of using cruder methods such as relying on the preprocessor. Although using preprocessor #if may seem more efficient because it removes code at an earlier stage, in practice modern optimizers work best when you give them as much information as possible (and of course it makes your program cleaner and more consistent if you can avoid adding a phase-separation dependency at a point where it isn't necessary).

Decisions like this are very, very easy for a modern compiler to make - even the very simplistic TCC will perform some amount of dead-code elimination; powerful systems like LLVM and GCC will spot this, and also much more complex cases that you, as a human reader, might miss (by tracing the lifetime and modification of variables beyond simply looking at single points).

This is in addition to other advantages of full compilation, like the fact that your code within the if will be checked for errors (whereas #if is more useful for removing code that would be erroneous on your current system, like references to nonexistent platform functions).

like image 190
Leushenko Avatar answered Mar 24 '26 01:03

Leushenko


Try

#ifndef REMOVE_UNUSED_CODE
if (cond) {
   doSomething();
}
#endif

Instead. Don't forget to do a

#define REMOVE_UNUSED_CODE

somewhere.

like image 25
rost0031 Avatar answered Mar 24 '26 02:03

rost0031



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!