3 ms·
It is bad that you can insert an integer and then if you try to read the value back as a string, it'll happily interpret the integer value as a char *.
by SamReidHughes 12y ago
It is bad that you can insert an integer and then if you try to read the value back as a string, it'll happily interpret the integer value as a char *.
- cperciva 12y agoNot really. If you don't know if you're dealing with integers or strings, you shouldn't be writing C anyway.
- deleted 12y ago[deleted]
- SamReidHughes 12y ago[First of all, what's the deal with the anonymous upvoters bringing my previous comment, which is against the guidelines for Show HN, back into the black? Bad comments should go to the hell where they belong!] If you're dealing with integers or strings on a key-by-key basis and can statically predict as a function of key whether it's an integer or a string, you shouldn't be using a hash table, you should be using a struct or two hash tables, one with the integers and one with the strings. If you're dealing with integers or strings on a key-by-key basis and can't statically predict whether it's an integer or string, you'll need some mechanism for ascertaining that and the best way is for the hash table to store and expose that information, because you'd be storing it elsewhere anyway. You could expose the underlying tagged union. If you're not dealing with integers or strings on a key-by-key basis (I guess you're dealing it on a table-by-table basis, which is a more likely usage, I hope), you just want to avoid duplicating code. There's little harm in having a tag and doing a run-time check anyway. Also, if you don't want to do that, you can make one underlying implementation, and then wrap it in types "struct hash_string_int" and "struct hash_string_string," and the like, and permit only the right kind of methods to be called on the right structure type. It's never the right thing to do to make needlessly risky code -- if that's how you like to code, then you shouldn't be writing C.