Playing with C

Since I was introduced to programming I have been fascinated by the small trick that can improve a program. Some of them are related with shortening the size others are related to improve the speed of the program. In C the for loops are usually used to interact trough vectors, it's made to be easily readable on that function. For example, when we want to use a for loop to run we normally would write something like:

int i;
for( i = 0 ; i < MaxNumber ; i++)
   {
      something();
   }

this will set the variable i to zero and after that enter in a loop. This loop will start by checking if i is less than MaxNumber, if it is it will do what is inside the brackets (in this case is just the something() function), if it isn't it will break out of the circle and by the end of the cycle increase the value of i by one. This seems pretty strait forward and effective, but by writing it as:

int i;
for(i = MaxNumber ; i-- ; )
    {
       something();
    }

we can improve the speed of this program by taking advantage on the way i-- works and the way a condition is considered true or false in C. The difference between i-- and --i is that when one of them is checked the i-- will return the value of i before decreasing it and the --i will first decrease the value of i and only after that return its value. Besides this, the way C checks if a condition is false is if its value is zero, other than that it is evaluated as true. So, now it starts by setting i as MaxNumber before the cycle begins and in the cycle it will starts by checking if i-- is true, after that it decreases the value of i by 1 and do whatever is inside the brackets. Because during the last step i will be evaluated as 1 before it is decreased the last desirable step will still be performed.

The speed improvement in this post is minimal(very minimal, mostly negligible) and there will be a decrease on code readability.

Comments

Popular posts from this blog

The struggle continue

C weird behaviour