frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

Open in hackernews

Generic Containers in C: Safe Division Using Maybe

https://uecker.codeberg.page/2025-08-10.html
94•uecker•13h ago

Comments

nly•10h ago
GCC generates essentially the same assembly for C++'s std::optional<int> with the exception that the result can't be returned in a register (a problem which will go away if the function is inlined)

https://gcc.godbolt.org/z/vfzK9Toz4

uecker•9h ago
Yeah it a amazing a far C++ has come, soon it will be almost as good as C.
JonChesterfield•8h ago
In this instance C++ is far ahead of C, because what you want for maybe<> is typestate, and that's only available in C++ because it's wedded to member functions. See https://awesomekling.github.io/Catching-use-after-move-bugs-... or similar
uecker•7h ago
Sure.
pjmlp•8h ago
Except that it is much more safer to use the type system than pre-processor glue based on text replacements, with more interesting error messages than templates.
uecker•6h ago
I don't see how it safer. I think this is just a random claim C++ people like to make without any evidence. In terms of error message, the problem is that C++ often can not produce them because due to overloading it is entirely unclear to the compiler what the intention of the code actually way. A macro-based solution also does not have ideal error message, but I do not think it is worse than C++.
pjmlp•6h ago
It isn't a random claim, is based on years of experience fixing pre-processing code gone wrong, because whoever wrote it in first place forgotten that it is nothing more than text expansion, and then someone else completly unaware that it is a macro, ends up giving a bad set of parameters.
uecker•6h ago
I spent also countless amount of hours fixing template code, so no I do not let your anecdotes count. There is certainly a lot of problematic macro code in C, but I do not think it is worse than C++ templates, and one can also write robust macros.
pjmlp•3h ago
One can also write robust template code, if that is the reasoning we're going for, enable_if, static_assert and concepts have been available for a couple of years now.

At least that is something we can agree on, C and C++ are both languages where developers could write robust code, and the large majority seldom does it.

uecker•2h ago
I can agree with this. The difference is that C++ approach is to solve problems with features people need to understand while C solves problems by only providing basic building blocks and expects people to use them correctly. In both cases it needs expertise to do this. But Rust also has this problem.
wahern•9h ago
Is this because std::optional isn't trivially constructible?
pwdisswordfishz•9h ago
Destructible. Opportunistically making it trivially destructible does the trick.
pjmlp•8h ago
Proving the point that better type system and abstractions don't necessarly produce bad Assembly, and if constexpr is used, there won't be anything on the final executable other than the actual value.

https://gcc.godbolt.org/z/31o75W5xx

https://gcc.godbolt.org/z/av6a43WeY

uecker•6h ago
You do not need constexpr, just remove the "volatile" which I put into my example only to prevent the optimizer from specializing it: https://godbolt.org/z/fs8q3sdxK

But what matters is run-time behavior for any input. And sorry, C++'s complexity still has the effect that the code is terrible: https://godbolt.org/z/vWfjjf8rP

In C, the compiler can remove all error paths: https://godbolt.org/z/GGMcc6bxv

account42•7h ago
> with the exception that the result can't be returned in a register (a problem which will go away if the function is inlined)

It's still a damned shame. Same for not being able to pass optional/unique_ptr/etc in a register.

We really need a trivially_relocatable attribute.

nextaccountic•8h ago
> Here, instead of handling the error condition, I create an lvalue that points nowhere in case of an error because it then corresponds to (({ (void)0; })), relying on the null sanitizer to transform it into a run-time trap for safety.

Isn't this undefined behavior?

lmm•8h ago
In standard C yes. But any decent C compiler will offer stronger guarantees than the minimum that the standard requires, and presumably the "null sanitizer" they're referring to is one of them.
pjmlp•8h ago
As usual, the problem is not what they have been offering for the last decades in tooling, rather what developers actually make use of.

Unfortunely many keep needing education on such matters.

shakna•8h ago
Maybe, but it is defined for GCC:

> You can store a null pointer in any lvalue whose data type is a pointer type. [0]

Though, I would expect a complaint from clang, and clang-tidy.

[0] https://www.gnu.org/software/c-intro-and-ref/manual/html_nod...

uecker•5h ago
It is only undefined behavior if it is dereferenced, in which case the null sanitizer can be used to define it to trap, so safely terminate the program. But the example then also shows how you can make sure that this case is not even possible in the final program.
layer8•4h ago
The null sanitizer is used to define the behavior, which is one of the ways a C implementation is allowed to handle situations whose behavior the C standard leaves undefined.
rowanG077•8h ago
At this point I always wonder why people who write stuff like this don't just move to a different language. You are introducing insane amounts of hidden complexity(see also the other posts on that blog). For something that just exists in other languages. Or maybe this is just a fun puzzle for the author, in which case it's totally fine.
throw-qqqqq•8h ago
You don’t always get to choose your language. Especially in the embedded/firmware area of software development, C is the most widely available option, if not the only option besides ASM shrugs
rowanG077•8h ago
Definitely. I still don't think you should swim against the stream. Just bite the bullet and write idiomatic C. The people who will have to debug your code in the future will thank you.
throw-qqqqq•5h ago
I agree 100%
windward•7h ago
It is, but the bar of what's considered too 'clever' in embedded/firmware is usually lower than this. In fact, even the ternary conditional operator is too much.
fuhsnn•7h ago
The said library is a bit farther away from the C that is widely available. It relies on C23 features, GNU statement expression, GNU nested function, sanitizer runtimes, VLA types and a very niche pattern of sizeof executing its statement-expression argument; only platforms that provide latest GCC/Clang would be able to use this.
uecker•5h ago
In the library I experiment with various things, and C23 and nested functions are not really required. And for running the code, it only relies on GNU statement expression. For bounds checking, you need need the sanitizers.

