c++ preprocessor commands
The C++ preprocessor commands are used to modify the source code before it is compiled. These commands start with a hash symbol (#) and are processed by the preprocessor, which is a part of the C++ compiler. The preprocessor commands are executed before the actual compilation takes place, and they can be used to include header files, define constants, and perform conditional compilation.
#include
The #include
directive is used to include the contents of another file into the current source file. This is typically used to include header files that contain function and variable declarations. The syntax for #include
is:
#include <filename>
#define
The #define
directive is used to define constants or macros. It allows you to define a name for a value or a block of code, which can be used throughout the program. The syntax for #define
is:
#define constant value
#ifdef, #ifndef, #endif
These directives are used for conditional compilation. The #ifdef
directive checks if a particular macro has been defined, and if it has, the code between #ifdef
and #endif
is included in the compilation. The #ifndef
directive is the opposite of #ifdef
and checks if a macro has not been defined. The syntax for #ifdef
, #ifndef
, and #endif
is:
#ifdef macro
// code to include if macro is defined
#endif
#ifndef macro
// code to include if macro is not defined
#endif
#if, #elif, #else
These directives are used for conditional compilation based on expressions. The #if
directive evaluates an expression and includes the code between #if
and #endif
if the expression is true. The #elif
directive is used for additional conditions, and the #else
directive is used for code that should be included if none of the previous conditions are met. The syntax for #if
, #elif
, and #else
is:
#if expression
// code to include if expression is true
#elif expression
// code to include if expression is true
#else
// code to include if none of the previous conditions are met
#endif
#undef
The #undef
directive is used to undefine a previously defined macro. This allows you to remove a macro definition if it is no longer needed. The syntax for #undef
is:
#undef macro
#error
The #error
directive is used to generate a compile-time error with a specific message. This is useful for enforcing certain conditions or displaying custom error messages. The syntax for #error
is:
#error "error message"
#pragma
The #pragma
directive is used to provide additional instructions to the compiler. These instructions are implementation-specific and can be used for various purposes, such as enabling or disabling certain compiler features. The syntax for #pragma
is:
#pragma instruction
These are the main preprocessor commands in C++. They allow you to modify the source code before compilation and provide additional flexibility and control over the compilation process.