Is there a difference between multiple if statements and else if? - c

If I write
int a = 1;
int b = 2;
if (a == b) {
//Do something
} else if (a > b) {
//Do something else
} else if (a < b) {
//Do something else
}
as opposed to:
if (a == b) {
//Do something
}
if (a > b) {
//Do something else
}
if (a < b) {
//Do something else
}
Is there a difference be it the way the compiler interprets the code or speed? I see no logical difference, but there surely must be a reason why an if else statement exists. It's just a single line break difference.

In the scenario above, they are the same, other than speed. If/else will be faster than a series of ifs, because else statements are skipped if the if condition is satisfied. In a series of ifs, on the other hand, each condition is evaluated separately.
In other scenarios, of course, the logic is not the same, and so replacing if/else with a series of ifs breaks the program. Example:
// this:
if(x <= 0) {
x = 1;
}
else { // only true if x started out > 0
x = 37;
}
// is different from this:
if(x <= 0) {
x = 1;
}
if(x > 0) { // always true in this version
x = 37;
}

In else-if statements, when a condition is met, all other else-ifs are skipped.
Whereas in multiple if statements, it has to go through all of them.
To be more precise, Lets suppose a=b.
Consider your first code block:
int a = 1;
int b = 1;
if (a == b)
{
//Do something
}
else if (a > b)
{
//Do something else
}
else if (a < b)
{
//Do something else
}
While executing, since a=b, it will skip all other conditions (a>b & a<b).
Checks if a=b.
Executes the code block.
All others are skipped.
Consider your second code block:
int a = 1;
int b = 1;
if (a == b)
{
//Do something
}
if (a > b)
{
//Do something else
}
if (a < b)
{
//Do something else
}
Even the first condition is met, all of them will be evaluated.
Checks if a=b.
Executes the code block.
Checks if a>b.
Checks if a<b.

In second type of code you wrote. Compiler will show out put for each true statement and will not skip any condition. Else command is use to make sure that one of two conditions are matched.

the time complexity of if-else statements is less as compared to multiple if statements. Therefore if-else steements are much advantageous

Related

if/else logic using NULL

I'm not sure if I understand the conditionals using = NULL and != NULL.
Is this
if (somethin->example == NULL)
{
do task A
return;
}
else
{
do task B
}
the same as this?
if (somethin->example != NULL)
{
do task B
}
else
{
do task A
return;
}
Yes, they are equivalent.
== is the inverse of !=. If you both invert the condition and swap the if and else blocks the two changes cancel out. These are equivalent:
if (a)
{
foo();
}
else
{
bar();
}
and
if (!a)
{
bar();
}
else
{
foo();
}
Yes. They are the same, the only difference is the order of comparison (is NULL vs. is not NULL)
and the order of operation blocks that go below the if statement based on the conditions written and conditions met.
if (x == y) {
do(x);
} else {
do(y);
}
is the same as
if (x != y) {
do(y);
} else {
do(x);
}
So the difference is that in the first sample we are evaluating that x is equal to y, so precedence of "equal" takes place, while the second sample we are evaluating that x is not equal to y, therefore precedence of "not equal" takes place.

Is there a better way to exit all recursive functions at once, rather than one by one?

