Suppose we have this code:
if (condition_1)
do this
if (condition_2)
do that
else
do blablabla
And now this one:
if (condition_1)
do this
else if (condition_2)
do that
else
do blablabla
And now let's check what happens line by line. If i'm not mistaken, the first program starts checking if condition_1 is true or false, then the same thing happens for condition_2. And if none of these conditions are true, the program runs "do blablabla".
The second program starts from checking condition_1, and if it's false then if checks condition_2. If condition_2 if false, if does nothing (by nothing i mean it ignores the else statement).
If so, the second if statment from the second program can be replaced by:
if (!(condition_1) and condition_2)
do that
But else then can be run, i thought that every else if statement can be replaced by only if with a bit longer condition. So is this possible to replace every else if by using only if? And when "do blablabla" will run?
First part:
if (condition_1)
do this
// previous if has nothing to do with this if & else
if (condition_2)
do that
else
do blablabla
This case if condition_2 is true then do that will be executed, otherwise do blablabla
will be executed..
Now the second part:
if (condition_1)
do this
else if (condition_2)
do that
else
do blablabla
Here, the first true condition will be executing and rest of else if & else will be ignored, all conditions will be checked sequentially till else or a true condition is found.
If no conditions hold then else will be executed. So do blablabla will be executed if those both of two conditions are false
And finally, yes second if can be replaced by:
if (!(condition_1) and condition_2)
do that
This is because second if will be checked (do that will be executed) only if the condition_1 is false.. and condition_2 is true.
Which is equivalent to: (if and only if the condition_1 is false)
if (!(false) and condition_2)
do that
You can replace else ifs by checking whether previous condition was false, this way each else ifs with previous conditions, this is tedious.
Example:
if (a) {
// do task1
} else if (b) {
// do task2
} else if (c) {
// do task3
} else {
// do task4
}
Is equivalent to:
if (a) {
// do task1
}
if (!a and b) {
// do task2
}
if (!a and !b and c) {
// do task3
}
if (!a and !b and !c) {
// here is the else
// do task4
}
When to use else if instead of if?
Generally speaking, we chain if, else if's and an else at the last to ensure execution of only one condition, if one is true rest are ignored and executions goes to the next of very last line ( } ) of last else.
If i'm not mistaken, the first program starts checking if condition_1 is true or false, then the same thing happens for condition_2. And if none of these conditions are true, the program runs "do blablabla".
No, condition_1 does not influence what happens in condition_2. condition_1 can be either true or false but it's only condition_2 that matters in the second condition:
if (condition_1) {
do this
}
// --- no connection here ---
if (condition_2) {
do that
} else {
do blablabla
}
It's different in the second version since then condition_1 must be false for condition_2 to be even evaluated. It helps to put curly brackets out:
if (condition_1) {
do this
} else {
if (condition_2) {
do that
} else {
do blablabla
}
}
Related
I have three conditions (a, b, c) to be checked that's supposed to run on the folliwing syntax:
if (conditionA)
{
if (conditionB && conditionC)
{
// Execute();
}
}
else if (conditionC)
{
// Execute();
}
Better still, can these conditions be simplified to one line, so that Execute() will end up in one set of braces? Thanks.
The first condition can be simplified to if (conditionA && conditionB && conditionC)
unless there is some processing or conditionB/conditionC are calculated between the first if and the second.
If the conditions are all available up front you could do something like:
if((conditionA && conditionB && conditionC)||(conditionC))
{
// Execute();
}
This will look at the first set of inner braces (conditionA && conditionB && conditionC) which will only return true if A, B and C are all true, then evaluate conditionC and if either of these return true, it will enter into the block and perform the Execute() function.
I don't quite understand the meaning of else if statements.
why not just to continue with the if statements in case one is false?
it works the same.
example with if only that will work the same with else if:
function testSize(num) {
if (num < 5){
return "Tiny";
}
if (num < 10){
return "small";
}
return "Change Me";
}
testSize(7);
In your actual code you specify a return statement in the code associated to the if statement.
Suppose you don't specify a return statement or suppose today you specify a return statement but tomorrow you remove it to do a common return at the end of the method.
This code will test each condition even if the first one is true :
if (num < 5){
// do something
}
if (num < 10){
// do something
}
This code will not test the next condition if the first one is true :
if (num < 5){
// do something
}
else if (num < 10){
// do something
}
These two ways of doing have two distinct meanings.
When you have a series of if statements, you expect that more than one condition may be true.
When you have a series of if-else-if statements, you expect to have not more than one condition true.
Using the first form (a series of if) while functionally you expect to have not more than one condition true is misleading.
Besides, if the code is modified and you add a condition that is both true for two if statements while you don't want have this case, it would create an issue.
Your code is only showing your belief. What would happen in the example below?
function testSize(num) {
if (num < 5){
x = 1;
}
if (num < 10){
x = 2;
}
result = complex calculations;
}
function testSize2(num) {
if (num < 5){
x = 1;
} else if (num < 10){
x = 2;
}
return x * 2;
}
testSize(4); // result is 4
testSize2(4); // result is 2
x may also be involved in more calculations
if(condition) {...}
if(condition) {...}
if(condition) {...}
In above code, even if the first or second condition is true, third condition have to be checked.
if(condition) {}
else if(condition){}
else if(condition){}
Here if first condition is true, next two will not be checked. So, it saves time and is more readable logically.
A one way if statement takes an action if the specified condition is true.If the condition is false, nothing is done. But what if you want to take alternative actions when the conditions is false ? You can use a two-way if-else statement. The action that a two-way if-else statements specifies differ based on whether the condition is true or false.
Well, there is a bit different from this two statement.Consider the follow samples
if(a > 0) {
...
}
if( a == 0) {
...
}
if(a < 0) {
...
}
and
if(a > 0) {
...
}
else if( a == 0) {
...
}
else if(a < 0) {
...
}
when a is zero the last else if statement will not be execute while if need to compare third time.If a equals to 10, else if could be execute once while if is third.From this else if statement could be execute less and let your program a bit fast.
else if should be used when there are multiple conditions and you want only one of them to be executed, for instance:
if(num<3){ console.log('less than 3') }
else if(num<2){ console.log('less than 2')
If you use multiple if statements instead of using else if, it will be true for both the conditions if num = 1, and therefore it will print both the statements.
Multiple if statements are used when you want to run the code inside all those if statements whose conditions are true.
In your case it doesn't make a difference because the function will stop and return at the very first return statement it encounters. But let's say, the blocks' orders are interchanged, then your function will never return 'tiny' even if num = (anything less than 5).
I hope that helps!
If all your if branches terminate the function (e.g., but returning a value of throwing an exception), you're right, and you really don't need an else statement (although some coding standards might recommend it).
However, if the if branches don't terminate the function, you'd have to use an else or else if clause to prevent multiple blocks from being executed. Assume, e.g., you want to log a message to the console instead of returning it:
if (num < 5) {
console.log("Tiny");
} else if (num < 10) {
console.log("small");
} else {
console.log("Change Me");
}
I am trying to find out if it's possible to have a set of test inputs that achieves 100% condition coverage for the following code.
bool a = ...;
bool b = ...;
if (a == True){
if (b == True && a == False){
...
} else{
...
}
} else{
...
}
However, most of the resources I have found only deal with one condition. Therefore I am not sure what to do with nested ifs. Specifically, I am not sure what to do with the second if statement. Since "a == False" should never be true given the outer if statement, is it correct to say that this code can never have 100% condition coverage test cases?
No, it's not possible: (b == True && a == False) will never be true, since it's inside a block
if (a == True)
a can't be true and false at the same time. Either there is a bug, or you have dead code that should simply be removed. And then, you can have 100% coverage.
I am experiencing troubles with what I suspect to be while loops. I am working on building a simple game, and I think my two while loops are interfering with eachother somehow. here's the main function! Thanks in Advance!:
int main( int argc, char* argv[])
{
SDL_Startup();
while(Playing == false && quit == false)
{
StartingScreen.input();
StartingScreen.render();
character.input();
SDL_Flip( screen );
SDL_Delay(1000/FPS);
}
while(Playing == true && quit == false)
{
CAMERAGUY.Camera();
character.input();
character.adjust();
SuperSnail.move();
SuperSnail.attack();
TheWall.boundaries();
TheWall.render();
SuperSnail.render();
character.render();
character.reset();
HUD.render();
SDL_Flip(screen);
SDL_Delay(1000/FPS);
cout << StartingScreen.x << endl;
}
if(Playing == false)
cout << "Playing == false" << endl;
if(quit == true)
return 0;
}
So the bool playing is set to false to begin with, and is set to true when my character runs out of lives. so when Playing is set to false in the second loop, it doesn't repeat the first loop. I JUST thought, I think maybe it would work if I put the two loops in a separate loop.
I've edited your code with comments to explain what it is doing (and why it is not behaving as you expect):
int main( int argc, char* argv[])
{
SDL_Startup();
// Set `Playing` to false
while(Playing == false && quit == false)
{
// Do stuff which applies when `Playing` is false
//
// At some point, set `Playing` to true, so that
// the loop ends
}
while(Playing == true && quit == false)
{
// Now do stuff which applies when `Playing` is true
//
// At some point, set `Playing` to false, so that
// the loop ends
}
// Both loops have come to an end, and there
// is no code to return to the first loop
// so execution continues below:
// This line always executes because `Playing` is always false
// by this point:
if(Playing == false)
cout << "Playing == false" << endl;
// This conditional statement doesn't do what you think, because
// in the case that `quit == false`, the end of your `main` function
// is reached and returns 0 by default, meaning that the outcome
// is the same no matter what the value of `quit`
if(quit == true)
return 0;
}
The solution: enclose the both loops in a while(quit == false) loop. This means that both when the second loop completes, the first loop will be evaluated again, until you are ready to stop execution by setting quit to true.
A few other tips:
A neater way of expressing quit == false is !quit.
A neater way of expressing Playing == true is Playing.
Using global variables in the way that you are is almost certainly a bad idea, and you should probably rethink your design.
It is pretty simple. In your current implementation you will never return to your first while loop if your second loop is finished, because you reach the return of your main routine.
I guess you should always use only one main loop for your game.
What is the difference between:
if (expr1) {stmt}
else if (expr2) {stmt}
else if (expr3) {stmt}
else {stmt}
And the same code block written as:
if (expr1) {stmt}
if (expr2) {stmt}
if (expr3) {stmt}
else {stmt}
In the first one, each block of statements is mutually exclusive; the structure guarantees that exactly one of them will get executed.
This is not true for the second one. Consider:
if (a == 2) { /* blah */ }
if (a == 3) { /* blah */ }
if (a < 5) { /* blah */ }
If a == 2, then two of the blocks will get executed.
Here's another good example to see how this works.
This example will print "FirstSecond":
if(1) {
printf("First");
}
if(1) {
print("Second");
}
This just prints "First":
if(1) {
printf("First");
}
else if(1) {
print("Second");
}
In your first code, at most ONE of the blocks can be executed.
In the second code, all of the blocks could be executed. (Except for the last else-thing.)
In the first case exactly one of the blocks will be executed. In the second, the first and second blocks may or may not be executed and exactly one of the last two blocks will be executed.
For the best performance choose a if else (if possible).
You can also use a switch case statement.
For example if condition1 == true and condition2 == true the first block(else id) will execute only some statements#1 and the second block would execute both some statements#1 and some statements#2.
When you use else if the program would stop matching next conditions after first matched. It would be slightly faster on runtime if conditions are exclusive(i'm not sure if it's right word).
With:
if (expr1) {stmt1}
else if (expr2) {stmt2}
else if (expr3) {stmt3}
else {stmt4}
One and only one of the statements can be executed.
With:
if (expr1) {stmt}
if (expr2) {stmt}
if (expr3) {stmt}
else {stmt}
Either, both, or none of the first and second sections will be executed. In the last if-else section, either stmt3 or stmt4 will be executed.