Preprocessing Directives - C++ Preprocessor

C++ examples for Preprocessor:Directive

Introduction

DirectiveDescription
#include Supports header file inclusion
#if Enables conditional compilation
#elseelse for #if
#elifEquivalent to #else #if
#endif Marks the end of an #if directive
#define Defines an identifier
#undef Deletes an identifier
#if defined (or #ifdef) Does something if an identifier defined
#if !defined (or #ifndef)Does something if an identifier is not defined
#lineRedefines the current line number and/or filename
#error Outputs a compile-time error message and stop the compilation.
#pragma Offers machine-specific features while retaining overall C++ compatibility

Defining Preprocessing Identifiers

The general form of the #define preprocessing directive is:

#define identifier sequence_of_characters

The following code defines PI to be an alias for a sequence of characters that represents a numerical value:

#define PI 3.14159265

The #define directive is often used to define symbolic constants in C but don't do this in C++.

In C++, do it this way.

const long double pi {3.14159265L};

Define it with external linkage:

extern const long double pi {3.14159265L};

Here's another example:

#define BLACK WHITE

If you don't specify a substitution string for an identifier, then the identifier will be replaced by an empty string.

For example:

#define VALUE

Undefining an Identifier

You can negate a previously defined VALUE identifier with this directive:

#undef VALUE

Example,

#define PI 3.142
// All occurrences of PI in code from this point will be replaced by 3.142

#undef PI
// PI is no longer defined from here on so no substitutions occur.
// Any references to PI will be left in the code.

Including Header Files

Example,

#include <iostream>
#include "myheader.h"

Related Tutorials