Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am using conditional compilation using #define.
I am iterating over a loop. Inside the loop, using #ifdef ... #else ... #endif
I want to skip the #ifdef part on the basis of some condition and want to run #else part.

What I have tried:

Example:
C++
#include <iostream>
using namespace std;

#define NOINPUT
int main ()
{
  for(int i =1 ; i <=10;i++)
  {
      int num = 0;
#ifdef NOINPUT
      //if(i > 5)
      //want to execute #else part for remaining iteration
      num = i;
#else
      cout<<"Enter a number:";
      cin>>num;
#endif
     cout<<"Number: "<<num<<"\n";
 }
}
Posted
Updated 28-Jan-22 8:50am
v3
Comments
Richard MacCutchan 28-Jan-22 11:38am    
Remove the line that says
#define NOINPUT

I'm not sure I understand what you want, but here's a guess. If NOINPUT is defined, the following will execute the if statement, with num taking on the values 0, 0, 0, 0, 0, 6, 7, 8, 9, and 10 through the loop. If NOINPUT isn't defined, the user will be asked to input the number.
C++
for(int i = 1 ; i <= 10; i++)
{
   int num = 0;
#ifdef NOINPUT
   if(i > 5)
   {
      //want to execute #else part for remaining iteration
      num = i;
   }
#else
   {
      cout << "Enter a number:";
      cin >> num;
   }
#endif
 
Share this answer
 
v2
Comments
Member 14036158 28-Jan-22 22:49pm    
I want to run 5 times #ifdef section and 5 times #else section while iterating over the given loop.
Greg Utas 29-Jan-22 6:43am    
Ah! Then you need to take out the #ifdef and #endif, and replace the #else with an else.
You should know that #define, #ifdef, #else etc are preprocessor directives. As such they modify the source code before it is passed into the compiler. Given this:
C++
#define NOINPUT
#ifdef NOINPUT
   cout << "foo\n";
#else
   cout << "bar\n";
#endif
by the time the compiler sees it, the source code has been modified to
C++
cout << "foo\n"
The section in the #else part has effectively been removed from the source.

At best guess, it looks like you are trying to execute different parts of your program depending on whether the user has entered a number or not. If that is so, then you can not do this with preprocessor tokens.
 
Share this answer
 
v2
Quote:
I want to skip the #ifdef part on the basis of some condition and want to run #else part.

The slightest change is to replace
C++
#define NOINPUT

with
C++
// #define NOINPUT
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900