Using && instead of “if statment” in C/C++
C/C++ is a lazy language. It will only execute code when it has to! When using AND if the first condition is false it will skip the second one. The first example below uses an if statement and the second one uses AND which is a little faster.
#include <stdio.h>
int main(){
int number[10] = {5, 1, 8, 3, 6, 5, 3, 8, 4, 6};
int i = 0;
while(i < 10){ if(number[i] > 5)
printf(“%d\n”, number[i]);
i++;
}
return 0;
}
The above program takes 0m0.004s to execute.
The program below is using “AND” instead of if statement
#include <stdio.h>
int main(){
int number[10] = {5, 1, 8, 3, 6, 5, 3, 8, 4, 6};
int i = 0;
while(i < 10){ number[i] > 5 && printf(“%d\n”, number[i]);
i++;
}
return 0;
}
The program above executes in 0m0.003s
Using AND can have some performance advantage over if statements, but it is only faster by a tiny amount.
Millions of tiny amounts, make big difference…
yes, I agree.
I will create another post that will test it using thousands of characters.