Proof that I am stupid -- newbies, don't do this 
Author Message
 Proof that I am stupid -- newbies, don't do this

I spent about 20 minutes yesterday pounding myself in the head with H&S for
the following bit of idiocy, and I figured it was good enough to share with
the group.  

I'm parsing a data file (I will die parsing data files, but that's another
story) that has fixed-length columns of data.  Occasionally, fields in some
of the columns will be blank (that is, all spaces).  So I wrote this nifty
little function to tell me whether a field had all whitespace or not.

However, several neurons misfired, and for some reason I had convinced
myself that I had to scan the *entire* field, maintaining a flag, instead
of just breaking when I hit a non-whitespace character.  Here's what I

      while (buf[i] != '\0')
         result = result && isspace (buf[i++]);

Now, what's wrong with this picture?  '&&' is guaranteed to evaluate from
left to right, meaning that 'result' will be evaluated before 'isspace'.
Secondly, '&&' is a short-circuit operator -- if the first expression
evaluates to FALSE, the remaining expressions *are not evaluated*.  This
means that when I hit a non-whitespace character, result is set to FALSE,
meaning that the 'isspace' part of the expression will never again be
evaluated, meaning that *i will never be incremented*, which sends us off
into never-never land.

In a related incident, I also learned that it is best to be specific with
the radix when using strtol().  I had always just used a radix 0 (no
particular reason, just because it always worked).  This works great, until
you try to deal with decimal numbers with leading zeros, to wit, 08 and 09.
When you specify a 0 radix, strtol() assumes that any leading zeros
indicate octal numbers (which 08 and 09 definitely aren't).  

I used to say I wasn't stupid, I was just sloppy.  I may have to amend that.

Anyway, I offer the cases above as a warning to novice programmers.  Don't
do what I do.

:-P~~~

--
John Bode
"Paranoia is just reality on a finer scale" -- Strange Days

To email me directly, remove the 'nospam.' from my address.



Sat, 23 Oct 1999 03:00:00 GMT  
 
 [ 1 post ] 

 Relevant Pages 

1. Don't I feel stupid...

2. Don't understand why I am getting the C2236 error

3. I am a newbies on C

4. I am a newbies on C

5. gets(rec->num); I don't know what I am doing wrong...

6. Don't read, it' a proof....

7. Don't blame Student stupid! Everyone fm STUPID to SMART!

8. Macro with functions problem -- why am I stupid?

9. Am i stupid? ;-)

10. I am stupid, so I need your help

11. I'm obviously doing something stupid with 'cout'

12. System.Threading.Timer , am I doing this correctly ?

 

 
Powered by phpBB® Forum Software