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.
Related
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
}
}
Suppose I have:
QString x;
Is the following code fragment:
if(x.compare("abcdefg") == 0){
doSomething();
}
else{
doSomethingElse();
}
... functionally equivalent to:
if(x == "abcdefg"){
doSomething();
}
else{
doSomethingElse();
}
I could prove this for myself by writing a fairly trivial program and executing it, but I was surprised I couldn't find the question / answer here, so I thought I'd ask it for the sake of future me / others.
QString::compare will only return zero if the string passed to it and the string it is called on are equal.
Qstring::operator== returns true if the strings are equal otherwise, false.
Since compare only returns zero when the strings are equal then
(qstrign_variable.compare("text") == 0) == (qstrign_variable == "text")
If qstrign_variable contains "text" in the above example. If qstrign_variable contains something else then both cases evaluate to false.
Also note that std::string has the same behavior
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 this code...
void drawMap(void)
{
if (false)
return;
for(auto iter = this->m_layers.begin(); iter != m_layers.end(); ++iter)
{
if ((*iter)->get() == NULL)
continue;
PN::draw((*iter)->get(), b2Vec2(0,0), true, 0);
}
}
If I'm not mistaken it should NEVER execute...but it does...and when I change
if (false)
return;
to
if (false)
return;
else
return;
it doesn't execute at all now, but how can that first statement NOT be false? grabs headache pills
P.S. I only did this 'cause I was debugging and noticed my code was drawing to the screen when it wasn't supposed to.
if (false) will never execute its body... because the value of the condition is never true. So in the code you've given, the remainder of drawMap will always execute because it will never return at the start.
Consider if (x == 5) - that will only execute if the expression x == 5 is true. Now substitute false for x == 5...
If you want an if statement which will always execute, you want
if (true)
instead.
Count me in with the crowd that didn't actually read the problem well enough, or couldn't believe that the OP didn't understand the problem if it were so simple :)
John Skeet's answer, of course, was spot on :)
Two thoughts:
If you're in a debugger, lines can appear to be executed, out of order, not at all or at unexpected lines when compiled with optimizations. This is because some machine instructions will get 'attributed' to different source lines. Compile without optimization to eliminate the source of confusion. It is confusing only, as optimizations should (! barring compiler bugs) not alter effective behaviour
It could be that you're getting an evil #define for false that you cannot trust. Rule this out by running the code through preprocessor only. g++ -E will do that. MSVC++ has an option to 'keep preprocessed' source
Blockquote
if (false)
is analagous to
if (1 == 2)
and will therefore never execute the next statement (or block).
In your context consider the following comments I made:
void drawMap(void)
{
if (false) return; //Not gonna happen.
//The following will always happen
for(auto iter = this->m_layers.begin(); iter != m_layers.end(); ++iter)
{
if ((*iter)->get() == NULL)
continue;
PN::draw((*iter)->get(), b2Vec2(0,0), true, 0);
}
}
I have seen the usage of this if(false), in a switch / case like construction like this:
int ret = doSomeThingFunction();
if (false) {}
else if (ret < 0 ) {
}
else if (ret == 0) {
}
else if (ret > 0) {
}
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()