13 ms·
Modern C and What We Can Learn from It [video]
- harry8 5y agoAssociation of C and C++ Users (ACCU) They should really just call themselves the ACU, they are wildly pro C++. It's progress that there is even a C talk at all at their conference but even looking at the title it's pitching itself at "No really, C isn't completely worthless" One day such language wars might seem quaint. While everyone has their livelihoods tied to their chosen technologies it probably won't. C++ is fine imho fwiw. It's just not anything like "always and everywhere a better choice that C which should be treated as a virus." The Scala folk are worst at it around here that I've seen but my experience may not be yours. People used to say similar of the LISP people on newsgroups. Perl was the first I saw where Larry and co. spent a lot of resource trying to make that not happen in the community. Python did a decent job following from what I've seen. C++ has always been pretty brutal in silly ways. I hope for it to calm down. Having one purely C talk at the conference of the Association of C and C++ users might be considered in some spheres to be "progress of a sort." edit: disclosure. I am a member of the ACCU.
- lmilcin 5y agoIn my experience, I have to qualify I program "ANSI C", otherwise people assume that I am really talking about C++. I list ANSI C and no C++ in my professional experience and yet I have had a bunch of people call me to seriously talk about me helping in their C++ project. Maybe I shouldn't fault recruiters too much, though they should probably understand what language they are hiring for. But some of these guys were technical managers. It kinda seems to me a lot of technical world assumes C died and C++ is newer and better version of it, which obviously is wrong way to look at it. These are separate languages that for unfortunate historical reasons share a lot of tooling and language syntax.
- harry8 5y agoIf you can program C well, C++ isn't going to be too much of a problem for you. The reverse is not necessarily true. If I were hiring on a C++ project I'd definitely want to talk to someone who is genuinely good at C - they may not want to talk of course.
- lmilcin 5y agoI have been programming professionally for over 20 years in languages ranging from assembly to Lisp and everything inbetween and applications from embedded to Linux kernel, to OS, to backend systems to algorithmic trading. That I don't touch C++ is my choice because after years of development I decided that most of all I value simple and readable code, working with people who like to write simple and readable code or helping projects write simple and readable code. And C++ and community is, in my opinion, anything but about simplicity and readability. For some reason I do not fully understand, C++ projects I have participated are a contest of who can think of more convoluted C++ construct that nobody ever will be able to understand and C++ seem to be absolutely perfect platform for it. Even if I am able to understand it (which I frequently do not), I just can't rationalize putting crap like that in a project that is expected to then be grokked and modified by new developers. I have tried restricting the types of constructs and C++ syntax used in projects in the past but this inevitably causes flamewars and lots of discussions about why these rules were instituted and whether they are necessary. I am sick and tired of explaining the value that exists in moderation and restriction.
- harry8 5y agoyep. That's a reasonable view. Hence: >> they may not want to talk of course. C++ as an indicator of dud project, poor team and programmer lack of taste is valid. It isn't necessarily always true but there's no reason for you to care if you've gone that way and it worked.
- wruza 5y agoNo upvote can tell how much I relate to this. The only way to get a good maintainable C++ code is to hire very mediocre programmers whose “C++” really means “Qt with some shared ptrs”. The reason (I believe) is that complex things are like hard drugs for smart people. Instead of solving business tasks, which honestly are often just boring, they long for an art in programming. In C++ this inevitably leads to solving non-existing problems in a most complex, efficient and unstable way that requires a hard set of prerequisites to work, and then these break. You can see it on forums. C, python, js folks discuss libraries, idioms and best practices, and C++ folks discuss a turing completeness of template metaprogramming and the most obscure ways to pass results up the callstack without copying 8 to 24 bytes. Almost no one I talked with there actually worked for someone who actually needed these microscopic gains all over the code. Or who understood what they do beyond “it’s complex and expensive, but in the end they deliver the results we need, so that’s justified”.
- varajelle 5y ago> C died and C++ is newer and better version of it That's kind of my opinion. C didn't die for legacy reasons, but starting new project in C seems a nonsense to me. C++ just has so many features that makes the development of programs and libraries easier, for almost no extra costs.
- harry8 5y agoThis is a perfectly valid and fine opinion for many new projects. Possibly even most. The point were I dismiss this sort of thing is where it is "all" new projects.
- Y_Y 5y agoMaybe you're just an unusually talented coder, but I pay dearly for every little extra bit of C++ my code touches. It's often worth it, but never a freebie.
- mettamage 5y agoI'm distinguishing between a hobby perspective and a professional perspective. IMO that really depends on the project size and goal of the project. I've written a C++ project of about 1000 lines (algobot trader with some optimized data structures in keeping the order book consistent). I've written it in VS Code, used a GUI debugger and I haven't really paid for anything. Meanwhile, I have this friend that programs so much C++ that his mantra is "in C++ assume all tools are broken." When I hear his horror stories, oh dear! Heisenbugs come by every 2 to 3 months. So for small projects that aren't touching the lower OS/systems level parts, you're not paying any extra costs. However, the deeper and further you go, I'd fully agree.
- fnord123 5y agoAre you sure you're not hitting heisenbugs every 2-3 months?
- lmilcin 5y agoThe issue is for small project you don't really require C++ over C. Because supposedly the price you pay for abstractions has better returns the larger the application is (and that is generally true). My largest C project was 60k lines of code. The code was very, very dense. It had a lot of functionality that had to be packed to as little code as possible (due to memory limitation). It had things like transactional log-based database working in very small, static amount of memory, point in time recovery (so if the application failed it could restore itself to a number of possible checkpoints before the failure), parsers for various protocols (BER-TLV, for example), a lot of cryptography and custom cryptographic protocols, a GUI framework for a small monochromatic screen and keypad, drivers for a bunch of devices (thermal printer, external pinpad, etc.), SSL, a lot of business logic, state machines for talking to a network host, etc.
- derefr 5y agoI prefer C, but I technically write C++ because my “C code” sometimes uses references instead of pointers. (Why did that never become a C feature, anyway? It’s completely independent from OO/exceptions/templates/etc.) Luckily, in most any environment you can name, installing a C compiler actually implicitly installs a C++ compiler as well; so I can hand my “C code” library to people and tell them it’s C, and the fact that there’re a few .cpp files in there won’t be a problem, any more than having some .asm files in there would be. I’d like to use std::string as well, but I want my code to externally obey the C FFI, rather than the C++ one (I.e. no need for the linking code to know it needs to initialize the C++ runtime), so I can’t really use any STL. Still wishing C had a standard, portable, found-in-all-compilers prefix-length strings library...
- flohofwoe 5y ago> Why did that never become a C feature, anyway? I would rather ask, why did C++ add another reference type next to pointers ;) PS: the important part is that libraries have a C API, whether the implementation underneath is written in C or C++ isn't all that important. But IMHO once you're restricted to a C API anyway, writing the implementation in C too makes more sense because there's fewer situations where the implementation clashes with the interface.
- pjmlp 5y agoBecause that allows for out parameters and referring to memory addresses without the unsafety of dealing with pointers, something that even ALGOL and PL/I supported.
- flohofwoe 5y ago> allows for out parameters Out parameters are mostly a legacy feature from the time when C compilers didn't allow struct return values though, or implemented this inefficiently (besides, out parameters via pointers works too). > memory addresses without the unsafety of dealing with pointers I never understood the "increased safety" argument. C++ references can become dangling just as easily as pointers, and arguable they're even worse, because most of the time they look like regular value types.
- kaba0 5y agoNot trying to start a language war, but what exactly would you use C for? C++ is just as good at embedded, and you can use it as basically a slightly less foot-gunny C. And there is also Rust and Zig, if that’s not really what you want. I just can’t really use C with that amount of namespace pollution, at least namespaces should be added. And purely text-based macros are the worst thing ever.
- pjmlp 5y agoUNIX/POSIX clones.
- david2ndaccount 5y agoRust is very, very complicated and Zig is not stable.
- Arnavion 5y agoThe presenter has discovered the Result / Either monad at 00:24:16, but their proposed C implementation sounds like a really bad idea: - The flag needs to be manually inlined into every type, thus bloating the type even after the value has been successfully created. ie every instance of `file_contents_t` in your program has become the equivalent of `Result<file_contents_t>` and you have to check it for validity every time you use it, not just when you create it. - The flag is easy to forget to check. `std::optional` has that problem too with its `*` and `->` operators, but at least you have to write them, as well as the type "std::optional", explicitly. You can't accidentally use a `std::optional<file_contents_t>` as a `file_contents_t`, but you can accidentally use a `file_contents_t` with `.valid = false` where one with `.valid = true` was expected. - The `img = crop_to_cat(img); img = add_bow_tie(img); ...` example looks great when you just call the functions in sequence and expect each function to be a no-op for invalid inputs. But this breaks down when you have loops or logging or sleeps or other side effects that you genuinely want to skip. At that point you will have to start checking `if (img.valid)` manually again anyway. And if there are enough of these scattered around multiple scopes, you'll end up wanting `goto error` again. The callback-based example with `std::optional` as well as the Rust example with early returns don't have these problems. (Incidentally the Rust version uses an explicit `match` and manual return of the error for some reason, even though that particular usage pattern is exactly what the `?` operator is for.)
- enqk 5y agoHaving used the “local errno” solution, I feel you’re overstating the downsides a great deal.
- dthul 5y agoI agree. `crop_to_cat(img)` now has to be concerned with handling a possibly invalid image even though this method doesn't make sense for an invalid image. It muddies the type signature of the method and instead of `Image -> Image` (or possibly `Image -> Either Image Error`) it has to read `Either Image Error -> Either Image Error`. What if I want to apply that method to a valid image? I either need to wrap the image or provide different overloads of the method which can get quite tedious if the number of possibly "fallible" parameters grows. A macro for unwrapping and early return would be nicer.
- makapuf 5y agoIt is to be noted that designated struct initializers will be/are in C++20 (of course it has all the features, it's C++). See it here: https://en.cppreference.com/w/cpp/language/aggregate_initialization https://en.cppreference.com/w/cpp/language/aggregate_initial...
- david2ndaccount 5y agoThe C++ version is much worse. "Note: out-of-order designated initialization, nested designated initialization, mixing of designated initializers and regular initializers, and designated initialization of arrays are all supported in the C programming language, but are not allowed in C++.” Arrays designed to be indexed by an enum is a pattern I use all the time in C and designated initializers make it a whole lot safer and reduce the likelihood of a bug when refactoring.
- varajelle 5y agoThe out of order initialisation is not supported because it would be confusing with the order of destruction. Note that initializing the members in a constructor in a different order is allowed, but they are actually still initialized in the declaration order. That's quite confusing and most compiler warn about that. So in a way it's good the same mistake was not done in designated initialized. I don't know why the array notation is not allowed in C++.
- flohofwoe 5y agoApparently the array initialization clashes with lambda syntax. Regarding all the restrictions added in C++20: Clang supported the full C99 designated intiialization feature set in C++ without any issues long before C++20, so the decision by the C++ Committee to add those restrictions is quite baffling, considering that there is a solid implementation in the wild that has been working just fine for many years.
- flohofwoe 5y agoUnfortunately the restrictions added in C++20 make designated initialization quite pointless for any structs or classes with more than a handful items. Having to remember the order of initialization is too much hassle in this case.
- throwaway20014 5y agoAnyone who wants a very good modern C book that's only 272 pages, take a look at 'Effective C - An Introduction to Professional C Programming by Robert C. Seacord. [1]. It's from 2020. Robert Seacord is a Technical Director at NCC Group where he develops and delivers secure coding training in C, C++, and other languages. Seacord is an expert on the C Standards committee. > That's some solid credentials. He focuses on secure C code in the book. Here's a short article on why he wrote the book [2]. [1] https://nostarch.com/Effective_C https://nostarch.com/Effective_C [2] https://ieeexplore.ieee.org/document/9237323 https://ieeexplore.ieee.org/document/9237323
- IgorPartola 5y agoHi Robert! :)
- throwaway20014 5y ago? . I'm not Robert. Just wanted to mention his book.
- nathcd 5y agoPer the HN guidelines: > Please don't post insinuations about astroturfing, shilling, brigading, foreign agents and the like. It degrades discussion and is usually mistaken. If you're worried about abuse, email hn@ycombinator.com and we'll look at the data. https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html
- cptnapalm 5y agoI believe it's important to always mention in conjunction with this book that, after decades of existence, the No Starch finally discovered C's natural mascot: Cthulhu. Cthulhu is powerful, to be respected and feared and, if malignantly unleashed, will be the end of the world. Just like C.
- squarefoot 5y agoWhat book would you suggest for someone who started on the K&R 2nd Ed. then didn't write a line in C for about 15 years? I would appreciate something near the K&R style, but updated with the latest changes to the language, security related caveats etc.
- zvr 5y agoModern C, https://modernc.gforge.inria.fr/ https://modernc.gforge.inria.fr/
- squarefoot 5y agoThanks, looks interesting. I would order the dead tree book if it wasn't from Manning, which uses a layout that is almost unreadable to me: thin fonts and no bold text where it should be. just take a look at the difference from the CC licensed .pdf and the livebook at Manning's site, and on paper it'll be even worse (been burned before with the otherwise excellent Nim book which is hardly readable as well). Why is it still so hard to replicate the readability of the K&R after so many years? Please stop using thin fonts!
- an1sotropy 5y agoAn account of modern C should also note <tgmath.h>, which came with C99, and makes "sin()" and "cos()" do the right thing w.r.t. argument type (float, double, long double), something that has long been possible in Fortran. In C, this allows you to typedef a "real" type, set to either float or double at compile-time, in order to conveniently explore trade-offs associated with the different floating point precisions. The implementation of tgmath.h is an incredible hack though https://www.pixelstech.net/article/1324906407-The-ugliest-C-feature%3A-%3Ctgmath-h%3E https://www.pixelstech.net/article/1324906407-The-ugliest-C-...
- cygx 5y agoNote that C11 added _Generic to the language, so things like the type-generic functions from tgmath.h can nowadays be implemented in user space.
- an1sotropy 5y agoIndeed; thanks. I do appreciate knowing that <tgmath.h> does this for all the math functions in one fell swoop. speaking of FP-precision genericity, I really wish there was a format specification for printf that would reliably print a floating-point number with just enough digits to recover the bits of the given value (float or double), but the given value will already have been promoted to double since printf is variadic.
- belgesel 5y agoAlthough I disagree with some part of the presenter's ideas. I learned struct initializers and _Generic keyword from the presentation. So that is a great win for me. Now I can write safer code with the const and non-const pointer types. Suppose that I want to return a pointer to a field inside of a struct. Either I had to write const and non-const versions of the same function and use them which brings unreadable code. Or I would have to define argument as const and return non-const pointer which defeats the purpose of const in the first place. This keyword allows me to use same function name with const and non-const pointers.
- 5y ago
- amelius 5y agoIs it possible to translate C into (unsafe) Rust while maintaining both human readability and link-level compatibility?
- pornel 5y agoI've attempted to implement this: https://lib.rs/citrus https://lib.rs/citrus And my conclusion is: No. • Rust deliberately makes unsafe syntax ugly and noisy to steer users towards the good parts. • C idioms are very different from Rust, and much harder to translate to "nice" Rust than it seems (e.g. getting rid of linked lists, or translating `goto cleanup` to RAII, pointer arithmetic to iterators quickly runs out of trivial cases and becomes a Sufficiently Smart Compiler problem). There's https://c2rust.com https://c2rust.com that at least preserves semantics accurately.
- dnautics 5y agothis is an evolving, and first-class capability of zig (you can run it now, the issue isn't closed because it's an epic) https://github.com/ziglang/zig/issues/2457 https://github.com/ziglang/zig/issues/2457
- MrRadar 5y agoHave you considered D's "Better C" mode? https://dlang.org/spec/betterc.html https://dlang.org/spec/betterc.html
- dmytrish 5y agoThere is also https://github.com/jameysharp/corrode https://github.com/jameysharp/corrode I have not used it, but I doubt it's possible to translate C into idiomatic Rust mechanically.
- 0xdeadbeefbabe 5y agoWhat is isize_t?
- belgesel 5y agoPresenter doesn't give any information about it. But I think it is not a type defined in C standard and presenter's own implementation.
- synergy20 5y agoWhat I really want, is a C++ book that lists the absolutely must-have features for a beginner-intermediate programmer, I don't want to be overloaded(no pun intended) with all those 2000 advanced features, I can read an advanced level book when I'm ready. Basic types, smart-pointers(how to use them and when to use them), basic OOD and template(but no advanced tricks), essential algorithms and containers, that's about them. No need on constexpr, rtii etc for now. In this fast-paced world it's hard to get interested in any books more than 300 pages for me.
- lfowles 5y ago"A Tour of C++" is only 256 pages and the 1st edition is what I used to get into modern C++ in the workplace years after a strange mix of C/C++ labs in college.
- synergy20 5y agotrue, a great book that I'm reading now, but it's more of a 'tour guide' indeed. It's probably the closest I can find however.
- ku-man 5y agoI also wish such book could exist. Seems we have to rely in our instincts to realize when an author is getting a bit too "enthusiastic" with C++.
- jhauris 5y agoAs a professional C++ programmer who hasn't used C since the compiler limited me to C89 (so 2015ish), I am very impressed by how clean C code can look these days. This was a great talk. There are a lot of really good things in modern C, and if I ever have to use C again I will have some great new tools. And I found the "25k allocations for a single character entered" in chrome extremely shocking; it definitely pays to think about allocations in C++. Given the improvements, I found the warning not to use libc unless absolutely necessary very surprising. I suppose C++ has parts we know to avoid, but I wonder why, with all the improvements to the C language, there haven't been the same improvements to the standard library? It appears C programmers are used to rewriting pretty basic functionality for every new project, or carting around their personal utility library. I'm also still not at all convinced by macros.