Is there a better way to exit all of the recursive iterations immediately after the if(a == b) condition is met, instead of having to include lines 7 and 8 in their current form? Without lines 7 and 8 as they currently are, it seems to exit merely the last iteration.
bool recursive(int a, int b) {
if(a == b)
return true;
for(int i = 0; i < count; i++)
if(locked[b][i] == true)
if(recursive(a, i) == true)
return true;
return false;
}
It's not really critical, but I'd like to spare lines whenever possible. Any ideas?
I would probably write this like so:
bool recursive(int a, int b) {
bool result = (a == b);
for (int i = 0; i < count && !result; i++) {
result = (locked[b][i] && recursive(a, i));
}
return result;
}
Introduction of a variable to hold the working result of the function allows for testing that result as part of the condition for performing a loop iteration. That way you can terminate the loop as soon as the result flips from false to true, yet you don't need any code to distinguish after the fact between the two possible reasons for loop termination.
Yes. You could use a bit obscure functionality of C named longjmp.
It allows to jump back a stack over multiple function calls. A bit similar to throw in C++.
Firstly, return environment is created with setjmp().
It returns 0 if to was a first call to setjmp().
Otherwise it returns a value set by longjmp() called deeper in the recursive call.
#include <stdio.h>
#include <setjmp.h>
void slowrec(int n) {
if (n == 0) {
puts("done");
} else {
puts("go down");
slowrec(n - 1);
puts("go up");
}
}
jmp_buf env;
void fastrec(int n) {
if (n == 0) {
puts("done");
longjmp(env, 1);
} else {
puts("go down");
fastrec(n - 1);
puts("go up");
}
}
int main() {
puts("-- slow recursion --");
slowrec(5);
puts("-- longjmp recursion --");
if (setjmp(env) == 0) {
fastrec(5);
}
return 0;
}
produces:
-- slow recursion --
go down
go down
go down
go down
go down
done
go up
go up
go up
go up
go up
-- longjmp recursion --
go down
go down
go down
go down
go down
done
For original problem the code may look like this:
jmp_buf env;
void recursive_internal(int a, int b) {
if (a == b) longjmp(env, 1); // true
for(int i = 0; i < count; i++)
if(locked[b][i])
recursive_internal(a, i);
}
bool recursive(int a, int b) {
if (setjmp(env) == 0) {
recursive_internal(a, b);
// left without triggering long jump
return false;
}
// returned with longjmp
return true;
}
Note that there is no return value in recursive_internal because either a==b condition is met and longjmp was taken as it was the only way true could be returned. Otherwise, condition was never met and the algorithm exited via return false.

Can I use an if statement as condition in another if statement in C?

Can I do that? I´ve searched for an answer, but I couldn´t found any. What I want to do is this:
if(a==5)
{
printf("25");
}
if((if(a==5))==TRUE)
{
printf("\n30");
}
Is this permissible in C?
Can I use an if statement as condition in another if statement in C?
No, you can´t do that, it isn´t syntactically correct. You would get this or a similar error for the inner if test, if you would attempt to compile code that has any occurrence of that in its source code:
error: expected expression before 'if'
But it is already redundant since you can proof several expressions inside just one if statement´s condition test by using the logic operators &&(AND) and ||(OR):
int a = 5;
int b = 10;
if(a == 5 && b == 10) // If a is 5 AND b is 10. - true
{
/* some code */
}
or
int a = 6;
int b = 10;
if(a == 5 || b == 10) // If a is 5 OR b is 10. - true
{
/* some code */
}
Given your example:
if(a==5)
{
printf("25");
}
if((if(a==5))==TRUE)
{
printf("\n30");
}
The inner if statement inside the condition of the outer if statement - if((if(a==5)) == TRUE) isn´t permissible but also redundant, because an if statement proofs on its own whether the condition or a sub-expression is true or not.
Thus, if((if(a==5)) == TRUE), if((a==5) == TRUE) and if(a==5) would be all equivalent, if a if condition test inside the condition of another were permissible and the if statement shall somehow be evaluated to 1.
So even in this surreal case, the code in the example would be equivalent to:
if(a==5)
{
printf("25");
printf("\n30");
}
This
if(a==5)
{
printf("25");
}
if((if(a==5))==TRUE)
{
printf("\n30");
}
can be rewritten this way with keeping the same logic
int condition;
if( ( condition = a == 5 ) )
{
printf("25");
}
if( condition )
{
printf("\n30");
}

Implementing loops on the basis of condition in C

