News for hackers. Stuff that matters.
Re:Brian's Rules for Writing Cross Platform 'C' Code (2008) by voltagex_ on Saturday June 14, 2014 @11:41AM (#7892967)
I'm just starting C, what should I be using instead?
Re:Brian's Rules for Writing Cross Platform 'C' Code (2008) by jacquesm on Saturday June 14, 2014 @01:33PM (#7893192)
Don't make any assumptions about the architecture that your program will run on. If you have to go into variables with a different type than the one with which they were declared make sure you do so in a portable way.

So, for instance, if you want the lower 8 bits of an int don't declare a pointer to a character and then lift out the byte, but do (value & 0xff) instead.

That way if you move your program to a big endian machine it will still work. Storing pointers in ints assumes that pointers and ints are the same size, which is definitely not always the case.

So store pointers in a space sizeof(whatevertype*) rather than sizeof(int).

Re:Brian's Rules for Writing Cross Platform 'C' Code (2008) by mikeash on Saturday June 14, 2014 @02:33PM (#7893313)
If you need to store a pointer in a integer variable, first stop and look very hard at what you're doing and think about whether you really need this. It's usually a really, really, really bad idea.

If you have decided that you do really need it, then use the standard C type for "integer type large enough to hold a pointer". Yes, there is one. Actually two. They're called intptr_t and uintptr_t depending on whether you want signed or unsigned.

Similarly, if you subtract two pointers and need to store the answer (this is less of a cause for reflection, but still not too common) then don't toss it into an int and hope that it works. Use the language-provided type for "difference of two pointers", ptrdiff_t.

If you have a value that needs 32 bits of storage, don't throw it in an int and say, hey, int is probably at least 32 bits. Use the language-provided types int32_t and uint32_t.

Understand what types are provided (Wikipedia has a decent summary at http://en.wikipedia.org/wiki/C_data_types), what they mean, and what the guarantees are. Don't fall into the trap of "it works for me, here, now, so it's fine". If you need a particular guarantee (such as the ability to hold a certain range of numbers), ensure that the type you're using provides it.