What is the #define Preprocessor in C++?

PythonServer Side ProgrammingProgramming

The #define creates a macro, which is the association of an identifier or parameterized identifier with a token string. After the macro is defined, the compiler can substitute the token string for each occurrence of the identifier in the source file.

#define identifier token-string

This is how the preprocessor is used. The #define directive causes the compiler to substitute token-string for each occurrence of identifier in the source file. The identifier is replaced only when it forms a token. That is, identifier is not replaced if it appears in a comment, in a string, or as part of a longer identifier.

example

#include<iostream>
#define MY_VAR 55
using namespace std;

int main() {
   int x = 10;
   cout << x + MY_VAR;      // After preprocessing this expression becomes: x + 55
   return 0;
}

Output

This will give the output −

65

You can read more about the #define directive in MSDN https://docs.microsoft.com/en-us/cpp/preprocessor/hash-define-directive-c-cpp

raja
Updated on 18-Jun-2020 13:05:52

Advertisements