Teens party – empty if statement
Understanding the behaviour of if when nothing is done when if condition is true.
Learning Objectives
- Learning to use a lone ; when in the true portion of selection condition we do not want to do anything.
Source Code
|
Run Output
Code Understanding
if(age<=19 && age >=13) ;
Here no output is shown or no variable is set when the condition is found true. We just put a ; after the if selection to indicate an empty statement.
else cout<<“Sorry! only teens allowed.”<<endl;
This is displayed when selection condition is not true.
Notes
- Sometimes empty statements are also used by programmers while developing a code where the statements for a particular block are not final.
- If else condition is empty then the entire else block can be removed instead of writing an empty condition.
- Empty condition can be often avoided by reversing the logic of condition. For e.g. above code can also be written as (without any empty block and without the else condition).
if(age>19 || age<13) cout<<“Sorry! only teens allowed.”;
Common Errors
- Sometimes programmers confuse between use of && and || between two conditions. Remember that when the range of true values is within the given first and second conditions && is used. When the values are outside first and second condition || is used.
sunmitra| Created: 27-Dec-2017 | Updated: 28-Nov-2018|