Defining constants

There are two main ways to define a constant via the preprocessor: through a compiler switch and in code. To see how this works, let's change the main function to print out the value of a constant; the two important lines are highlighted:

    #include <iostream>      #define NUMBER 4      int main()     {         std::cout << NUMBER << std::endl;     }

The line that starts with #define is an instruction to the preprocessor, and it says that, wherever in the text there is the exact symbol NUMBER, it should be replaced with 4. It is a text search and replace, but it will replace whole symbols only (so if there is a symbol in the file called NUMBER99 the NUMBER part will not be replaced). After the preprocessor has finished its work the compiler ...

Get Beginning C++ Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.