Overall, it is still far more portable than C++ or any other new language.

throw-qqqqq•5h ago
Fair point. I did not notice that. Most C-only compilers only support C99 or a subset thereof
pjmlp•7h ago
Unless you are talking about PIC and similar CPUs, there is hardly a modern 16 bit CPU that doesn't have a C++ compiler available as well, assuming that we still consider 16 bit modern for whatever reason.

Heck I learned to program in C++, back when DR-DOS 5 was the latest version, and all I had available was 640 KB to play around, leaving aside MEMMAX.

Nowadays the only reason many embedded developers keep using C is religous.

uecker•6h ago
Religion and the garbage code C++ compilers produces, incomprehensible error message, unstable tooling, and very long compilation times.
simonask•5h ago
What year is it, 1998? Am I going crazy?

I think you're making some extraordinary claims. I'd love to see some receipts. :-)

uecker•2h ago
What specific claim do you think is extraordinary: That embedded programmers still often use C, that compilation times for C++ are often very long, that the languages is less stable than C, or that code produced by C++ can be worse?
pjmlp•3h ago
I assume you are not using GCC or clang for compiling C code, given that are garbage compilers written in C++.

Still using tcc, or stuck in GCC 5 ?

uecker•2h ago
GCC was written in C but changed to C++ later. A lot of the code still looks a lot like C. And as a contributor, I would much prefer it was purely C (and compilation times for GCC itself are a pain - although I think this is not because of C++ but because some files grew to big and some refactoring would be in order)
throw-qqqqq•5h ago
> … there is hardly a modern 16 bit CPU that doesn't have a C++ compiler

There are quite a few besides various PICs AFAIK, how modern they are is subjective I guess, and it IS mostly the weaker chips. Keil, Renesas, NXP, STMicro (STM8 MCUs used to be C only, not sure today) all sell parts where C++ is unsupported.

> Nowadays the only reason many embedded developers keep using C is religous.

I don’t completely agree, but I see where you are coming from.

The simplest tool that gets the job done is often the best IMO.

In my experience, it is much more difficult to learn C++ well enough to code safely, compared to C.

Many embedded developers are more EE than CS, so simpler software is often preferred.

I know you don’t have to use all the C++ features, all at once, but still :)

Horses for courses. I prefer C for anything embedded.

amiga386•7h ago
Quite. There's standard POSIX behaviour for this. Divide by zero and execution continues, safely, in your SIGFPE exception handler.
uecker•6h ago
Because the different languages suck much more.
munchler•5h ago
So this was inspired by Haskell, but you don’t actually think Haskell is a good language?
layer8•4h ago
A language can provide useful features worth adopting, and suck at the same time.
uecker•2h ago
I think Haskell is a cool language. It is still definitely very bad for what I use C for.
dazzawazza•4h ago
Other languages internalise that complexity. C leaves it bare, human scale and understandable.

The speed at which you can write great C code often far outstrips other languages which are applicable to the problem domain.

All languages are a compromise, there are no silver bullets.

yobbo•6h ago
It might be more useful with a signature like maybe_divide -> maybe(int) -> maybe(int) -> maybe(int) ... and then a set of operations over maybe, and functions/macros for and_then(), or_else(), etc. It would be interesting to see how ergonomic it could get.
munchler•5h ago
I await the first “Monads in C” tutorial with mixed feelings.
uecker•1h ago
Good idea. This is very easy, here is a preview. https://godbolt.org/z/dME1MMr19
BiraIgnacio•6h ago
I love seeing the creative ways people implement these types of, if I can say, high level abstractions in C. Thanks for sharing
teo_zero•3h ago
Clever, but it misses the very goal of option/maybe types: forcing the user to check the result. In this implementation nothing stops the user from omitting the "if (p.ok)" part and directly using "p.value".

It could work if "maybe(T)" is completely opaque to the user; both checking and accessing its payload must happen through helper macros; the checking macro ticks an invisible flag if ok; the accessing macro returns the payload only if the invisible flag is ticked, otherwise it triggers a runtime error/exception.

Not impossible. However, you would need to replace all "p.ok" with "maybe_check(p)", which is not unreasonable, and all "p.value" with "maybe_value(p)", which might be too much for the final user...

