Why use if-else if in C++? - c++

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()

Related

Is it good practice if container's size is validated and accessing an element under same conditional statement?

Which one of the following code is more preferable between two of them and why?
1.
std::stack<int>stk;
//Do something
if( stk.empty() == true || stk.top() < 10 )
{
//Do something.
}
or
2
std::stack<int>stk;
//Do something
if( stk.empty() == true )
{
//Do something.
}
else if( stk.top() < 10 )
{
//Do something.
}
Builtin operators && and || perform short-circuit evaluation (do not evaluate the second operand if the result is known after evaluating the first). So, expression stk.empty() || stk.top() < 10 is safe and good practice, stk.top() is only called if stk.empty() evaluates to false. In other words, the operators were designed to enable such usage.
It entirely depends on the use case. In the first code, you have an OR condition for empty stack and checking the value of element if an element exist. So, it's clear and you can proceed with the code.
In the 2nd code, you want to execute something different for both the conditions. Hence you have put the conditions in a if else loop.
Good practise comes into sense when you don't want your code to break or pass corner test cases.You might not wan't something in your code when the stack is empty.
std::stack<int>stk;
if(stk.top() < 10 )
{
//Do something.
}
else if(stk.empty() == true)
{
//Do something
}
This will generate run time error since the stack is empty but you are accessing top element before checking the stack empty condition.
Snap of the error
I hope the answer makes it clear.

what is the use of if else statements?

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");
}

Qt String Comparison

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

Optimized code for two string compare in if condition

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.

Check multiple OR operators in IF statement

I have the following C++ code:
if(x==y||m==n){
cout<<"Your message"<<endl;
}
If x is equal to y or m is equal to n, the program prints "Your message". But if both conditions are true,the program tests only one of them and eventually prints one "Your Message".
Is there a way to print each "Your message" independently based on each condition using a single if statement?
The output would be identical to the below using multiple if statements.
if(x==y){
cout<<"Your message"<<endl;
}
if (m==n){
cout<<"Your message"<<endl;
}
Not that I'd ever do it this way, but ...
for(int i = 0; i < (x==y)+(m==n); ++i) {
std::cout << "Your message\n";
}
Let me expand on this. I'd never do it this way because it violates two principles:
1) Code for maintainability. This loop is going to cause the maintainer to stop, think, and try to recover your original intent. A pair of if statements won't.
2) Distinct input should produce distinct output. This principle benefits the user and the programmer. Few things are more frustrating than running a test, getting valid output, and still not knowing which path the program took.
Given these two principles, here is how I would actually code it:
if(x==y) {
std::cout << "Your x-y message\n";
}
if(m==n) {
std::cout << "Your m-n message\n";
}
Aside: Never use endl when you mean \n. They produce semantically identical code, but endl can accidentally make your program go slower.
I don't think that's possible. What you have inside your bracket is a statement which is either true or false, there's no such thing like a true/true or true/false statement. What you could do is a do/while loop with a break statement. But I don't think that's the way to go. Why do you want to avoid two if statements?
single "|" or "&" gaurantees both side evaluation even if the result can be determined by left side operator alone.
You could do something like this, to build up the "message":
string msg = "Your Message\n";
string buildSt = x == y ? m == n ? msg + msg : msg : m == n ? msg : "";
Compiler checks only one condition when both are true because you've connected your conditions with OR.
If even one condition in ORs chain is true there is no need to check others as a result already true and will be false if one of them is false. So if you think that your logic is right then there is no need to do multiple checks. Your code is asking that you will print a message if one of the conditions is true and program doing it. If you want something special for a case when both conditions are true then add it separately. Shortly you should never expect from the compiler to do all checks in the expressions connected by OR.
Regards,
Davit
Tested code:
#include <iostream>
#include <string>
using namespace std;
void main() {
int x=1;
int y=1;
int m=1;
int n=1;
string mess1="Your message 1\n";
string mess2="Your message 2\n";
cout<<((x==y)?mess1:"")+((m==n)?mess2:"");
getchar();
}
If you are trying to see if both statements are true an && is what you will want to use.
Take a look at Boolean Operators to see all of the possible options when comparing boolean (true/false) values.
To answer your question:
if ((x==y) && (m==n))
{
cout<<"Your Message"<<endl<<"Your Message"<<endl;
}
else if((x==y) || (m==n))
{
cout<<"Your Message"<<endl;
}