Safely Swallowing Up Spaces or Non-Spaces

Can you explain why this is bad? (to swallow up spaces)

if( ' ' == *instring)

  while( ' ' == *instring && *(instring++));

The idea? You encounter a space, and now, while you see spaces and not the NULL ('\0') character, you keep advancing the string pointer.

Bad. But why?

It's not that dangerous - just not very readable. Better to have 

while( ) instring++;

What is really dangerous? Swallowing up non-spaces using

while( ' ' != *instring && *(instring++));

The idea - if the character you see is not a space and not the NULL character, advance the string pointer. But what actually happens? Exactly! The pointer advances EVEN in the case of the NULL ('\0') being encountered at *instring.

So, always do

while( *instring && ' ' != *instring ) instring++;

Much more readable. Yes, in this above snippet, you can be cute and do ' ' != *(instring++);

Comments

Popular posts from this blog

Poor Documentation - How Could You Do this to Us K&R?

A Classic C Programming Mistake - See if You Can Spot it