Hacker News new | past | comments | ask | show | jobs | submit login

In practice it's _worse_ than that because you probably don't want a "long", you probably want a particular size like a 64 bit integer. So you have to add ifdefs to call either strtol or strtoll depending on the size of "long" and "long long".

And if you are using base 16 then strtol will allow an optional "0x" prefix. So if you didn't want that you have to check for it manually.

Strtol also accepts leading whitespace so if you didn't want that you have to test manually for it.

Don't pass a zero base thinking it means base ten. This works almost all the time but misinterprets a leading zero to mean octal.

Good luck!




>> you probably don't want a "long", you probably want a particular size like a 64 bit integer. So you have to add ifdefs to call either strtol or strtoll depending on the size of "long" and "long long".

stdint.h (https://en.cppreference.com/w/c/types/integer) provides fixed-width integers in specific sizes. It became a standard in C99.


Doesn't provide strto32 and strto64 though so you still need an ifdef.


Newsflash, the C language has conversions. You can assign a long or long long to your int32_t.


Great, and what happens when you accidentally assign something greater than 2^31 to an int32_t when using strtol? You won't benefit from a range error if LONG_MAX is 2^63, and now you have to make sure to handle any implementation defined behavior.


That's true. If the range you're interested in is not the same as the range of long or long long, you'll have to check the range yourself before you go on and use the value. No ifdefs required. If you're not happy doing it yourself, I do recommend strtonum or any of the alternatives that allow you to explicitly specify the range you're interested in. I don't see the point in littering the standard library with functions having hard-coded range for every range you might be interested in.


And get undefined behavior where the compiler can do anything it wants...


Unlike other cases of signed overflow, you actually don’t get UB on integer-to-integer conversions. You still have a bug in your code, though.


This is crazy


Welcome to the real world. At least it is understandable crazy. After all it is in a library call not part of the mental model of c.

To compare, I can’t say about the mental baggage you carry with javascript the core language. Still, it sort is of works. World moved on. Good luck.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: