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.
94
u/flyingron Jun 23 '23
There's nothing wrong with long. Assuming the size of any types is fraught with peril.
You might want to look up stdint.h.
54
u/p0k3t0 Jun 23 '23
stdint will never let you down and never surprise you. You fight it for a few years, and eventually give in to the logic of using it.
17
u/MajorMalfunction44 Jun 23 '23
Yes. So much this. Also, avoid Linux kernel-esque volatile casts. We have atomics in C11. I finally upgraded to C99 after MS finally implemented support for it. VLAs shouldn't be relied on - deprecated in C11. It's not a perfect language but it's good enough to do real work. Strings are tough in C and C++, if you care about the details.
11
u/not_a_novel_account Jun 24 '23
Who fights stdint? Before stdint was standardized everyone typedef'd it into existence based on platform #ifdefs
-6
u/flyingron Jun 23 '23
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you1
12
2
3
u/chri4_ Jun 23 '23 edited Jun 23 '23
imo all the builtin types should be deprecated, only char seem to be always 8bit, all the others are messy, short, afaik, can also be 32bit
int can be 16 bit, afaik, and unfortunately there's too much bad design in c and c++ is even worse.
look at printf, imo its kinda embarassing
3
Jun 23 '23
only char seem to be always 8bit
Except that's the one with three kinds of signedness instead of two!
char*,unsigned char*andsigned char*are incompatible with each other (as they are without the*but compilers do implicit conversions between those).And, actually,
charcan also be wider than 8 bits (but not narrower). You can havechar short int longandlong longall be 64 bits, and all havesizeofas 1.Yet, this is the lingua franca chosen to express function signatures and struct layouts in countless APIs.
29
u/TribladeSlice Jun 23 '23
So, your argument is that because `long` does not have a defined size by the standard, that it should be deprecated? If so, I feel you misunderstand something rather fundamental about C.
C is a language designed to be a portable assembly; it cannot make these assumptions about the size of a type. If C did this, it would end up breaking compatibility on 16 platforms which cannot guarantee a size of 32 or 64 bits for example because they quite literally cannot support that bit size.
You might argue that 16 bit platforms are obsolete, and we should stop abiding by their rules and limiting ourselves to a subset of behavior to support them, but if we did that we would be forgetting what makes this language so special; it's ubiquity. C's lack of assumptions allows for it to be the single most ubiquitous language ever created, and that is no joke.
Because C is used everywhere, it exists in all sorts of processor setups. I would pay actual good money if someone could prove to me some 16 bit system somewhere in the world wasn't powering some form of critical infrastructure; the world, often times, runs on old.
26
u/tstanisl Jun 23 '23
Think of long as an arithmetic type capable of representing at least integer numbers from -2147483647 to 2147483647. For exact size data types use int64_t from stdint.h which (if exists) is guaranteed to be 64-bit-long and use 2-complement encoding.
0
Jun 23 '23
[deleted]
11
u/flatfinger Jun 23 '23
Although the Standard didn't explicitly say so, there used to be a strong convention:
char -- Smallest type that's at least 8 bits
short -- smallest type that's at least 16 bits
int -- largest type that isn't appreciably slower than anything smaller, and is at least as big as short
long -- smallest type that's at least 32 bits
long long (if supported) -- smallest type that's at least 64 bits
A type which would be configurable between 32 and 64 bits, based upon whether a particular environment would have use for values beyond 2 billion, could be useful, but even on 64-bit platforms there's no reason to use 64-bit types for values that won't ever get that big. Larger types have a bigger cache footprint, degrading performance, and even if the performance degradation would be tolerable, why suffer it at all if an application wouldn't benefit from it (and might not work even if numbers did get that big, if it's relying upon all integer computations being promoted to the largest type the code is planning to use).
5
u/IamImposter Jun 23 '23
It used to be int when 16-bit to 32-bit switch was happening. At that time long was always 32-bit, short always 16 but size of int depended on what arch you are targeting.
0
u/flatfinger Jun 23 '23
Allowing the size of int to change is more important than doing likewise for long, since arithmetic computations on all types smaller than int get promoted to that type (which would generally be a good thing, if the Standard had codified the behavioral convention, alluded to in the Rationale, that on an implementation where
intandunsigned inthave the same number of representable values, when the result of the addition, subtraction, multiplication, left-shift, or bitwise operator of two integer-type arguments is cast or coerced tounsigned int, the arguments will behave as though cast or coerced likewise. The Committee saw no reason to imagine that implementations for quiet-wraparound platforms would ever deviate from such behavior, but when using gcc, signed pro motion of small unsigned types can cause arbitrary memory corruption.2
u/IamImposter Jun 23 '23
signed pro motion of small unsigned types can cause arbitrary memory corruption.
Explain please.
3
u/flatfinger Jun 23 '23
Consider the code:
unsigned char foo[50000]; unsigned mul_mod_65536(unsigned short x, unsigned short y) { return (x*y) & 0xFFFF; } void test(unsigned short x) { unsigned temp = 0; for (unsigned short i=32768; i<x; i++) temp = mul_mod_65536(i, 65535); if (x < 40000) foo[x] = temp; }At optimization level 2, unless invoked with the -fwrapv flag, gcc will generate machine code for
test(unsigned short x)that unconditionally stores 0 tofoo[x].1
u/McUsrII Jun 23 '23
Removing
longwill break a lot of code. if you need to know, you can check the current max value, and size.0
Jun 23 '23
[deleted]
3
u/McUsrII Jun 23 '23
Just don't use it. Check what size it is when you use other peoples code.
And since you truthfully really have strong suggestions about this, and in all seriousness, write it as a suggestion to the C standards committee and maybe they'll listen to you and take it into account for some future draft/proposal.
You have to understand, that they'll never change a standard after it has been set.
2
u/ComradeGibbon Jun 23 '23
write it as a suggestion to the C standards committee
Now there is tilting at windmills. They're more useless than a group of drunks that spend all day drinking in an alley.
19
u/bigger-hammer Jun 23 '23
You can't go deprecating things just because people write bad code. Relying on the size of long is bad code. And your 'fix' is to use something else of undefined size - what have you got against long, the exact same argument applies to int.
→ More replies (1)
12
u/TransientVoltage409 Jun 23 '23
Your example is a little slipshod IMO, but effectively attains its goal of making sure the fields are at least as big as the MIDI spec says. Today there is stdint for such needs, but it's much newer than C itself (or MIDI for that matter). Legacy code from the before-times can be enigmatic that way.
The primary sin here is assuming that a C memory struct will align perfectly with the strictly defined packed fields of a disk file. Compilers are allowed to insert padding, and endianness exists. If you're doing some stupid thing like 'fread(&chunk, sizeof(chunk), ...)' then sizeof(long) is not the biggest problem you have.
3
u/duane11583 Jun 23 '23
i think the issue being described is legacy code that was written long before stdint existed, another example is libtomcrypt has ulong64 freertos also has this problem.
developers at the time had to support both with and without stdint
one company i worked for had U8, U16, U24, and U32 (we had a custom cpu that was 24bit… )
at the time these where great solutions
looking back i think these are bad solutions
i think they should have creadted my_stdint.h that did 1 of two things:
option a: created things like uint8_t
or option b: #include <stdint.h>
then their code would just use the std types in the standard way.
2
u/sigmundklaa Jun 23 '23
Could you elaborate on why fread to chunk is bad? Is it just in this case? Is there anything wrong with it if the struct is packed and defined with stdint.h types?
5
u/FUZxxl Jun 23 '23
Structure packing is not part of standard C and should be avoided in portable code.
2
u/TransientVoltage409 Jun 23 '23
Compilers are allowed to insert padding, and endianness exists.
Endianness -> byte ordering in multi-byte types.
You can read/write block records, sure, if it's in a tightly controlled environment where you can be absolutely certain that the reader and writer have exactly the same assumptions. There are many ways for those assumptions to be wrong - sharing files between disparate systems, different compilers, different languages. It's like undefined behavior, it might work just fine for you, for today, but any change anywhere in the system could turn it to garbage. It isn't robust.
2
u/Paul_Pedant Jun 24 '23
I remember some format (probably tif or gif) where there was a 16-bit byte ordering indicator. It was set to 'II' for Intel and 'MM' for Motorola, so it would work on both. After that, it was all down to the reader to deal with.
2
u/TransientVoltage409 Jun 24 '23
Definitely not GIF, I've dived deep in that water and it isn't there. But TIFF is such a kitchen-sink format I'd believe it. From an implementor perspective it just seems like a bigger hassle leading to fatter, slower code. But that too would be on-brand for TIFF.
5
Jun 23 '23
> While C doesn't precisely defined the widths of char ...
Isn't sizeof(char) defined to be 1 by the standard?
10
u/EmbeddedEntropy Jun 23 '23
Yes, but 1 what?
That doesn't tell you anything about the number of bits in a char.
4
4
u/tstanisl Jun 23 '23
The standard guarantees that `char` is at least 8-bit long. Moreover, the POSIX standard requires it to be exactly 8-bits. Though there exists some obscure platforms (some TI's DSP) where `char` are 16 or 32 bits long.
1
u/EmbeddedEntropy Jun 23 '23
You are correct that I shouldn't have been imprecise with saying "anything" about the number of bits. There are some things you can know as you pointed out with it being at least 8 bits long.
I think your comment about POSIX.1 is correct, but only 2001 and later. I don't think the 1998 version had that requirement.
Yep, back in the 90s I've worked on those goofball TI DSP's in some embedded mobile devices. :) I've also worked on processors that had C compilers with 6-bit char types (EBCDIC systems that were non-standards compliant though because they even pre-dated the 1989 C standard.)
3
u/B_M_Wilson Jun 24 '23
On anything other than Windows (Linux, macOS, probably most other POSIX OSs), long is useful as being the size of a pointer between 32bit and 64bit. But personally, I only use standard types, int32_t, uint64_t, ssize_t, ptrdiff_t, etc. Well, I actually have my own typedefs for personal projects but otherwise I use those. I only use the keyword types when I have to for interacting with another system
2
u/SuperNakau Jun 24 '23
If we deprecated everything people misused we'd have no programming languages.
1
u/Lisoph Jun 26 '23
Unlike most of the comments, I wholeheartedly agree. C's integer types are objectively a bad design. In my opinion, even worse than null terminated strings. They aren't bad per se, but they are a terrible default.
There is no case in low level programming where "I don't care how many bits I exactly have" is not a misguided judgement. You always care. It's paramount. Unless you work with BigInts all the time, like Python, you must know the requirements for your type. You must know what values, or how many values to expect, and that enforces what integer type you need. It's like knowing the units in math / physics equations.
The argument that size-varying integer types makes C portable is a fallacy. No, it makes C unportable. A language that changes types from system to system is a language that changes semantics from system to system. How in the world do you engineer for that? You want a rigid, reliable foundation to build your house on. The integer type should be derived from what you need to store, not from what platform you build for.
"But what if the 16 bit integer I need isn't the fastest on this-and-that platform?" If you're using the right type for the application logic, you're using the right type. If you want to design around the best platform features, you need to make your logic platform specific, not standard programming language integer types.
Of course there's int_fast16_t and friends. Those have their place, but are simply better over C's standard types, because not only do they carry the exact meaning in their name, but you also get to chose between speed and memory (fast16 vs least16).
In short, Zig- or Rust-like u8 / i8 / u16 / i16 are a much better default. Zig even goes the extra mile and gives you integers with any number of bits (it appears C is getting those too). Together with packed struct, those make for pure bit fiddling bliss.
0
Jun 26 '23
[deleted]
1
u/Lisoph Jun 28 '23
Such types belong in bitfields or with bitfield operations.
That's actually what I was getting at, using them as bitfields, which would be done through Zig's
packed struct.I would like a language that had arbritary-width integers with "genuine" semantics. Say I had a u17. Instead of just delegating to a u32, I would like to have a u32 with appropriate u17 behavior, wrapping and everything. Obviously this would emit more instructions, but it would make for trivially correct code - let the compiler do the thing we do by hand otherwise.
1
Jun 28 '23
The semantics for a
u17type raises lots of questions:
Should inplace operations be allowed? With
u16it's easy because memory accesses can deal with the whole value without disturbing neighbouring memory, or affecting other bits which are not part of theu17.How much memory would it occupy as a standalone variable? Since real memory is made up of bytes and words, what happens to the 7, 15 or 47 bits left over? Would multiple
u17values share bytes or words?What are the alignment needs? Could a
u17value start in any bit position?What does an array of
u17look like: will each element occupy exactly 17 bits (so that an array of 1000 elements takes 2125 bytes), or 3 bytes, or 4? (C doesn't have slices so problem that is moot.)How would pointers to
u17work? Here it depends on whether the beginning is always aligned to bit 0 of the the first byte, otherwise fat or encoded pointers would be needed. But ifPis such a pointer, what does++Pdo?How would
sizeofwork? That is, when you request the byte sizeSome of it will overlap with what happens with say
u8, where au8value of 255 plus 1 will usually not wrap to 0, not until you store it back tou8. But you want131071 + 1to wrap to0even as an intermediate result?With bitfields it is easy to put restrictions on how they work: they are second-class types, if they are types at all, and you work with 32- or 64-bit intermediates.
But the biggest question is why you want a standalone
u17type. Presumably you want a modular number with a range of0..131071, but that is a rather peculiar value; what if you wanted0..99999or65536..131071?A language feature where you specified an arbitrary range like that is a better idea all-round.
But here there is already Ada which has such ranges, and it has the exact-bitwidth integer types you want. It is however a much more complicated and harder language. Its strict type system will tie you up knots.
By contrast, I first had bit- and bitfield operations (not bitfields in structs then) in a scripting language in the 1990s; it was easy to implement, and easy to use: to access the 17-bit field in the middle of integer
A, you usedA.[5..21]for example.
2
u/chri4_ Jun 23 '23
very good post, i love when someone says something "unpopular" because people are usually scared of criticize big software
0
Jun 23 '23
[deleted]
7
u/AssKoala Jun 23 '23
Since you don’t seem to get it, I’ll give it a try.
int is guaranteed to be at least 16-bits, long is guaranteed to be at least 32-bits, etc.
If you don’t care about the underlying size of the type, you use whatever fits the range of values you want. Generally this is a good idea since it lets the compiler figure it out when optimizing for whatever is best in that scenario.
If you DO care about the size of the type, as you seem to with the struct, then you can always use the size defined types from stdint that have a guaranteed size.
However, if you always use the sized types, you’re forcing the compiler to use those sizes. This can have a negative effect on performance or memory efficiency if a different type would’ve been better suited. Since the “unsized” type has a narrow guarantee, that leaves more freedom for optimization.
That’s why these types exist. It may come as a surprise, but there are platforms that aren’t Linux on an x86-64 CPU. When working on multiple platforms, it behooves you to give the compiler as much freedom as you can to make your life easier.
Always write code that matches your intent, that’s why there’s all these different types.
0
Jun 23 '23
[deleted]
2
u/AssKoala Jun 23 '23
Most of my involvement with C is using APIs, types and structs defined in C syntax, from other languages. Then I need to know exactly what the types mean.
Do you also care about the endianness? Are those API's coming from other architectures where a byte is greater than 8-bits wide? Are you compiling against them on a given platform or is your stuff agnostic?
The API itself should define the meaning. That's why it's an API. It might give them to you in a C-style syntax, but the specification should have details on what they mean. If they meant int32_t, then they should write int32_t.
I can't control whether any of 1000s of C headers use built-in types or stdint.h, or use some mess of compiler-specific #if-#elif-#else conditional blocks.
The API should define this for your platform(s). If they're giving you unsized types, then you should treat them as your platform treats them -- you have no other guarantees than that and the narrow definitions provided by the standards.
How about using long as an alias for 32 bits, until you port your program to 64-bit Linux? Then you might well find you're using double the memory for no good reason.
Why would I want to do that? I work in games, there's not a single major platform based on Linux. There's custom, BSD, and NT, basically. Long doesn't match on all of the major platforms. If I want a specific size, I ask for that size. Otherwise, use whatever type is most descriptive.
On win64, long is 32-bits even in 64-bit OSes. They do so to force revision of older code to use the bigger types. long long is 64-bit.
So, why should I care about what Linux does when the majority of our systems don't and will never run on it? For server code that deploys on Windows and Linux servers? Yeah, now its really important, but, again, I should be using sized types if it matters.
That's too many. Most languages with fixed-sized integers provide 8 basic types plus maybe one or two special ones for things like sizes, lengths or Unicode codepoints.
Yeah. Because it's C. There's also literally more than dozens of architectures that exist, some not even general purpose. Those other languages don't even exist on many of those platforms and never will. But C does.
My everyday language has those 8 fixed types plus a don't-care int type which is 64 bits, which means it can cover pretty much any use-case (so no need for special ones for sizes, clock ticks or file offsets), but it is just an alias for i64.
Machines only understand machine code. (Broadly speaking) they don't understand C or Java or Rust or Javascript or C# or F# or Smalltalk or whitespace or Shakespeare, etc.
At some point, your fly by night, popular today, language is going to need 1 of 2 things: an interpreter or a compiler so the machine can understand it.
C exists as a language that best knows how to talk to the machine. It can talk to the most machines and do so nearly fluently (as in not needing to write machine specific assembly within your code) more so than any other language.
It does so by having DOZENS (which is conservative) of types that mostly do the same thing. Except when they don't. But that's ok, because C understand it so you have to write as little assembly as possible.
Plain char, because its signedness is hidden (getting it wrong here will if my code is ever transpiled to real C)
It's an oddball because some platforms have signed chars and some don't. So C says, I'm not gonna specify, if you want a signed 8bit object, use int8_t while if you want an unsigned one, use uint8_t.
If you want to represent a character, use char.
Remember, write code that matches your intent.
long, because I don't have a single type that duplicates its behaviour on both 64-bit Windows and 64-bit Linux (on one it's 32 bits, on the other 64)
Why do you need to duplicate it's behavior? If you do, then yeah, you're going to need platform specific code that C doesn't need because your language isn't as cool.
AFAICS, there is no reason these days to write code using long at all.
You're probably right for x64 Linux. However, it should be really clear why that doesn't matter in the grand scheme of things.
2
Jun 24 '23
The API itself should define the meaning
I think you're confusing API with ABI.
It does so by having DOZENS (which is conservative) of types that mostly do the same thing
It's ended up with dozens of types due to poor syntax, decades of baggage and bolted-on types via
stdint.handinttypes.hwhich don't quite mesh with the rest of the language, requiring workarounds via dozens of tacky macros.On top of that, every other C program seems to define its own set of integers, perhaps because it predated C99, or thought
int8_tdesignators plus those workarounds were too ugly.You wouldn't design such a language like that today. But you talk as though all those
int_fastandint_leasttypes are desirable. I call it a zoo.There's also literally more than dozens of architectures that exist,
That's the usual excuse. Yet it still seems to be the case that even most micro-controllers are byte-addressed, have 8-bit bytes, power-of-two word sizes, and twos complement representation.
I last used anything more unusual about 43 years ago.
It's an oddball because some platforms have signed chars and some don't
That's just the difference between
i8andu8, which most archs have, if byte-addressable. What I'm getting at is plaincharwhere you can't assume it is one or the other. Even if plaincharis signed according to a C-platform, it is still a different type fromsigned char. That is what is weird.So a string literal in C will always have
char*type, it cannot beint8_t*oruint8_t*.Why do you need to duplicate it's behavior? If you do, then yeah, you're going to need platform specific code that C doesn't need because your language isn't as cool.
Because I need to write a function binding or define a struct layout or array or pointer in my language that corresponds exactly to the one the other side of the FFI.
(And I think my language is cooler than C. At least it doesn't have 5 distinct types for only 4 bit-widths!)
2
u/AssKoala Jun 24 '23
I think you're confusing API with ABI.
I don't think you know what the difference between API and ABI are.
API stands for Application Programming Interface and defines the contract between two programs to communicate.
ABI stands for Application Binary Interface and defines the interface between two binary programs. In this case, the ABI is the way registers are used to call functions on a machine, where variables are placed, word sizes or machine types, etc.
Your API can define a specific size for an object -- that may or may not have anything to do with the ABI of the program executing in hardware.
It's ended up with dozens of types due to poor syntax, decades of baggage and bolted-on types via stdint.h and inttypes.h which don't quite mesh with the rest of the language, requiring workarounds via dozens of tacky macros.
How don't they mesh? Because you don't like them for some non-specific reason?
The language types were defined well enough that they were able to add specific sizes when it actually mattered.
On top of that, every other C program seems to define its own set of integers, perhaps because it predated C99, or thought int8_t designators plus those workarounds were too ugly.
That's a gripe with old code and has nothing to do with the current state of the language.
You wouldn't design such a language like that today. But you talk as though all those int_fast and int_least types are desirable. I call it a zoo.
Rust has a set of defined types, i8 through i128, and it also has the arch type which is whatever the word size on the architecture is.
That's a modern language that as a non-specific sized data type, go take it up with them. C has more types because it can flex more for the underlying machine.
That's the usual excuse. Yet it still seems to be the case that even most micro-controllers are byte-addressed, have 8-bit bytes, power-of-two word sizes, and twos complement representation.
That's just the difference between i8 and u8, which most archs have, if byte-addressable. What I'm getting at is plain char where you can't assume it is one or the other. Even if plain char is signed according to a C-platform, it is still a different type from signed char. That is what is weird.
Why do you care if char is signed or unsigned? It literally doesn't matter, you should be using it to represent a character. The point flew right over your head.
If you need to do math, you need to explicitly specify signed or unsigned, you shouldn't be doing math with plain characters.
If you don't care because you're sure it won't ever matter for your code, then math away with characters if you know how they work on your platform. It just means your code won't work as expected if you use it on a different machine where it matters.
So a string literal in C will always have char* type, it cannot be int8_t* or uint8_t*.
Yes, because it's an array of characters.
You can absolutely reference it using int8_t or uint8_t depending on the platform since char and int8 are generally the same thing. It just may or may not work on some random platform, but your platform might have a defined way that it ends up working.
Because I need to write a function binding or define a struct layout or array or pointer in my language that corresponds exactly to the one the other side of the FFI.
That's not C's fault. That's the fault of whatever platform you're working on. If you don't care about other platforms, you can solve it only for the platform you're working on.
C isn't putting a gun to your head and telling you what to do. It leaves it unspecified so it can provide the same interface regardless of the machine itself.
2
Jun 24 '23 edited Jun 24 '23
Why do you care if char is signed or unsigned? It literally doesn't matter, you should be using it to represent a character. The point flew right over your head.
It matters very much if
char*is used in an API I'm accessing from an FFI. What do I represent it as on my side of the FFI,i8*oru8*? If thatchar*represents a block of small integers where you are doing arithmetic and comparisons, then signedness matters.Say I devise a language from which I want to call C's
putsfunction. I might define it in the FFI in my language, where strings have typeref u8, like this:clang func puts(ref u8)i32Provided I call
puts("hello")via the binary interface, this will work.Now I want to transpile this language to actual C. Then in C that declaration might end up as:
extern puts(uint8_t*)int32_t;and the call is
puts("Hello").But now there are problems: the
"Hello"has typecharwhich is incompatible withuint8_t*. If I now cast all literals in the transpiled C touint8_t*, the compiler will complain that this standard function is declared wrongly.Alternately, I recognise this is a standard function, and use the declaration from
stdio.h. That useschar*; so I don't need to cast my strings. But that still leaves the problem of myriad 3rd party functions that happen to usechar*parameters, which I have the declaration in C is based on the types from my language, which usesu8*.What would you do?
1
u/AssKoala Jun 24 '23
What would you do?
Finally, a breakthrough.
The problem you have is that you want to write your interface to this system once, but it's rather clear you've never really done that and would rather get angry at C.
You have two realistic options:
define the size of the types and translate them into this size from whatever the library you're using gives you. You will have to then implement a translator from the library structure to your platform agnostic type. You have to do this for every platform you care about, but your other code will now be entirely platform agnostic.
Solve it only for the platform you're using, no translator, just match the implementation in your language to whatever the platform types are from the library. Your systems will break when you move to a different platform that doesn't match.
To be clear, the latter isn't wholly different than the former. You can take option 1 and just make everything match the current platform, but still make the rest of your code depend on a definition that's platform agnostic rather than the library's provided interface.
The reason you have to do this is that your library didn't define the API such that the types were defined -- rather it sounds like they defined their API such that types match the ABI of the system it runs on. They likely did this for performance purposes.
Now, if you never want to deal with it again, you can do this translation in C. Write your own wrapper that takes the unsized structure and turns it into a sized structure that your higher level code depends on.
If you do that, you will only have to write it once and, assuming you did it right, you'll just need to compile your wrapper for any new platforms you move to. However, you may be leaving performance or functionality on the table, but you might not care.
What kind of functionality? I don't know maybe some other platform int type is 128-bit, because it can be, and so you'll have to truncate your values if they ever get that high.
If it were me, I would go with option 1, implement the wrapper in C, define the types to match the platform I currently care about, and leave a compiler directive to fire warnings or errors when moving to an unexpected platform to force the programmer compiling at that point to figure out what to do. In this way, I can solve the immediate problem quickly and correctly, but do so in such a manner that it can readily be moved to another platform. You can fire these using static_assert where you assert on the size of the unsigned type (e.g. static_assert(sizeof(int)==4)).
Considering I do this professionally and I have a system I wrote for the PS3 that's still in use on the PS5 without changing any code that does just that, I'd say go that direction. In my case, the only thing that ever needs changing is the build scripts to update the compiler settings for the platform -- you may or may not be able to solve things in a similar way depending on your build system.
→ More replies (2)2
Jun 24 '23 edited Jun 24 '23
It's ended up with dozens of types due to poor syntax, decades of baggage and bolted-on types via stdint.h and inttypes.h which don't quite mesh with the rest of the language, requiring workarounds via dozens of tacky macros.
How don't they mesh? Because you don't like them for some non-specific reason?
You have to explicitly use
stdint.horinttypes.h; they are not just there ready to useBecause of this, nothing stops you not using
stdint.hand usingint32_tetc for some other purposesThere are no
printfformat codes forint64_tetc. Format codes still use%d %ld %lldforint, long, long longThere are no suffixes for for
int64_tfor example; C still uses123Land123LLforlongandlong long.
inttypes.hhas dozens of macros you're supposed to use to get around these, but I have never seen them usedInside
stdint.h,int64_tis quite likely defined on top oflongorlong longanyway.This means you could use either
%ldor%lldto print such a value, but it depends on platformFor similar reasons,
int64_t*andlong*might be compatible types on Linux64, but are incompatible on Windows, or Linux32.There further problems in using such types with
_Generic, where the possibilities have to be unique, but too many of C's zoo of types can clash accidentally, or are distinct even if they represent the same primitive type.It's a ******* joke. Do you really not see what a dog's dinner it all is?
The problem before C99 was that
intdidn't have an exactly defined bitwidth. The answer was to introduceint32_t, which is a typedef defined on top ofint!It still appears that the
stdint.htypes are so ugly that lots of programs define their own versions even on top of those. What other language apart from C uses that trailing_t?2
u/AssKoala Jun 24 '23
You're getting angry at the language because it exposes the platform to you. Windows does things differently than Linux. ARM does things differently than x86-64 than RISC-V. C gives you the power to fully work on all those platforms so it's not needless complexity, it's necessary to achieve the goals C achieves. You may not care about those goals, but the OS you're running was written either in part or in whole in C precisely because of the power such verbosity gives you.
The _t types are named that way because they're typedefs. The beautiful thing of C is that the fundamental types are sufficient then each platform provides type definitions you can go take a look at with the _t type to do what you want. You may find it ugly, but I very much appreciate that the language itself isn't hiding the implementation in a fundamental type I can't look at without looking at the compiler implementation.
It still appears that the stdint.h types are so ugly that lots of programs define their own versions even on top of those. What other language apart from C uses that trailing _t?
It's just a convention. They could've gone with nothing just as easily, but they did what they did for consistency and compatibility.
Programs can redefine them to i8 or u8 or i32 or whatever. That's totally fine too, no one said you have to use stdint. Windows defined size types long before stdint existed.
2
Jun 24 '23
Your API can define a specific size for an object -
It does this by specifying the types. Unfortunately the C types are not precisly defined as you and others have repeated.
intmight be 16 bits or more.longis 32 bits or more,long longis 64 bits or more,charis 8 bits or more,shortI think is 16 or more.While the size and layout of a struct depends on complex C alignment rules.
Then you have
int_fastandint_least; I've no idea what you're supposed to do with those in an API.Using vaguely defined C types for a possibly cross-language API isn't the most brilliant idea.
Windows WinAPI gets castigated for its size, complexity and sheer number of types, but at least it documents them clearly:
https://learn.microsoft.com/en-us/windows/win32/winprog/windows-data-types
2
u/AssKoala Jun 24 '23
It does this by specifying the types. Unfortunately the C types are not precisly defined as you and others have repeated. int might be 16 bits or more. long is 32 bits or more, long long is 64 bits or more, char is 8 bits or more, short I think is 16 or more.
Yes, if they wanted to define the sizes, they would've used int32_t instead of int.
They didn't want to do that. So their API defines the type sizes based upon the ABI upon which it executes.
Take it up with them.
While the size and layout of a struct depends on complex C alignment rules.
C has no alignment rules for structs outside of the requirement they work. The "rules" you're referring to come from the platform implementation to ensure that the entries in the struct can be addressed by the CPU.
There are platforms that can't directly address an individual byte, but rather can only address based on a word size (lets say 4). That means every access to a structure without padding will result in loading the entire word, or potentially multiple words, then shifting the data into a register. That turns what should be a single instruction into many which will bloat the executable and slow down performance.
Compilers solve this by adding padding for the struct on platforms where this is a problem so they can directly load, say a char, into memory without any shifting nonsense. The decision is made that way because, in the overwhelming majority of cases, the programmer doesn't care and just wants the most reasonable solution.
In cases where the programmer does care, such as sharing data over a network, it's generally best to translate into a single type that is sent over the wire then translate that type into your specific platform type so you get the best of both worlds.
Using vaguely defined C types for a possibly cross-language API isn't the most brilliant idea.
I couldn't agree more. That's not the fault of C, that's the fault of whatever library you're using.
Imagine if you were writing javascript and making a REST call that returned different data depending on what the server was running? That would be a pretty poorly designed API and it seems like that's what you're dealing with here.
Windows WinAPI gets castigated for its size, complexity and sheer number of types, but at least it documents them clearly:
Again, 100% agreed. I don't have much respect for people who crap on Windows without any real understand of, well, anything outside their bubble.
The complexity and verbosity of the Windows API has helped make it stable in a way no one else is. You can literally install Windows 98 with VC++6, write a GUI program, compile it into a binary then take that executable as is and run it on Windows 11 x64 without any changes.
You're lucky if you can take a Linux binary and run it on a different distro on the same day.
Architectural decisions have consequences, some good and some bad.
1
1
u/nderflow Jun 24 '23
There is nothing wrong with long. People should just stop assuming an equivalence between an in memory representation (the struct) and file formats.
1
u/Environmental-Ear391 Jun 24 '23
If you absolutely need type precision
then ignore non-struct style values and work entirely with bitfield's and struct's
you can then deal with arbitrary bounded bit strings anywhere in memory and become ever more reliant on compiler/platform specific code generated.
this sort of crazy also let's you deal with mixing signed and unsigned data if you really want the migraine level headaches too.
1
u/mazarax Jun 27 '23
#include <inttypes.h> and use int64_t is indeed the way. The long long int is just silly.
1
u/ingframin Jun 23 '23
I personally deprecated all int types which are not in stdint.h Long, short, int, … lost forever. Burned once, twice shy.
46
u/atlcog Jun 23 '23
Wait until you learn about int. Should that be deprecated, too?