257 points · by ingve · 4y ago · 196 comments
This creates a problem. How do you portably printf() an integer type that you don’t (and can’t) know the size of, like, say, a uid_t?
Before, when intmax_t was guaranteed to be the largest type, you could reliably and portably cast a uid_t userid to an intmax_t and printf() that: printf(PRIdMAX "\n", (intmax_t)userid);
But now, when any type might be larger than an intmax_t? What do you do?
(The same problem exists when reading an integer string; how do you read, say, a port number, when you don’t know what type in_port_t is? Previously, you could call strtoimax() on the string, detect overflow, and then cast the resulting intmax_t to in_port_t and finally compare for equality to make sure it wasn’t truncated.)
> There is active work in this area to allow us to transition to a better ABI and let these two types live up to their promises
Yes please. Introducing new wider integer types in your CPU, but pretending you haven’t created a new architecture with an associated new ABI, is silly.
https://thephd.dev/c-the-improvements-june-september-virtual...
That makes parsing the unsigned variant relatively simple. Undefined behavior would be end-of-game, but unsigned addition and multiplication will not invoke that (if you need he,p, look at your favorite multiple-precision library for ideas about detecting wraparound)
For parsing signed integers, derive the min and max values of the signed variant from the max value of the unsigned one ((whatever_max - 1) / 2 or something like that
Then parse your input to the unsigned variant first, then check whether it fits in the unsigned version.
Someone's got to write a paper to get it in, hopefully based on some sort of existing practice.
Anyone who uses intmax_t in a durable API (public function argument, member of public structure) is just a goof.
How would you compile that to machine code which would, when run, still give you the maximum integer on next year’s CPU with all-new super-duper wide integers?
It is more reasonable to think of a binary to be compiled to a specific architecture triplet, and if the CPU changes, the architecture must change, and therefore the ABI, and if the OS wants to run a binary from an older architecture, some emulation layer is needed.
Of course, this would be a lot of work for the operating system people if they want to run binaries from lots of what are now different architectures, and it was apparently easier to just force the C standard to abandon the entire concept of intmax_t being the largest.
- POSIX defines that in_port_t is equal to uint16_t, so for that type there's no problem at all ;)
- Don't use printf/scanf for this, roll your own
- Refuse to print/read uid_t that are outside intmax_t range
- Use an autoconf test
Similarly for the second problem you can read digit by digit in reverse order and create the number using x = 10x + d while detecting overflow.
I'm not saying that this is a great thing to need to do, but the mentioned problems aren't particularly fundamental and the solutions are CS101 stuff.
Sure, someone might come up with an architecture where that's not true. But even in an intmax_t-is-really-the-largest-integer-type world [which hasn't been true for the major C compilers for the past decade or so!], I can almost assuredly come up with some compilation modes that still conform with whichever C version you use that still causes your code to fail horribly. I don't think there's any architecture where uid_t et al would exceed uint64_t, and until such an architecture comes to exist, it's quite frankly not worth caring about.
But the "physical" size of the number as represented in memory can change across platforms, no?
Complain to POSIX so they add printf macro defines for all their implementation-sized integer types by the year 2100.
"Portably" across what? You need to narrow down the problem space and better define it.
If it's portably across a myriad of processor architectures, hardware profiles and operating systems then you would need to take the intermediate representation route (like Java). There's very little else that can be done in the face of infinite, non-compatible ABIs at every layer.
> you would need to take the intermediate representation route (like Java). There's very little else that can be done in the face of infinite, non-compatible ABIs at every layer.
No, I don’t think so. There’s an obvious solution, dictated by the architectual choices made by C (i.e. every architecture which introduces a new larger integer type, by necessity redefines intmax_t, and creates a new ABI), but the community (for reasons of their own) did not want to do it that way, and instead broke the promise of intmax_t always being the largest type.
Here is the direct link: “Use #embed from C23 today with the Cedro pre-processor” https://sentido-labs.com/en/library/cedro/202106171400/use-e...
As I write there, “The advantage of using Cedro is that the source code is the same and this way it is very easy to use different compilers, only adding or removing the #pragma line.”
I also added a command-line option to embed the bytes as strings instead of byte literals; embedding an 8 MB file, the strings variant compiled between 28 and 72 times faster depending on which compiler I used, gcc or clang. It is more efficient, but less compatible, that’s why it’s optional.
I’m considering adding some low-hanging fruit, like the number literal separators: 1'384'849 → 1384849
Maybe that’s a better idea, implement it with underscores in Cedro as it does not need C++ compatibility.
Edit: alright, it works. I also extended the parser to accept the apostrophe as part of number tokens. The only thing it does is to remove the underscores when writing.
I might need another command line option to specify whether the output should be C23:
1_234_567 → 1'234'567
or pre-C23: 1_234_567 → 1234567
1'234'567 → 1234567They should have formally defined NULL as void* instead.
> Someone recently challenged me, however: they said this change is not necessary and bollocks, and we should simply force everyone to define NULL to be void*.
I'm glad someone brought it up. The scenarios nullptr "fixes" are so minor adding a new null concept to fix them is the sort of overkill solution I expect from the C++ committee, not the C committee. It's a shame this wasn't thought-out more.
> I said that if they’d like that, then they should go to those vendors themselves and ask them to change and see how it goes.
The C committee has already broken compatibility on numerous occasions: forcing 2's complement representation, changing the type of u8"" string literals from char to unsigned char, removing mixed wide string literal concatenation (allowed in C11, disallowed in C23). It's difficult to be convinced by the argument of backwards compatibility when the committee has already broken it on multiple occasions. Furthermore, I seriously doubt compiler vendors who define NULL as 0 would take issue with redefining it as void*. This change is so minor and inconsequential there should be no push back.
>Introduce the nullptr constant
>They should have formally defined NULL as void* instead.
That doesn't make any sense to me. void* is a type isn't it? nullptr is a value. I don't see the overlap.
The C standard permits NULL to be defined as (void*)0 or 0. The issue is this creates an inconstancy when NULL is used with _Generic selection: a compiler defining NULL as (void*)0 will cause NULL to be caught by a pointer case whereas a compiler defining NULL as 0 will cause it to be caught by an integer case. This inconsistently could be solved by mandating NULL be defined as (void*)0 so it will always be caught by the pointer case.
The issue is instead of mandating (void*)0 the C committee decided to introduce a whole new nullptr concept. This duplicates the concept of null in the language and requires all C compiler vendors to modify the languages type system to account for it. So it creates more work for vendors and duplicates the concept of null all to solve this minor use case.
Exciting to see this in the standard. Once this is in all compilers, this will probably have security effects beyond C.
Fun fact: Miguel Ojeda linked to @cperciva's article and its following HN discussion in the note (N2897) to propose this: https://news.ycombinator.com/item?id=8270136
memset_explicit is just to overcome stubborn optimizer people who insist to optimize functions away (without warnings!), even when they have no idea about side-effects.
Wow, was that a requirement for memset_s? I'd never heard of timing being a something guaranteed by the *_s functions, regardless of security being in their name.
(if it isn't, hopefully somebody who knows more will post a better link)
Up until now, safely implementing explicit_bzero() has depended on various hacks that a new compiler version might drag out from under you. This should end the "arms race".
Had a disscussion about this here:
Many of those open source projects happen to only compile with GCC, exactly because they rely on GCC C.
Google has spent several man years making the Linux kernel compilable with clang, and not all of it has reached upstream to this day.
I just read the actual proposal on it. They describe an example implementation using macros and _Generic.
What’s really bad about this is that the arguments provided to these methods are used more than once in the macro body. This will cause:
- gibberish compiler errors in case of typos in the arguments,
- worse compilation times, as the compiler has to process more code.
Constructs like these may lead to an exponential explosion in preprocessed source code size. I hope that nobody implements it that way.
field *my_struct_get_field(my_struct *s)
const field *my_struct_get_field(const my_struct *s)
In practice you will choose the first instance, so you simply won't use const where you could. Which is unfortunate.It would be nice to have a shorthand for this. The nested macro shown in the paper looks like it can fix the problem, but is quite complicated. I would like something like:
autoconst field *my_struct_get_field(autoconst my_struct *s)
The returned pointer inherits the qualifiers of the argument. Inside the getter function the pointer is const, and there is only one implementation of the function.The real issue, in my eyes is, that "const" simply doesn't transfer well across function call boundaries. "const" is always only a local judgement - data that is const for one function is not necessarily const for another function. I've even read an old conversation where Dennis Ritchie was uttering concerns about const when it was initially designed.
Typically I use the const keyword only for global static data, because there it makes a real technical difference. Sometimes I declare function pointer parameters as pointer-to-const, partly for reasons of documentation, but I'm always aware of the strstr() issue.
An exponential code size increase even with the example implementation would only happen if people are nesting these functions inside each other. And while that could happen, it would be unusual to nest them very deeply. So for compilers that just want an easy implementation, and don't really care about quality of error messages or maximizing compile speed, the shown approach is probably fine.
It was a bit silly that stuff like that wasn't in either standard until this recently.
Damn, so close. Well I hope it's included next time.
Has anyone seriously proposed adding namespace to C? This feels like an obviously good addition to me. What’s the argument against it?
- What is the benefit of using A::B::C versus A_B_C, really, in terms of avoiding name clashes? I can point out one immediate benefit of doing the latter - code is easier to read because line noise is reduced (perhaps subjective but I think it will be hard arguing the other way around).
- Is it a good thing that half the code will now refer to A::B::C using only B::C or even only C? Without assistance of a program with good semantic insight (a solid IDE, etc) this only makes identifier search harder.
- Namespaces "enforce" discipline in one way - you can be sure that the symbols at the binary level will be properly prefixed. But with only a little discipline programmers can do the prefixing themselves, and in return they can move code between files (/namespaces) more freely, which is good for refactoring.
And as a sibling commenter pointed out, one factor why namespaces get called for could be lack of understanding that we can hide the "guts" of any function (or variable) using "static" linkage. There is less discipline (prefixes..) needed for these functions because they are only visible in the current translation unit.
Many C programs do not use hierarchical names like `A_B_C` as they ideally should. They instead pick a short identifier that is (often incorrectly) believed to be distinct enough.
> Is it a good thing that half the code will now refer to A::B::C using only B::C or even only C? Without assistance of a program with good semantic insight (a solid IDE, etc) this only makes identifier search harder.
If you meant that the identifier search should be possible with just grep, yeah namespace makes it harder but it's not the only cause and this doesn't explain why many other languages with less overall IDE support than C/C++ have namespaces. And I believe it is possible to design a namespace system that only needs a ctags-level automation for proper identifier search, though I don't know how you feel about ctags.
What is your list of name clashes that you experienced? How many real headaches did they give you? Or is it all a non-problem? Not a rhetorical question - I'm mostly working on smaller projects < 100KLOC.
> I don't know how you feel about ctags.
I use ctags from time to time when I have to, but I still don't like it when there are multiple namespaces that contain the same set of names which confuses navigation operations, even vim with ctags I think. Maybe even IDEs like Visual Studio, I'd have to check though what works and what doesn't.
Because they are not C-style language. In Python or Java, for example, you need a separate file to create a package. In C++ you can add namespaces anywhere you want. This makes C++ namespaces harder to maintain even with automated tools.
I suppose aliasing is useful for widely used libraries, for example if a big software projects wants to include two different versions of the same library. Or Team A wants to rename their module but make it easier for other teams that use their module to follow suit.
All that can provide some ease of use in the short term but produces more mess to clean up in the long term. IMHO.
Real name clashes between two different libraries are quite unlikely, and namespaces would only solve that problem on the source code level, not on the binary / symbol level.
And that brings you what benefit exactly? I've seen a number of projects that are preoccupied about "proper nesting", while it is 99% bureaucratics and all those projects are still a mess.
The benefits of "living under this or that" are technically zero, and with respect to human factors are minimal given that 1) you can get most of the organizational benefits of namespaces by doing A_B_C, and 2) you can also add new members to proper namespaces from external files in most languages, including C++, so there really isn't a difference w.r.t "knowing for sure".
I think not having namespaces may be an effective way to prevent enterprise programming from happening.
I was asked during the meeting why I think that name spaces are a bad idea, so here is my thoughts. I must warn you that the following may sound like an anti C++ rant, because well .... it is.
Name spaces have several bad aspects. The majority of them are that they make the code a lot less readable.
First, If I see a function call in source code, I cant assume what function is called. There may be a namespace somewhere above or in a header-file somewhere that changes the meaning of the code. It matters a lot for instance when you copy code from one file to another, and all of a sudden the code just means something completely different. Name spaces add state that changes the meaning of the code around it. When your code isn't doing what it should and you are trying to figure out why, you need to be able to trust that the code you are reading on screen is actually what you think it is. I dislike it for the same reason i dislike overloading: it makes it less clear what things you are reading really are.
(It may be argued that you already cant trust your eyes in C, because you can do lots of devious things with the per-processor, and to that I say, yes its bad enough, so lets not add more of it)
Name spaces splits the identifier in half, but its still a unique identifier.
my_module::create();
is and has to be as unique as:
my_module_create();
So what are we accomplishing? Do we have the same level of collisions? No, in fact we have more collisions because the parts can collide individually! if there are multiple my_module they will collide, and if there are multiple create in different namespaces they will collide!
my_module::create(); // one name space my_module::destroy(); // another name space
Collision! how about:
using namespace my_module; // namespace with a create using namespace my_other_module; // namespace with a create
crate();
Collision! If we instead write plain old C:
my_module_create(); my_module_destroy();
No collision.
my_module_create(); my_other_module_create();
No collision.
Beyond creating new opportunities for collisions, we create confusion by making it possible to hide half the identifier somewhere else. Yes, it can save some typing, but programing is never hard because of typing, programing is hard because its hard to understand what is going on. Namespaces solves the easy stuff, by making the hard stuff harder.
Its the age old, trap of C++ of adding something clever out of convenience, that turns out to be unclear and something that the programmer has to manage.
Further, namespaces encourage people to use short common names even further, because they think it saves them typing, and they think if it goes wrong they can always manage it with namespaces, and then they end-up having to manage something they shouldn't have to manage in the first place.
I have never had a namespace collision in 20+ years of C programming. Why? Because I use long descriptive names, that always start with where the functionality resides. Its readable, straight forward and works. Namespaces is a complicated system for managing a problem that should never happen in the first place, unless the user is very careless. We should not encourage carelessness.
I think C, should take some blame for this being a problem because the standard library have far shorter names then is advisable. It has made people think that names like: "jn" or "erf" are good examples of unique, clear and descriptive naming. The added wrinkle of "significant characters" has made people think that C mandates short names, something that no major implementation requires. There also seems to be a persistent belief that display technology has not yet evolved to the level that we can display more then 80 characters per line and that we therefor need to use short cryptic names for everything. This is also an argument from a different age.
Namespace collision in C almost never happens between 3rd party libraries, it is almost the exclusive problem of the standard library because it is so poorly named. If we want to fix this, by hiding the standard library behind a namespace, we might as well just add a c_standard_lib_ prefix to all functions, and keep the garbage that is namespaces out of C. Not that we would do either, since both world break backwards compatibility. So why would we add namespaces if it wouldn't be used by the standard lib, the very library we have name collision problems with? In fact if we added an optional namespace for the standard lib, all we would accomplish is to pollute the namespace with one more identifier.
using namespace my_better_name = my_module;
//....
my_better_name::create(); // colision gone
Problem solved, better improve your C++ knowledge.The C standard library should have (maybe as early as C11 or C99) picked stdc_ as a "namespace", reserved it, made it a warning to put things in it, and used it for everything going forwards.
What C needs is not namespaces, it's a module system, so that symbol visibility can be more tightly controlled.
I agree that optimizing number of keystrokes is a bad goal, but in my opinion that isn't the selling point of namespaces. The benefit is better readability. Code written with namespaces lets your eye focus the semantic name of the method, not extra character noise that was added as a form of manual name-mangling.
This is highly opinionated, of course, because there is a tradeoff with the ability to uniquely identify a method at a glance, as you mentioned. Which camp you fall into is likely to depend on what sort of software you write and whether you use an IDE or a text editor.
In C++, it is intentionally not straightforward to know what code gets called when a statement is executed - even without namespaces. We have:
* Function overloads
* Non-trivial (and not-built-in) implicit conversions
* Non-trivial copy and move constructors
* Template and concept resolution, which can be tricky
* Operator overloads, so that foo[n] or bar() may do something very different than what you expect.
And if you add in macros to the mix, you can really go crazy. For example, in this SO answer: https://stackoverflow.com/a/70328397/1593077 I explain how to implement an infix operator which lets us write:
int x = whatever();
if ( x is_one_of {1, 3, 42, 7, 69, 550123} ) {
do_stuff(x);
}
C is simply not that kind of language (well, macros notwithstanding I suppose).With your example, both a switch and simple if-else chains would be perfectly readable and also easy to write.
By now if a "module prefix" is bigger than say 4-5 characters, I get unhappy and know I need to improve, to find a short mnemnonic. Same goes for local variables names, which I try keep at 1-5, rarely they get 10+ characters long. There is always this tension between names being "self-documenting" and "just long enough to remind of the purpose that was explained in a not too distant context". Variables that are frequently used should be shorter. Variables that have a clear intuitive use (like "x" or "i" which most often have very clear meaning with only little context added) should be shorter. Module names should _always_ be very short because (I assume) there are only few modules, and it's better to remember the purposes of a few modules together with their abbreviated names, than to have to read a long repetitive module name each other line. Function name suffixes (without the module prefix) should often be long because there are many different functions and not all of them can be cached with their meanings in the programmer brain - so I allow function names to be a little self-documenting typically.
I agree that the names in POSIX and C are too short and cryptic but think they made more sense in the context of Unixes of the 1970s when projects weren't as big as today.
I still try to stay within 80 or 100 columns because line length a readability / eye strain concern as well, but given that I'm in the 8 spaces camp I don't freak out anymore if there is the occasional 140 characters line and I'm to lazy to trim it down. Judicious insertion of linebreaks is most often useless busywork. Then again, some function signatures take too many arguments (glVertexAttribPointer/glBufferData... or the Win32 API come to mind) and inserting linebreaks in calls can improve readability sometimes.
I have that problem, repetitive prefixes getting in the way of reading the code, and I’ve been doing some experiments with what could be described as “local namespacing”, only inside an expression or statement, with the prefix/suffix feature of the backstitch macro in my C preprocessor:
https://sentido-labs.com/en/library/cedro/202106171400/#back...
For instance, writing a program with libxml2, I write:
Next(reader) @xmlTextReader...;
which gets translated to xmlTextReaderNext(reader);
and I find the first easier to read.Whether that’s the case for others, I don’t know.
A longer example from the link I wrote above, this time for libuv:
@uv_thread_...
t hare_id,
t tortoise_id,
create(&hare_id, hare, &tracklen),
create(&tortoise_id, tortoise, &tracklen),
join(&hare_id),
join(&tortoise_id);
Result: uv_thread_t hare_id;
uv_thread_t tortoise_id;
uv_thread_create(&hare_id, hare, &tracklen);
uv_thread_create(&tortoise_id, tortoise, &tracklen);
uv_thread_join(&hare_id);
uv_thread_join(&tortoise_id);std::opinion::bad_idea()
;)
namespace foo { void x(); }
and namespace bar { void x(); }
and then you have to rely on compiler vendors to use the same mangling everywhere otherwise you end up exactly at the C++ position where there are multiple incompatible name mangling schemes, thus C code compiled with e.g. cl.exe would not be able to call a C function compiled with gcc (and FFIs wouldn't be able to either so you loose the "easy language bindings" "feature" of the operating system ABIs)Annex K tanking badly was just sad. At least they finally standardized strdup().
Some of the string functions, like strtok() or strcat(), and I would also include strdup(), are broken beyond repair and should simply not be used. The only way to "fix" the library would be to remove these functions, but I assume this would create more trouble with legacy code than it's worth.
C strings are mostly a useful storage format for small strings, including string literals, and as a "default" string type for the little basic functionality that is expected to be part of C to support a small program growing up - including printf() and friends.
For longer strings, you are expected to build datatypes that fit your usecase, and that includes decisions about memory management. It should not be the responsibility of the language to make these decisions for you.
Perhaps they're just to give you a better understanding of the more minor details/intricacies of the language, but I couldn't help but think with a lot of their code, if I saw a coworker write something like that I'd roll my eyes that they didn't do it in a more obvious way.
> struct T_slice { T* ptr; size_t len; };
with all the syntactic sugar and bounds checks added in. This could catch so many out of bounds issues and doesn't seem that hard to do.
int arr[..];
syntax for such things. But, our plates are full and the proposal wasn't written: it'll be up for next release, for sure, and it's one of the many things I would like to put in the language.
I always thought it was silly that the best way to embed a resource in a binary using CMake was to either convert it to hexadecimal C array manually or use specific flags with ld to convert it into an object (and good luck getting that to work reliably with cross-compiling!).
Unfortunate characterisation of constexpr in C++ over revisions as feature creep. It's more that any C++ should be executable at compile time with constexpr ultimately going the way of the register keyword, but selling people on things like compile file I/O is a long game.
Ultimately though it's hard to be too excited. I don't have a use case for C any more, beyond keeping some old code alive (with fstrict-aliasing et al and a sense that I really should port it to something else before I can no longer get any compiler to build a program out of it).
If you want a better C, do yourself a favor and use D
Same syntax, more secure and with modules
Every language has downsides/upsides and time. There is a nice quote by Titus Winters: “Engineering is programming integrated over time”[0], this helped me a lot in learning that context matter for tools/languages/frameworks, and you can learn with their mistakes.
I'm still waiting for tagged unions, tuple and pattern matching
auto and #embed is nice to have though
You'll have a hard time pushing for those: C will likely never get them in those forms. At least, not for another 10-20 years, since there's no existing C compiler that implements any of those things yet.