I am preparing for an exam in my Intro to C++ class and one thing I have to know if the requirements of an if statement, and requirements of an else if statement. I know How to use these statements, but I'm not sure how to answer this question. Can anyone help me with this?
b. if( condition ) statement_one ; else statement_two ;
The sub-statements statement_one and statement_two implicitly declare a block scope.
The following are equivalent: if( x == 7 ) int y = 2 ; and if( x == 7 ) { int y = 2 ; }
The condition may be either:
a. an expression that is, or can be implicitly converted to bool eg. if( x == 7 ) { /* ... */ }
b. an initialized declaration in a statement where the declared variable is, or can be implicitly converted to bool
eg. if( int x = 7 ) { /* ... */ }
The scope of the declared variable in the condition is the scope of the sub-statements.
eg. if( int x = std::rand() % 7 ) { --x ; } else ++x ;
There is no separate else-if statement in C++. In if( condition ) statement_one ; else statement_two ;statement_one or statement_two could be any statement, including another if statement.
1 2
if( int x = std::rand() % 7 ) if( int y = std::rand() % 7 ) x += y ; else x -= y ;
elseif( int y = std::rand() % 7 ) x -= y ; else x += y ;
Is syntactically equivalent to:
1 2 3 4 5 6 7 8 9 10
if( int x = std::rand() % 7 )
/* statement_one */ {
if( int y = std::rand() % 7 ) { x += y ; }
else { x -= y ; }
}
else
/* statement_two */ {
if( int y = std::rand() % 7 ) { x -= y ; }
else { x += y ; }
}
If statements are basically the highest priority and works to the lowest priority as in else if or else. So basically which ever condition is true in your if statement or else if or else. That will execute. So for example in my program I created. There is 3 password for three different options . Depending on what the user types in as an option it requires a certain password. Following the if and else if and else statement. So if option 1 is equal to choice -> (Menu), then inside the if block the if statement will execute if that condition inside is true, if not it will skip to one that is true, which is the else inside the if block statement. If they choose choice 2, then it will skip the if statement and everything inside that if statement block and head to the else if statement, and from there that block will execute either the if or else depending which condition is true. If they choose choice 3 from the menu then it will skip the two and go to the last else if and it repeats from what I explain. If they decide to choose a number that's not listed in the menu then it will execute the else statement and ignore everything above the else statement. Hope this is what you are looking for friend.