Sunday, January 30, 2011

Efficiency can be fun and make your code look cleaner.

Well it's been over two weeks in OOP344 and I haven't blogged about anything. Well today I do have something I'd like to share. Something I learned in class while listening to Fardad's lectures.

When I'd use a for loop for the purpose of character arrays for strings I'd have a habit of using the null-byte in the condition to terminate the loop once found like this:

for (i = 0; str[i] != '\0'; i++){
    /* do something */
}

The for loop would end when the null-byte is found. However Fardad showed the class how to use a more efficient way to terminate the loop without the use of using the null-byte in the condition. Heres how its done:

for (i = 0; str[i]; i++){
   /* do something */
}

At first I didn't get it until I remembered that the null-byte is really a 0 in integer terms even though its a char. 0 being false.

Its like saying:

if (str_is_true){
  /* do something */
}

str_is_true being an integer with a non zero value would be true, instead of doing this:

if (str_is_true != 0){
  /* do something */
}

Which is an inefficient way to find out if str_is_true is not zero. If I were to use the inefficient way I'd probably want to change the variable name to suit the condition. Instead of str_is_true I'd just call it str. I'm getting carried away but thats how I see it.

Even though this may have been obvious to a lot of students in the CPA program in this semester, I thought it was amazing to see something so subtle change my view of how to program with for loops with strings.

No comments:

Post a Comment