348 points · by shakna · 6y ago · 184 comments
> printf("%s\n", "Hello, World!");
>
> That's an awful lot of symbolic syntax.
Well... Because it should have been printf("Hello, World!\n");
in the first place?One can do something like
printf("%s,%s%c\n", "Hello", "World", '!');
and claim that C is awful and that displayln("Hello, World!");
is so much better. double foo = 1.2;
printf(foo);
puts(foo);
won't compile, while double foo = 1.2;
display(foo);
works fine.Incidentally I actually think display is the only thing on this list that is probably worth using, you could also probably extend it to accept multiple arguments relatively simply as well.
puts(“Hello, World!”)
which has been in C since the dawn of time?[0] https://gist.github.com/shakna-israel/4fd31ee469274aa49f8f97...
All of these are valid:
displayln("Hello, World!");
displayln(100);
displayln(1.8);
The point is, for simple things, to not have to specify how they appear.> Well... Because it should have been
> printf("Hello, World!\n");
No. You don't really want to do that. If you're doing that, use puts [0] . All this requires is a modification to one string in memory and you have an injection vulnerability.
I'm pathologically lazy.
Also as others point out typically the literal string will be in a ro segment so tampering with it won't be easy unless the code runs in a rather exotic environment.
This is not the case for RO strings, is it?
By modifying the start of that string, you can begin reading and writing to various parts of the stack.
Whilst implementations may inline that string into a RO memory region - that's not defined behaviour, so you shouldn't depend on it.
[0] https://owasp.org/www-community/attacks/Format_string_attack
But there's also the appeal of the dreaded Incunabulum...
#define TYPE typedef
#define STRUCT TYPE struct
#define UNION TYPE union
Well, that's extremely opinionated. Which I guess is the point. It does seem to add a BASIC-ness to the code.However, when I see landmines like these:
#define TRUE (-1)
#define FALSE 0
I might just hide instead of touching it.I might just hide instead of touching it.
This code (the Bourne Shell source) is actually the reason why the IOCCC was created.
In this case, that language is the C Preprocessor, already well documented and widely accepted as a Bad Language To Start With.
The title of the article is misleading: it's not "destroying C" it's writing Bad Code using the C Preprocessor. It's not destroying C any more than a series of bad puns destroys the English language.
But it's more fun to do in C.
Pretty sure I pointed that out:
> Can we turn C into a new language? Can we do what Lisp and Forth let the over-eager programmer do, but in C?
---
> The title of the article is misleading: it's not "destroying C" it's writing Bad Code using the C Preprocessor.
To put it another way, when I look at something like this, I might moan and say, "They've ruined it."
It's an expression.
There's been a lot of noise on the internet about Rust and C++20 and "modern" languages. I recently had an opportunity to try some of these first hand.
Honestly the new language features are all terrible with few exceptions. In general, anything that was added to a language to support generics or to hide pointers and memory management from the developers on a language that isn't a lisp has only produced more harm than good.
I grew up as a programmer always thinking about the underlying CPU and the underlying memory and how my code would interact with both of them. It requires greater care as a programmer and tools like static analysers, code reviews and rigorous testing are extremely important. Improving these tools and coming up with new ones is far more useful (in my opinion) than trying to update C.
Yes C has it's flaws. Sometimes, those flaws are important and a replacement language is useful. I find that Go is a very interesting replacement for C at sufficiently higher up the stack. Something like Haskell probably will best fill in the gaps between C and Go.
I'm not convinced that fixing C with something like C++ was a good idea. Similarly, anything that's trying to fix C++'s problems is unlikely to come up with a decent way to have generics and hide memory and pointers from developers.
If I was going to create my own language, I'd keep it like C, remove some of the undefined behaviors, add support for Posits, 128 bit and arbitrarily wide signed and unsigned integers, features for explicit cache management (!!!), container classes as part of a standard library, Go-lang style interfaces and bake in something like cppcheck into the compiler.
/rant
This is the double-edged sword of C and other lower level languages though. The programmer is given great power over their environment, but as the saying goes with great power comes great responsibility. Not all programmers are capable of handling that responsibility, and even those who are make mistakes from time to time. If you don't need the power, there's a strong case to be made for giving some of it up in exchange for also reducing the number of ways you could misuse it.
There will always be a place for low level programming in performance-critical code or extremely resource constrained environments, but there's a lot of software out there that spends most of its time waiting on I/O or user interaction while running on systems with gigabytes of free RAM and a half dozen idle cores. In those cases I believe the use of safer languages should be encouraged.
But I think it's pretty clear from this comment that the article has zero to do with the posted article. The article's title was provocative and humorous, bc it's abt using C in a very peculiar way. It's not about the tired argument of "should we replace C with Rust/etc." which the above poster and many others have glommed onto. This waterfall of irrelevant comments has no place next to this article which is abt a very specific, interesting set of techniques.
There was a great talk from a C/C++ compiler writer about why you can't remove undefined behaviors while at the same time keeping C like speed.
Simple example: accessing an array past it's end it's undefined behaviour. If you want to remove this, you need to add bounds checking (either to raise an error or to just return 0).
I don't think this is true. Look at Zig, they don't seem to have a problem removing a lot of C's undefined behaviour, while still being able to surpass C in speed in many cases.
> Simple example: accessing an array past it's end it's undefined behaviour. If you want to remove this, you need to add bounds checking
Zig does indeed do bounds checking. I think the way it can still compete with C is: - Zig should be better at propagating constants (Better module system, Link-Time Optimization by default, and I think avoiding undefined behaviour helps here too). Arrays/slices do often have constant bounds. - You can choose to build with or without bounds checks (--release-safe, --release-fast). This means you're more likely to discover out of bounds problems during debugging, since you'll always get errors in those cases. But you have the option to release a fast version.
Julia has another interesting solution to bounds checking, where you can mark a piece of code with @inbounds to declare that you assume array access is within bounds.
I think some undefined behaviour can also be detrimental to performance. If you pass two pointers to a function, and it's undefined whether they alias or not, there are optimisations you can't do.
I think this results from a misunderstanding of how undefined behaviour works in C. When a program exhibits undefined behaviour it is not a valid C program. The compiler may just assume (instead of having to prove) that it doesn't happen.
Example: the memcpy(3) standard library function. C says the behaviour is undefined if the given areas overlap. That means the implementation can perform optimizations "knowing" that there is no overlap. A valid C program can't possible invoke memcpy with buffers aliasing each other (because then, the program would be invalid). The compiler is not required to issue a diagnostic about these kinds of incorrect programs and just compiles your code assuming they don't exist.
This is absolutely correct. The specs of C allow so much undefined behavior in order to let the compiler just emit the instructions for the arithmetic operation or memory access or whatever. For edge cases like overflow and bounds, C deliberately says "not my problem" and you just get whatever that hardware architecture happens to do with that instruction. It's a deliberately leaky abstraction.
> Simple example: accessing an array past it's end it's undefined behaviour. If you want to remove this, you need to add bounds checking (either to raise an error or to just return 0).
What's wrong with saying "it will either return an unspecified value or trap"?
I understand why you would want explicit memory management, but what specifically is harmful about generics?
The compile time generics is kind of necessary to replace some of the stuff people use C preprocessor macros for. I think Zig is just taking the idea of having compile time evaluation of code to its natural conclusion, and it ends up being a lot cleaner than C with preprocessor magic.
The only thing they've added which isn't necessary for a "better C", is the async stuff they're working on now. But I think it's still a good idea.
I also suspect that Haskell fits above Go, not between Go and C.
Other than that, I'm pretty much in agreement with you.
And yet, even projects filled with extremely strong engineers who participate in all the best practices and run interprocedural static analysis and sophisticated fuzzers still write piles of security vulns in c programs.
In particular: "remove some of the undefined behaviors" I think the confusion caused by this is not nearly worth the optimization gained.
Compiler folks will say "but look, this loop is 58% faster!" but ignore the fact that slow code can be optimized through other means, including profiling, restructuring, etc.
This is more of knowing your language and tools. UB isn't some magic beast either, it's where it isn't really feasible for a language that runs on many platforms to dictate what happens. What should the std's say when you shift a signed int too far? Often the HW will have a way of doing it and others will not, so either don't do that or know your implementation
Why should I care or need to worry about pointers and memory management in every part of my code?
Yeah as a C# developer I need to be aware if I'm passing a variable by value or reference.. but I don't want to and should not need to define this all the time. I know that built-in simple types (int, string, double) etc are passed as value... and everything else is passed as reference. So it's basically a non-issue.
I grew up learning C/C++ and having to deal with all the crap. Why oh why do I want to handle all of this myself?
I just want to code and focus on getting things done... C#, for example, allows me to do that.
You saying these things have "produced more harm than good" is so obviously coming from a more academic standpoint, or purist in the sense of "oh my god he doesn't even realize that those 8 bytes are going to be held up until the garbage collector comes, whereas I can deallocate that precious memory right away!". Sorry but almost no one cares. Yeah there are times where you need to care, but for most developers that time is... never.
The elitist attitudes on HN are astounding sometimes. Heaven forbid someone code without also managing every aspect of the underlying hardware!
If you are operating within a managed usermode level of an operating system then what you say is perfectly valid, especially for programs that do not require high availability such as web servers. You can program in a managed environment and trust in your languages JIT/GC to handle low level optimization.
On embedded systems, software that requires high availability (video games for example), or kernel mode drivers and firmware, you are not always allowed that luxury. Understanding of and strong micromanagement of how memory is allocated and moved around the system becomes more and more crucial. It could be hardware limitations of the device that cause this, or in the case of firmware or drivers, any overhead that would be acceptable in a usermode application will be felt throughout the environment when you work on low-level.
TLDR you and the parent post are talking about apples and oranges.
C++ lambdas don't suffer from this problem.
IIRC compound statements, like I've presented, don't use trampolines. Nested functions definitely do, but that isn't quite what we're doing here.
GCC _should_ compile using descriptors for the compound statements that lambda is expanding to instead of using trampolines.
gcc -fno-trampolines -I. examples/lambda.c
Works. There's no trampoline present. #define lambda(ret_type, _body) ({ ret_type _ _body _; })
I found this one really fascinating, they're using both statement expression and nested functions. Their (reformatted) example of: int (*max)(int, int) =
lambda(int, (int x, int y) { return x > y ? x : y; });
macro-expands to int (*max)(int, int) =
({ int _(int x, int y) { return x > y ? x : y;}; });
So they have a statement-expression with just one statement in it - the value of that statement is the value of the whole statement-expression. And the one statement inside the statement expression is a declaration of a nested function named _. Statement-expressions decay their return types, so that function gets converted to a function pointer. And thus your "lambda" is a pointer to a GCC nested function. { ret_type _ _body _; }
Notice the second underscore at the end? The compound statement contains a nested function definition followed by an expression statement which "returns" the function just defined. The function definition alone wouldn't work.If you reference the outer scope inwards, however, you will end up with an executable stack. And you won't have a borrow checker to tell you the the value that the lambda mentions is no longer at the same address. In fact, you have no flags to warn you of that event.
C++ has lambdas. GNU-C has a hack that is truly terrifying to behold if you use it to the full power.
I'd try myself but my gcc doesn't recognize -fno-trampolines.
// Original macro hack by Robert Elder (c) 2016
Described also back in 2000 on https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html[0] https://books.google.ca/books?id=9f9uAQAAQBAJ&pg=PA9&lpg=PA9...
The various BSDs use the Almquist and Korn shells for /bin/sh nowadays. Indeed, M. Van der Linden was out of date even back in 1994. At that time, BSD had already been largely freed of AT&T code, such as the Bourne shell, for 3 years. It's now approaching 3 decades.
(I ended up using this in a job once. They didn’t hire me back...)
Example:
// remove more clutter
#define O printf
#define R return
#define Z static
#define P(x,y) {if(x)R(y);}
#define U(x) P(!(x),0)
#define SW switch
#define CS(n,x) case n:x;break;
#define CD default
1 - https://github.com/KxSystems/kdb/blob/master/c/c/k.h typedef char C;typedef long I;
typedef struct a{I t,r,d[3],p[2];}*A;
#define P printf
#define R return
#define V1(f) A f(w)A w;
#define V2(f) A f(a,w)A a,w;
#define DO(n,x) {I i=0,_n=(n);for(;i<_n;++i){x;}}
I *ma(n){R(I*)malloc(n*4);}mv(d,s,n)I *d,*s;{DO(n,d[i]=s[i]);}
tr(r,d)I *d;{I z=1;DO(r,z=z*d[i]);R z;}
A ga(t,r,d)I *d;{A z=(A)ma(5+tr(r,d));z->t=t,z->r=r,mv(z->d,d,r);
R z;}
V1(iota){I n=*w->p;A z=ga(0,1,&n);DO(n,z->p[i]=i);R z;}
V2(plus){I r=w->r,*d=w->d,n=tr(r,d);A z=ga(0,r,d);
DO(n,z->p[i]=a->p[i]+w->p[i]);R z;}
...
1 - https://code.jsoftware.com/wiki/Essays/Incunabulumhttps://minnie.tuhs.org/cgi-bin/utree.pl?file=V7/usr/src/cmd...
> In October of 1979 I had a pre− processor, called Cpre, that added Simula− like classes to C run-ning and in March of 1980 this pre− processor had been refined to the point where it supported onereal project and several experiments.
Recognising that you could do it that way is kinda awesome. Maybe not entirely uncommon, but you drafted a powerful bit of software yourself.
Interesting stuff:
"Cfront [the fist c++ compiler] was (and is) a traditional compiler front− end performing a complete check of the syntax and semantics of the language"
"[...] the C compiler is used as a code generator only. [...]. I stress this because there has been a long history of confusion about what Cfront was/is. It has been called a preprocessor because it generates C, and for people in the C community (and elsewhere) that has been taken as proof that Cfront was a rather simple program – something like a macro preprocessor."
Cfront being a preprocessor is something that gets repeated often. As you correctly point out, cpre was the preprocessor and it wasn't realy C++ yet.
The library that this post is a subset of, actually does have a testsuite. It compiles every example, and it's own documentation. The testsuite still needs to grow, and check evaluations rather than whether something "works", but it's getting there.
No kidding.
Details here.... https://www.ioccc.org/
The first proposed macro displayln is the archetype of malpractice. What if I want to do:
if(some_condition) displayln("enjoy debugging that");
etc etc... almost all proposed changes seem to be awful ?
> What if, for a moment, we forgot all the rules we know. That we ignore every good idea, and accept all the terrible ones.
Amen, brother! For a language that has been so supremely successful in the "real world", i simply don't understand the HN crowd's disdain for it.
As an aside, "printf format strings" are actually a DSL and hence the complexity. In their book, The Practice of Programming Kernighan & Pike actually show how to implement something similar for Network Packet encoding/decoding. It is quite neat and validates the power of this approach.
Sourcehut? Sounds great- I'd love to replace my Gogs/gitlab instance with something more lightweight. Let's download the source and run it. I guess click on "git" on https://git.sr.ht/? Wait that's where I already am with no indication that that is the selected tab. Ok maybe the link for sourcehut? https://sourcehut.org/ Cool. There's some links about pricing, ignore that and click on "100% free and open source software" Now I am just at a list of what appears to be about 20 repos, all with helpful names like sr.ht-apkbuilds.
I can tell that this person has put a ton of work into making something that is probably fantastic, but it is really all presented in an undiscoverable way. I still have no idea what language this project is written in, how to deploy or maintain it.
I assume https://git.sr.ht/~sircmpwn/git.sr.ht might be what I want, but it still looks like the inscrutable mess that reminds me of hgweb. There's not even a readme on the first page, let alone the source or anything useful. There's a link to https://man.sr.ht/git.sr.ht/installation.md. Which looks like it might be what I want, but I guess I'm old and at this point I've lost interest.
I'm definitely being crotchety, but I wish this information was organized in a more useful way. I can tell Drew has put a lot of time into it, but I don't feel like it is being shared in an effective way. And I would definitely never pay for software like this. Please someone tell me I'm crazy and this UI makes perfect sense to them.
It isn't surprising that the main interface is pointing you to _use_ it, rather than deploy it.
If you click on the help hub, _man_, you'll find what you're looking for straight away:
> Hacking on or deploying sourcehut yourself? Resources here.
---
> I guess click on "git" on https://git.sr.ht/? Wait that's where I already am with no indication that that is the selected tab.
That's incorrect. If you look to the left of the nav bar, you'll see some text with red highlighting exactly where you are.
> I still have no idea what language this project is written in, how to deploy or maintain it.
If you click the dev resources link, then you'll find this nice and obvious quote:
> sr.ht core is a Python package that provides shared functionality across all sr.ht services. It also contains the default templates and stylesheets that give sr.ht a consistent look and feel.
That looks part of the "logo", not part of the navbar. There is at most a minimal difference in the actual "tabs". Of course the reason is that this isn't actually a navbar/tabs but a list of applications offered by sourcehut, this is really noticeable if you click on git when you're at an actual git repository (e.g. https://git.sr.ht/~sircmpwn/scdoc) note that the red text highlighting where I am already says git, so clicking on git shouldn't do anything if it was actually a tab bar, but in reality it navigates to https://git.sr.ht/
Anonymous non-user people allowed on issue tracker that doesn't have to be linked to any repo? Awesome. (And you can export easily.)
Easy to combine multiple build projects into a single build that can be kicked off by any one of the projects? Sweet.
Drew is also really responsive if you run into any problems.
There's also all the examples [1].
<3
But not when printing to stdio.h text streams; \n turns into the right line ending.
Only on some, but not all, compilers. I got varying behaviour until I went ahead and did it myself.
evil.h == arduino.h