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");
}
Related
I want to be able to generate a boolean condition during the runtime based on the states of some variables. My task looks simple at first. I have a large if () else if () statement what needs to determine if the number is in a certain range. It then does something depending on whether that number is inside that range.
Here's pseudocode to demonstrate what I want:
void fun(int num, int offset = 0) {
if (0...60) {
// do something
} else if (60...180) {
// do something else
} else if (180...240) {
} else if (240...360) {
}
}
The first if statement should work like this:
if (0 >= num && num <= 20) {
// do something
}
The caveat here is that in addition to int num, there is another parameter passed in, which I call the offset. The structure of the code here, including the do something inside the { } is the same. The only things that need to change are are ranges, based on the value of the offset. By the way, this is not a default parameter here, it is just pseudocode demonstrating what the value of int offset was passed in.
void fun(int num, int offset = 120) {
if (120...180) {
// do something
} else if (180...300) {
// do something else
} else if (300...360) {
} else if (360...120) {
}
}
That last else if () statement has been giving me some trouble.
} else if (360...120) {
}
What I'm actually trying to write here is:
} else if (num >= 360 || num <= 120) {
}
The reason for this is that my int num may have a value > 360. However, in that case for the purpose of my application it has to "wrap around" and be treated as a value 0...120.
This is for a mathematical application here. Whenever you have int num > 360, you go around the full circle and you end back at 0 where you started. So that is the effect which I want to achieve.
I don't want to write extra functions. I want my code to be generic because many different values for int num and int offset may be passed into my function. I want to generate the necessary conditions during the runtime based on the value of int offset.
The main problem here is that in the first situations, when int offset = 0 my condition is
} else if (240 >= num && num <= 360) {
}
However, for a different offset we wrap around and so I have to change the format of the entire condition! For example, when int offset = 120, as shown above:
} else if (num >= 360 || num <= 120) {
}
The problem is that in the first situation I had the && in the last else if (), but now I have the || to convey the same meaning. What I'm looking for is a way to be able to manipulate the operators inside the conditional statements as mere chars in a string, then "paste" the completed condition into the if () statements during the runtime!
What's even worse is that this "wrapping around" can occur inside any one of the if () statements, not just the last one. It is based on the value of the offset.
I can't use preprocessor tricks, because I want this to work during the runtime. Maybe it is possible to use function pointers or something for this, but I don't know how to do that. Please note that the ... above is not real C++ code, it is pseudocode! I'm aware that there is a "range-based" switch statement in C++, but I can't use that because of the "wrapping around" property mentioned above.
I want to do two string compare and used two different if condition. Is there any better way to do string compare in one if condition
if (strcmp(Buff1(), Config1) == 0)
{
if (strcmp(Buff2, Config2) == 0)
{
// my code goes here
}
}
The equivalent code is:
if ((strcmp(Buff1(), Config1) == 0)) &&
(strcmp(Buff2, Config2) == 0))
{
// my code goes here
}
Note: The compiler should generate the same machine code for both code samples. The difference is cosmetic and primarily aimed at the reader of the code.
You do get a difference when you add else clauses:
if (strcmp(Buff1(), Config1) == 0)
{
if (strcmp(Buff2, Config2) == 0)
{
// my code goes here
}
else
{
// else 1
}
}
else
{
// else 2
}
Compared to:
if ((strcmp(Buff1(), Config1) == 0)) &&
(strcmp(Buff2, Config2) == 0))
{
// my code goes here
}
else
{
// Single else clause
}
In addition to Klas's answer(just in case you're not familiar with the AND operator) - the AND operator ('&&') checks the first condition and it continues to check the second condition -only if- the first condition is true.
So in your specific question, it checks if the first couple of strings are equal and only if true (are equal), it checks if the second couple are also equal.
The obvious optimization (not mentioned yet), if you know anything about those strings, is to first perform the compare that is more likely to fail.
I have a mini program I’m working on for class. The program is of correct syntax. Logically I cannot get the program to compute the remaining data after it completes the first else if statement that it matches.
I am subtracting numbers from each (a >= b) at each else if, the remaining value I am then assigning to a variable temp and using (temp >= c), rinse and repeat till value is zero. Each else if, will assign a char ‘A’ – ‘Z’ depending on the scenario. The problem I am having is it will meet one of the first else if’s but will not continue working the remaining else-ifs. I know this is standard of how if, else works. My question is how would I go about getting the remaining else ifs examined after the first one checks out. Is the only solution to use a switch function? Is there no way I can use if else and have each else checked/passed till my value = 0?
Just forget using else if, use a chain of if statements instead. For example:
bool isThisThree(int number, string &message)
{
if(number == 1)
message = "No, it's a one!";
if(number == 2)
message = "No, it's a two!";
if(number == 3) {
message = "Yes!";
return true;
}
if(number == 4)
message = "No, it's a four!";
if(number == 5)
message = "No, it's a five!";
return false;
}
In this example, the if statements will be examined one by one until the function hits a return statement.
are following code samples equivalent?
This:
while (true)
if (!a[counter] || !b[counter++]) break;
and this:
while (true){
if (!a[counter] || !b[counter]) break;
counter++;
}
i mean, would increment be performed after all conditions' checking done?
Here:
int _strCmp(char* s1,char*s2)
{
int counter = 0;
while (s1[counter]==s2[counter])
if (!s1[counter] || !s2[counter++]) return 0;
if (s1[counter] > s2[counter])
return 1;
if (s1[counter] < s2[counter])
return-1;
return 0;
}
Are there some cases, when this function doesnt work correctly?
No they are not.
Here if !a[counter] returns true the OR'ed condition will not be evaluated.
The second condition in OR is only evaluated if the first condition is false. This is because anything OR'ed with true will be true.
Look at the following image :
As in the image you can see that case 2 is not equivalent
Since the it is incremented post-evaluation (rather than ++counter), the value that will be returned is the value before it is incremented. So, those are equivalent statements.
If counter = 6, then !b[counter++] will return b[6], and then increment 6 to 7.
You could try it yourself changing your code to this:
run = 5;
while (run > 0) {
run--;
if (!a[counterA] || !b[counterA++]) break;
}
run = 5;
while (run > 0){
run--;
if (!a[counterB] || !b[counterB]) break;
counter++;
}
// compare counterA and counterB
EDIT:
Regarding "i mean, would increment be performed after all conditions' checking done?"
No. There are post and preincrement operations. Since you are doing a postincrementation your value would be incremented after it's value was used to evaluate the expression.
Why would you use if-else statements if you can make another if statement?
Example with multiple ifs:
input = getInputFromUser()
if input is "Hello"
greet()
if input is "Bye"
sayGoodbye()
if input is "Hey"
sayHi()
Example with else-if:
input = getInputFromUser()
if input is "Hello"
greet()
else if input is "Bye"
sayGoodbye()
else if input is "Hey"
sayHi()
If you have non-exclusive conditions:
if(a < 100)
{...}
else if (a < 200)
{...}
else if (a < 300)
....
this is very different from the same code without the "else"s...
It's also more performant.
In your first example, every if will be checked, even if input is "Hello". So you have all three checks.
In your second example, execution will stop once it found a branch, so if the user types "Hello" it will be only one check instead of three.
The difference may not be much in your simple example, but imagine that you're executing a potentially expensive function and you might see the difference.
you mean like this:
if (a == true && b == false && c == 1 && d == 0) {
// run if true
}
if (a == false || b == true || c != 1 || d != 0) {
// else
}
An else-statement would be much clearer and easier to maintain.
If you need to chose exactly one action from given set of actions, depending on some conditions, the natural and most clear choice is either switch (don't forget to break after each branch) or combination of if and else. When I write
if (conditon1)
{
action1();
}
else if (condition2)
{
action2();
}
else if (conditon3)
{
action3();
}
.
.
.
else {
action_n();
}
it is clear to the reader that exactly one of actions is to be performed. And there is no possibility that because of mistake in conditions more than one action is performed.
Following your same example if we use sequence of if conditions, whatever the input is it will run all 3 conditions. Replacing sequence of if with if-else conditions will run only first condition in best case whereas all 3 in worst case.
So conclude with that if-else will save our running time in most cases, therefore using if-else is preferred over using sequence of if conditions.
input = getInputFromUser()
if input is "Hello"
greet()
if input is "Bye"
sayGoodbye()
if input is "Hey"
sayHi()