Hacker News new | ask | show | jobs
by rbanffy 25 days ago
Passing a negative value to a function that is specifically for converting strings into unsigned numbers is pretty much an error. In the case of functions that return an unsigned number, at least, negative return values can represent errors.

It’s more fun when the result can be signed though. Maybe strcmp with the representation of the LONG_MAX, and if it doesn’t match, call strtol and watch for a LONG_MAX indicating an error.

C is a bit messy. Would be nicer to return a struct with a possible error and the desired value, Golang style.

1 comments

If that's an error then so is passing in a non number.

So catch 22. You can only check for valid numbers if the number is valid?

If you pass a negative number as a string to a function that converts strings representing positive numbers into positive long integers, then yes, it should return an error status instead of the wrong result.
Ah, I misunderstood what you meant by "is an error". Agree.
That's the C way, yes.
No. This is more like if strcmp compared null terminates strings, but can only compare strings that are in fact equal.