Wednesday, 22 January 2014

C PROGRAMMING TRICKS

C Programming Tricks:

1.

Always try to compare like

if ( 0 == i )

rather than

if ( i == 0)

In this way you can catch error for unintended assignments like

if ( 0 = i) .


2.

Dont use strlen in a loop condition:

The strlen function is expensive. For every call it must loop over every character in the input string until a nul terminator is found. Therefore, it is very unwise to call it more often than needed. This is bad code:

for ( int ix = 0; ix < strlen(a_str); ix++)
{
     a_str[ix] = tolower( (unsigned char) a_str[ix] );
}


Lets consider a string 1000 characters in length. strlen will be called 1001 times and loop over 1000 characters each time. That is over one million wasted iterations. If the tolower call and assignment takes the equivalent of 10 iterations we can calculate that the operation takes one hundred times longer than it would if written correctly.

strlen as a loop condition should be replaced with:

for ( int ix = 0; a_str[ix] != '\0'; ix++)
{
     a_str[ix] = tolower( (unsigned char) a_str[ix] );
}


or the slightly less efficient:

int len = strlen(a_str);
for ( int ix = 0; ix < len; ix++)
{
     a_str[ix] = tolower( (unsigned char) a_str[ix] );
}


As well as removing unnecessary strlen calls from loops, we should try to remove any other expensive function calls.

3.

Temporarily swap:

Here's a neat trick to swap two variables without creating a temporary:

void swap(int& a, int& b)
{
   a ^= b;
   b ^= a;
   a ^= b;
}


To check correctness, you only need to know that (a^b)^a = b and (b^a)^b = a.

No comments: