Hacker News new | ask | show | jobs
by DSMan195276 3354 days ago
As a C programmer, I would also agree. "Everything is an int" is not a good way to be thinking about things. There's a reason that `intptr_t` exists. Well written C shouldn't rely on any integers being specific sizes or the same size unless you're using the standard types for that purpose (Llke `uint8_t`, `uint32_t`, etc.). Even then, you probably don't need them in a lot of cases, and you should basically never be casting integers into pointers unless you're using the above `intptr_t`, or `uintptr_t`. Even then, you're probably still better off just making your life simple and use a `union`.

That said, I would argue that minimal explicit casts is a pretty good goal for any C programs - I find that crazy casting tends to be a sign something could be done better. But obviously, casts are definitely necessary in some instances, so it's not like "castless" code is guaranteed to be the right way to do things anyway.

1 comments

To clarify, I should probably have said "integer" to avoid confusion with the C type called "int", or to be more accurate ℤ/w for a variety of widths w.

I didn't mean "C is nice because I can just write 'int' for all the types and it works", I meant "C is nice because it represents data in a very conceptually uniform way: either as integer, or 'pointers' which are themselves integers."

The current world population is an integer, my bank account number is an integer, but that doesn't make it's meaningful to add them together. Values can have the same representation without being the same type :)

> "Everything is an int" is not a good way to be thinking about things. There's a reason that `intptr_t` exists.

From http://en.cppreference.com/w/c/types/integer (top Google hit for `intptr_t`):

    intptr_t
    integer type capable of holding a pointer
They're integers :)

> Well written C shouldn't rely on any integers being specific sizes or the same size unless you're using the standard types for that purpose (Llke `uint8_t`, `uint32_t`, etc.).

I never said it should; but from that same cppreference site:

    int8_t, int16_t, int32_t, int64_t
    signed integer type with width of exactly 8, 16, 32 and 64 bits respectively
These are also integers :)

> you should basically never be casting integers into pointers

Again, I never said you should. I didn't say, or mean, anything about casts.