MESSAGE
DATE | 2010-03-16 |
FROM | Ruben Safir
|
SUBJECT | Subject: [NYLXS - HANGOUT] C++ Workshop _ Syntax Basic: Flow Control Structures
|
In addditon to loops, C++ allows for conditional forks. The keywords "if" and "else" allow for complex decision making trees on condition. The general syntax is as follows:
if (conditional statement){ block statements; block statements; block statements; }else{ block statements; block statements; block statements;
}
"if"s and "else"s can also be combined into a further compound statement:
if (condition){ block statements; block statements; block statements; }else if(condition){ block statements; block statements; block statements; }else{ block statements; block statements; block statements; }
This is what I would call a closed logical contruction. One of the must be true. YOu can have an open logic construction as well, but then it is up to you to control the outcome
if (condition){ block statements; block statements; block statements; } if (condition 2){ block statements; block statements; block statements; } if (condition 3){ block statements; block statements; block statements; }
In order to help you control your loops, C++ gives you two keywords to stop and start loops: break and continue
break: The break statement stops the nearest enclosing loop or switch statement (we'll look at the switch statement in a moment). Once you use a break then the loop end and program control continues with the first statement after the loops curly braces.
continue: continue ends the current iteration in a loop and then reevaluates the condition and continues within the loop.
The program demonstrates the break and continue statements. It is a very rough clock which counts down some "event". The unix enviromental variable ALERT is accessed and evaluated. If it is equal to "WAIT", the countdown is held. If it is STOP, the countdown is ended.
To make this work and to test it you have to add the variable in your shell and export it
ALERT="GO" export ALERT set|grep ALERT
-----------------------------------------------------------------------
#include #include #include #include
using namespace std;
int main( int argc, char * argv[]){
//count like a clock // int sec = 59; int min = 59; int hour = 24; int breakflag = 0;
cout << "Countdown: Time " << hour << ":" << min << ":" << sec << endl; while(hour >= 0){ if (min < 0){ min = 59; } while(min >= 0){ if (sec < 0){ sec = 59; } while (sec >= 0){ cout << "Time " << hour << ":" << min << ":" << sec << endl; if(char * alert = getenv("ALERT")){
if(strncmp(alert,"WAIT", 10) == 0){ sleep(1); continue; } if(strncmp(alert,"STOP", 10) == 0){ cout << "Count Down Aborted\n"; breakflag=1; break; } } if(breakflag == 1) break; sec--;
sleep(1); } if(breakflag == 1) break; min--; // cout << "min\n"; } if(breakflag == 1) break; hour--; // cout << "hour\n"; } }
|
|