Re: Finding a word inside a string



On Fri, 24 Sep 2010 19:09:23 -0700 (PDT), Chad <cdalten@xxxxxxxxx>
wrote:

 if(value_str[0])
   {
     v = strtol(value_str, (char**) NULL, 10);  

What purpose do you think the cast serves?  What would be different if
you deleted it?

     if(0 == v && ERANGE == errno)  return ERR_CONVERSION_CHAR_TO_INT;
   }

So -10 will never be valid input to your code?

If strtol sets errno to ERANGE, you have already invoked undefined
behavior in the previous assignment to v (unless INT_MAX happens to
equal LONG_MAX).  Regardless, when errno is set to ERANGE, v will
never be zero so the if can never evaluate to true.

If v happens to be zero, you do not know whether that is because your
text evaluated to 0 or because strtol could not perform any
conversion.  Using NULL as the second argument to strtol eliminated
your best hope of doing error analysis.


Would a better method be something like the following

errno = 0;

if (v == 0) {
if (errno == ERANGE) {
return errno;
}
return ERR_CONVERSION_CHAR_TO_INT;
}

How could it be? If v is zero, the errno cannot be ERANGE. It makes
no sense to test a condition when the answer is already known.

On the other hand, if errno is ERANGE then the code invokes undefined
behavior.

--
Remove del for email
.



Relevant Pages

  • Re: cast or other error question
    ... the test above accepts an empty string as a valid ... to my mind was handling it prior to passing it to strtol rather than ... error in that conversion (errno remains 0). ... Furthermore, you haven't really handled ERANGE, or do you ...
    (comp.lang.c)
  • Re: detabbing again
    ... If no conversion could be performed, zero is returned. ... stored in errno. ... strtoll is but not strtol. ...
    (comp.lang.c)
  • Re: strtol with hex greater than 4 byte ?
    ... as this `use' of errno is documented; ... >ERANGE seems to be reserved. ... If strtol is not returning LONG_MAX or LONG_MIN, ... Dan Pop ...
    (comp.lang.c)
  • Re: Requesting advice how to clean up C code for validating string represents integer
    ... Bullet Proof Integer Input Using strtol() ... ERANGE is stored in errno." ...
    (comp.lang.c)
  • Re: cast or other error question
    ... you have a reference that tells you what values strtol may ... You do not need the macros from limits.h to perform the ERANGE ... Once you know that errno has been set to ERANGE by strtol, ...
    (comp.lang.c)