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: 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: boolean annoyance
    ... sets errno to ERANGE and returns LONG_MAX or LONG_MIN. ... The strtol(), strtoll, strtoimaxand strtoqfunctions ... ***If no conversion could be performed, ...
    (comp.lang.ruby)
  • Re: Finding a word inside a string
    ... If strtol sets errno to ERANGE, ... If v happens to be zero, you do not know whether that is because your ...
    (comp.lang.c)
  • Re: detabbing again
    ... Calling printf can loose the value of errno. ... test argvto see if it is zero and spit this case back to the user ... to the pointer whose address you pass to strtol. ...
    (comp.lang.c)