I have a set of statements that need to be executed in two different loops; the loops identified on the result of a check condition. There are multiple such sets of this type.
Set A : statement 1
statement 2
statement 3
Set B : statement 4
statement 5
statement 6
and so on..
Now they need to be executed as follows:
if(condition 1)
loop over some Loop A
execute Set A
else if(condition 2)
loop over some loop B
execute Set A
These loops can be completely different from each other.
Now, for the sake of code clarity, I don't wish to write the code as mentioned above. Another reason being I'll have to make multiple sets in order to group them together.
Is there any mechanism by which I could achieve the following:
CHECK_CONDITION_AND_LOOP_HERE
execute Set A
I've tried using macros to achieve this, using braced-group within expression but could not . I also tried using ternary operators as well as fall through a switch case to achieve this, but could not get the same result.
Is there any way in C using which I could achieve the desired behavior?
Sample code for the problem:
if(condition A)
for(i=0; i<10; i++, k*=2) {
execute Set A; //Operations performed here use variable k
}
else if(condition B)
for(j=5; j<75; j+=5, k*=arr[j]) {
execute Set A; //Operations performed here use variable k
}
The answer to Version 1 of the question:
Given that the only difference is the range of values over which the statements are executed, you can use a couple of variables to store the range end-points, e.g.
int first = 0;
int last = -1;
if (condition1) {
first = 1;
last = 10;
} else if (condition2) {
first = 3;
last = 7;
}
for ( int i = first; i <= last; i++ )
execute set A
Note that initializing last to be less than first prevents the body of the loop from running if neither condition is met.
The answer to Version 2 of the question:
Here's the code from the question. I've made some changes for clarity, and to make the question more concrete.
if (cond1)
for (initA;condA;updateA)
execute SetX
else if (cond2)
for (initB;condB;updateB)
execute SetX
Here's the refactored code
int is1 = cond1;
int is2 = is1 ? 0 : cond2;
if (is1)
initA;
if (is2)
initB;
while ( (is1 && condA) || (is2 && condB) )
{
execute SetX
if ( is1 )
updateA;
if ( is2 )
updateB;
}
A function, maybe?
void func_A() {
printf("Here0\n");
printf("Here1\n");
}
...
if(a < b) {
for(i = 1; i <= 10; i++) {
func_A()
}
}
else if(a == b) {
for(i = 3; i <= 7; i++) {
func_A()
}
}
Or if you want to only make one call/block:
if(a < b) {
min = 1; max = 10;
}
else if(a == b) {
min = 3; max = 7;
}
for(i = 3; i <= 7; i++) {
printf("Here0\n");
printf("Here1\n");
}

Changing the if statement into a while statement

I'm trying to change an if statement into a while statement.
For example
int A=1; if(A==1){};
is similar to int A=1 while(A!=1).
My If statement has no codes, I just need it to do nothing in order to avoid the else-if statements.
My If statement is inside 1 While statement and 1 If statement.
So I want the program to do the same thing in the while statement rather than going in 1 While statement and 1 If statement with an If statement with no code.
Original codes something like this
while(C1)
{
if(C2)
{
if( h->data[temp] < h->data[temp*2] && h->data[temp] < h->data[temp*2+1] )
{
break;
}
else if(C4)
{
DO();
}
}
}
I've changed it to
while( C1 && h->data[temp] > h->data[temp*2] && h->data[temp] > h->data[temp*2+1] )
{
if(C2)
{
if(C4)
{
DO();
}
}
}
and the result is different. The original code gives the correct result but the changed code gives an incorrect result. I've only changed the location to if to while and also changed the direction of the < operator to the > operator.
The total code seems like I've spent less effort in it, making down votes. So I'm posting the code somewhat like a pseudo code.
For example int A=1; if(A==1){}; is similar to int A=1 while(A!=1).
As already mentioned, your loop is breaking. The above statement is also incorrect.
int a = 1;
if(a == 1) {} //this is true, and will happen once
BUT
int a = 1;
while(a != 1) {} //false on entry, skip loop ( never entered )
You could also consider a switch / case if you can isolate the condition.
This might achieve your goal of removing the ifs, and make the code more readable.
e.g
int a = 1;
while(a)
{
switch(a)
{
case 1: ++a; continue;
case 2: do();
default: break; //end loop
}
}
In the original code, if (for example) h->data[temp]>h->data[temp*2] were false, DO() wouldn't be executed, but the loop would continue. In the new version, the loop would stop.
As others said, there is no reason to obfuscate the code with an extra while statement; the original is perfectly clear. There is also no need for the else in your original:
while(C1)
{
if(C2)
{
if( h->data[temp] < h->data[temp*2] && h->data[temp] < h->data[temp*2+1] )
{
break;
}
if(C4)
{
DO();
}
}
}

Resources