Home > OOP344 > Using && instead of “if statment” in C/C++

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.

Advertisement
Categories: OOP344
  1. Fardad
    February 2, 2010 at 7:43 pm | #1

    Millions of tiny amounts, make big difference…

    • February 3, 2010 at 2:59 pm | #2

      yes, I agree.

      I will create another post that will test it using thousands of characters.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.