This question may seem rather basic, but coming from an engineering (non computer-science) background, I was unsure about what the snippets of '#
's were in some C++ code.
A quick search led me to the concise, well-explained cplusplus tutorial page on preprocessor directives.
But why bother with the concept of preprocessor directives at all? Is it not possible to write equivalent code that can assign values to constants, define subroutines/function/macros and handle errors?
I guess I ultimately want to know when it is good practice to use such preprocessor directives, and when it is not.
The C preprocessor performs a number of tasks, some but not all of which have better alternatives in C++. Where C++ has a better alternative use it. Those alternatives include templates, inlining, and
const
variables (an oxymoron, but that is what the standard calls them) in place of #define macros.However there are few things that you would not want to do without or simply cannot do without;
#include
for example is essential, and when coding for multiple platforms or configurations, conditional compilation remains useful (although should be used sparingly in all cases).Compiler specific extensions controlled via
#pragma
may be unavoidable in some cases.