Control execution of code block by entry

Hi,

I have a program including several code blocks in the following simplified structure:
1
2
3
4
5
6
7
8
9
10
11
int main() {
   // block A
   if(a > 0) {

   }

   // block B
   if(a > 1) {

   }
}

Block A and B should be executed separately, according to entry from keyboard. For example, if entry "1", block A will be executed and block B will be ignored; if entry "2" the inverse will happen.

I can control the execution of these two blocks through macro but the code will be separated during compilation. But is there a way to control them without using macro?

Thanks in advance!
So if block A executes, you don't want block b to execute? And if block B executes you don't want A to execute? If that's the case, do this:

1
2
3
4
5
6
7
8
9
10
11
int main() {
   // block A
   if(a > 0) {

   }

   // block B
   else if(a > 1) {

   }
}


Also, you'll want to switch them around so that the larger one is first. Since 2 will be larger than both 0 and 1 it will always execute, but if you do this:

1
2
3
4
5
6
7
8
9
10
11
12
int main() {
   // block B
  if(a > 1) {

   }

  //block A
   else if(a > 0) {

   }

}


it will not. It will check the first if, it it's ok then it goes on. The else if means if it did NOT meet the first check so it won't get executed. If it is, however, less than 2 it will execute the else if part.

Here's a little page on if/else statements :D
http://gd.tuwien.ac.at/languages/c/programming-bbrown/c_025.htm

Hopefully that's what you want!
Last edited on
Thanks for the reply. But actually I want to use, if there exists, something different from basic control structure like if else if. Because in each block there are a lot of code, already including several levels of control structures. Like:
1
2
3
4
5
6
7
   if(a > 0) {
      if(x == 1) {
         while(y != 1) {
            if() ...
         }
      }
   }

That's why I don't want to add one more structure.
I think that's basically all you got. :D If you want to, you can use a struct statement instead. If you really want to be a rebel, you could do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main() {

  if(a > 1) goto block_b;
  else if(a > 0) goto block_a;

  block_a:
    //code goes here
    goto end

  block_b:
    //code goes here
    goto end

  end:
    //cleanup and exit code here
    return 0;
}
Last edited on
Do not use goto. It messes up program order and this is clearly not the case when you should use it.
You can move large blocks of code into separate functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void blockA()
{
    //Block A code
}

void blockA()
{
    //Block A code
}

int main() 
{
  if(a > 1)
    blockB();
  else if(a > 0)
    blockA()
  //Rest of code
}
Topic archived. No new replies allowed.