When is it appropriate to use conditional compilation instead of regular if-else statements?

I see that there are some benefits to conditional compilation using constructs like #ifdef over runtime conditional checks such as smaller compiled file size, probably faster execution, and somewhat easier debugging, but when is it appropriate to use one over the other? Is it a best practice to use runtime conditional checks when the conditional statement being evaluated can only be determined at runtime?

In my opinion mixing #ifdefs with regular if-then-else statements makes the code ugly and harder to read, so I tend to avoid conditional compilation. However I've noticed that in a lot of C# log class examples conditional compilation is used to determine when to perform logging depending on whether symbols such as DEBUG/SHIP/TRACE are defined.

Answers


It's best to minimise the use of #ifdef's. Like you said, they make the code harder to read and debug.

They can be unavoidable when targeting different platforms, or when there are differences between debug/release versions.

Performance could be a consideration to use #ifdef's e.g. for debugging, but in most cases the impact of an extra conditional statement to check for log level would be negligible. I'd say you'd have to profile the code and determine that this is a bottleneck before converting conditional logic to #ifdef's


Need Your Help

How to get a UIView current position?

ios iphone objective-c

I have a UIView appearing when the user taps the screen.

Exception When Registering Lisst Change Listener

java exception generics user-interface javafx

I just added this code to my list program and I got an exception from it. I'm not exactly sure what is happening, and it avoided my efforts to debug with it. Specifically, the exception happened on...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.