Future AI bills of $100k/yr per dev

https://blog.kilocode.ai/p/future-ai-spend-100k-per-dev
83•twapi•37m ago•35 comments

Wikimedia Foundation Challenges UK Online Safety Act Regulations

https://wikimediafoundation.org/news/2025/08/11/wikimedia-foundation-challenges-uk-online-safety-act-regulations/
519•danso•5h ago•174 comments

I tried every todo app and ended up with a .txt file

https://www.al3rez.com/todo-txt-journey
433•al3rez•4h ago•308 comments

GitHub is no longer independent at Microsoft after CEO resignation

https://www.theverge.com/news/757461/microsoft-github-thomas-dohmke-resignation-coreai-team-transition
424•Handy-Man•2h ago•255 comments

OpenSSH Post-Quantum Cryptography

https://www.openssh.com/pq.html
246•throw0101d•6h ago•75 comments

The Associated Press tells its book critics that it's ending weekly reviews

https://dankennedy.net/2025/08/08/the-associated-press-tells-its-book-critics-that-its-ending-weekly-reviews/
24•thm•1h ago•0 comments

The Demographic Future of Humanity: Facts and Consequences [pdf]

https://www.sas.upenn.edu/~jesusfv/Slides_London.pdf
22•akyuu•1h ago•25 comments

The Value of Institutional Memory

https://timharford.com/2025/05/the-value-of-institutional-memory/
34•leoc•1h ago•9 comments

Trellis (YC W24) Is Hiring: Automate Prior Auth in Healthcare

https://www.ycombinator.com/companies/trellis/jobs/Cv3ZwXh-forward-deployed-engineers-all-levels-august-2025
1•jackylin•1h ago

Claude Is the Drug, Cursor Is the Dealer

https://middlelayer.substack.com/p/i-claude-is-the-drug-cursor-is-the
29•logan1085•2h ago•7 comments

The Joy of Mixing Custom Elements, Web Components, and Markdown

https://deanebarker.net/tech/blog/custom-elements-markdown/
28•deanebarker•2h ago•12 comments

Byte Buddy is a code generation and manipulation library for Java

https://bytebuddy.net/
16•mooreds•3d ago•3 comments

Claude Code is all you need

https://dwyer.co.za/static/claude-code-is-all-you-need.html
289•sixhobbits•4h ago•178 comments

Pricing Pages – A Curated Gallery of Pricing Page Designs

https://pricingpages.design/
121•finniansturdy•6h ago•35 comments

UI vs. API. vs. UAI

https://www.joshbeckman.org/blog/practicing/ui-vs-api-vs-uai
17•bckmn•2h ago•11 comments

Cloudflare Is Not a CDN

https://magecdn.com/blog/2025/08/11/cloudflare-not-a-cdn/
22•shubhamjain•1h ago•9 comments

Launch HN: Halluminate (YC S25) – Simulating the internet to train computer use

22•wujerry2000•3h ago•21 comments

The Chrome VRP Panel has decided to award $250k for this report

https://issues.chromium.org/issues/412578726
430•alexcos•12h ago•230 comments

36B solar mass black hole at centre of the Cosmic Horseshoe gravitational lens

https://academic.oup.com/mnras/article/541/4/2853/8213862?login=false
62•bookofjoe•3h ago•45 comments

Neki – sharded Postgres by the team behind Vitess

https://planetscale.com/blog/announcing-neki
12•thdxr•33m ago•0 comments

Porting to OS/2 – GitPius

https://gitpi.us/article-archive/porting-to-os2/
20•rbanffy•3d ago•0 comments

Designing Software in the Large

https://dafoster.net/articles/2025/07/22/designing-software-in-the-large/
41•davidfstr•4h ago•13 comments

How Boom uses software to accelerate hardware development

https://bscholl.substack.com/p/move-fast-and-dont-break-safety-critical
10•flabber•23h ago•3 comments

Wikipedia loses challenge against Online Safety Act verification rules

https://www.bbc.com/news/articles/cjr11qqvvwlo
68•phlummox•2h ago•30 comments

Learn, Reflect, Apply, Prepare: The Four Daily Practices That Changed How I Live

https://opuslabs.substack.com/p/learn-reflect-apply-prepare
12•opuslabs•2h ago•0 comments

Faster substring search with SIMD in Zig

https://aarol.dev/posts/zig-simd-substr/
148•todsacerdoti•8h ago•43 comments

Apache Iceberg V3 Spec new features for more efficient and flexible data lakes

https://opensource.googleblog.com/2025/08/whats-new-in-iceberg-v3.html
29•talatuyarer•1h ago•2 comments

Mistral Integration Improved in Llama.cpp

https://github.com/ggml-org/llama.cpp/pull/14737
46•decide1000•8h ago•3 comments

A Global Look at Teletext

https://text-mode.org/?p=23643
52•aqua_worm_hole•7h ago•14 comments

A simple pixel physics simulator in Rust using Macroquad

https://github.com/gale93/sbixel
30•sbirulo•4d ago•1 comments