Bools & Ifs
True/False C++ bool type Two values: true & false
True/False C++ bool type Two values: true & false Printed as 1 and 0
True/False C has no bool C++ converts numbers to bools in same way: Uses integers : 0 = false, all others = true C++ converts numbers to bools in same way:
Relational Operators Relational operators : Binary operators – compare two values Evaluate to true or false
Relational Evaluation Can store result of relational operator: bool result = 5 < 9; cout << result; Outputs 1 (true) bool result = 5 == 9; cout << result; Outputs 0 (false)
Control Structures Normal execution is sequential Control structures Selection (branching): making a choice Repetition (iteration): looping
Conditional If syntax: if( expression ) statement;
If Example Indent statement! int grade; //read grade if(grade < 60) cout << "F"; Indent statement!
Evil Error 1 if(grade < 60); cout << "F";
Evil Error 1 if(grade < 60); cout << "F"; Always prints F If grade < 60 do empty statement (;) No matter what, print F
Evil Error 2 if (x = 5) cout << "Is 5" << endl;
Evil Error 2 if (x = 5) cout << "Is 5" << endl; Changes x to 5 Value of assignment is 5 true Linux Hack Attempt: if ((options == (__WCLONE|__WALL)) && (current->uid = 0))
Evil Error 2 Yoda style (constant first) prevents this error: if (5 == x) cout << "Is 5" << endl;
Two-Way Selection Two-way selection syntax: if( expression ) statement1; else statement2; Exactly one statement executes
Example int grade; //read grade if(grade < 60) cout << "F"; else cout << "Pass";
Evil Error 3 if(grade >= 60); cout << "Pass"; else cout << "You shall not pass"; cout << "try again";
Evil Error 3 Always prints "try again" if(grade >= 60); cout << "Pass"; else cout << "You shall not pass"; cout << "try again"; Always prints "try again" Else only applies to next statement!
Compound (Block of) Statements Compound statement (block of statements): Surrounded by { } Acts as one statement
If Example Indent statements! Else with multistatement block int grade; double credits; //read grade if(grade < 60) cout << "F"; else { credits += 4; cout << "Pass"; } Indent statements!
Example Use { } with if/else to group statements: if(grade < 60) creditsEarned = 0; cout << "F"; //always executes Need { } to group instructions: if(grade < 60) { credits += 0; cout << "F"; }
Block Guides Never hurts to put { } around if/else body: if(grade < 60) { cout << "F"; //this is fine }