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?
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
elseif(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
elseif(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.
Thanks for the reply. But actually I want to use, if there exists, something different from basic control structure like ifelseif. Because in each block there are a lot of code, already including several levels of control structures. Like:
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;
elseif(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;
}
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();
elseif(a > 0)
blockA()
//Rest of code
}