Using the #define, #ifdef, #ifndef, #undef, #else and #endif in C++ program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: Conditional printing using #define, #ifdef, #ifndef, #undef, #else and #endif in C++ programming

To show: How to use the #define, #ifdef, #ifndef, #undef, #else and #endif in C++ programming

 

#define Module101

#define MyVersion 1.1

#include <iostream>

using namespace std;

 

int main(void)

{

cout<<"Sample using #define, #ifdef, #ifndef"<<endl;

cout<<" #undef, #else and #endif..."<<endl;

cout<<"-------------------------------------"<<endl;

#ifdef Module102

cout<<"\nModule102 is defined."<<endl;

#else

cout<<"\nModule102 is not defined."<<endl;

#endif

#ifndef MyVersion

cout<<"\nMyVersion is not defined"<<endl;

#else

cout<<"\nMyVersion is "<<MyVersion<<endl;

#endif

#ifdef MyRevision

cout<<"\nMy Revision is defined\n"<<endl;

#else

cout<<"\nMyRevision is not defined!"<<endl<<endl;

#endif

#undef MyVersion

#ifndef MyVersion

cout<<"MyVersion is not defined"<<endl<<endl;

#else

cout<<"MyVersion is "<<MyVersion<<endl;

#endif

return 0;

}

 

Output example:

 

Sample using #define, #ifdef, #ifndef

        #undef, #else and #endif...

-------------------------------------

Module102 is not defined.

MyVersion is 1.1

MyRevision is not defined!

MyVersion is not defined

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index