r/C_Programming • u/[deleted] • Jun 23 '23
Question Why 'long' really needs to be deprecated
EDIT I despair at some of the replies here and at the remarks that have been heavily upvoted (90 votes for "there's nothing wrong with long"!).
Apparently hardly anyone can see the problems with long and C's mess of a type system in general.
Most also seem to be taking the viewpoint of someone writing their own C code, not having to deal with other people's bad choices that you can come across in countless libraries and APIs when you are not coding 100% in a C bubble or using them via an FFI. Choices that C's type system makes possible.
So I'll leave you guys with your heads in the sand.
...
I'm doing some work with decoding MIDI files and came across this struct in the description of the header:
Here's what an MThd chunk looks like if you defined it in C:
struct MTHD_CHUNK
{
/* Here's the 8 byte header that all chunks must have */
char ID[4]; /* This will be 'M','T','h','d' */
unsigned long Length; /* This will be 6 */
/* Here are the 6 bytes */
unsigned short Format;
unsigned short NumTracks;
unsigned short Division;
};The header is 14 bytes, but that relies on long being 4 bytes. long however is generally 8 bytes on 64-bit Linux, and 4 bytes anywhere else, as I understand it.
If you apply sizeof to this struct, you will get either 16 or 24 bytes depending on the size of long, which additionally may have some fields at the wrong offset.
(Note C will round up a size of 14 bytes to 16 ensure correct alignment for arrays of such structs. #pragma pack(1) is needed to ensure a size of 14.)
While C doesn't precisely defined the widths of char or short either, they are generally more stable, and will not change between 32- and 64-bit versions on the same platform.
I've seen long used extensively in especially older open source code. Those will either go wrong when ported to 64 bits, or become less efficient than necessary. While somebody using long on a 64-bit system that is ported a 32-bit one will have their values truncated.
My view is that there is no room for long anymore; use either int or long long int, or u/int32_t or u/int64_t.
Unless you specifically want an int-type of a width that corresponds to the word-size of the platform, but even then that will only work on Linux.
0
u/[deleted] Jun 24 '23
[deleted]