28 ms·
“C is how the computer works” is a dangerous mindset for C programmers
- fortran77 7y agoSo the Rust community is now pushing anything with "Rust" in the title even if it's content free? There's absolutely nothing here other than an announcement that Mr. Kablink decided not to write this blog post. Yet the Rust community dutifully brigade-votes this to the front page.
- beervirus 7y ago> Basically, the overall thrust of this series has been this: C is not the hardware, it’s an abstract machine. But that machine runs on real hardware, and abstractions are leaky. If you go too far into “purely only the abstract machine,” you may not be able to accomplish your tasks. If you go too far into “C runs directly on the hardware,” you may be surprised when a compiler does something that you didn’t expect. Seems pretty uncontroversial for “propaganda.”
- mpweiher 7y ago> C is not the hardware, it’s an abstract machine Not sure whether it is controversial or, not, but C is very much not an "abstract machine". There are languages which define an abstract machine, and the implementations then have to map that abstract machine onto the hardware, making sure to faithfully reproduce the semantics of that abstract machine. Squeak Smalltalk is an example of this, the VM provides the abstract machine and thus images work identically on different underlying hardware. C isn't like that at all. While there is an abstract machine of sorts defined in the standard, a lot is left out of the standard in UB and IDB that says "just to whatever the hardware does", and the things that are defined are mapped closely to the hardware. And of course, some people say that "the hardware" doesn't work like that any longer, but that is the interface the hardware presents to its users via its machine language.
- gwd 7y ago> While there is an abstract machine of sorts defined in the standard, a lot is left out of the standard in UB... This is exactly why, on modern C compilers, you have to start thinking of C as an abstract machine -- because that's what the compiler writers think they're doing. But unlike abstract machines for older languages designed to be mathematically pure, or new abstract machines for newer languages designed to keep you from making stupid mistakes, the C abstract machine is full of bear-traps, such that if you ignore the "C is an abstract machine" warning, nearly any simple-but-obvious program is probably vulnerable to a dozen UB vulnerabilities.
- mpweiher 7y ago> because that's what the compiler writers think they're doing. Yep. And that's why modern compilers are such a shit show. > any simple-but-obvious program is probably vulnerable to a dozen UB vulnerabilities. I was shocked (well not really, but it is shocking) when a Googler and member of the C++ standards committee said in a talk (probably some C++ conf) that he works with the best C++ engineers in the world and none of them can write even small amounts of correct code according to the standard. Head explodes. Maybe, just maybe, there's something wrong with the standard and how it is interpreted? But apparently the thought never entered his mind.
- throwaway17_17 7y agoHard agree on ‘that’s what compiler writers think they’re doing.’ I don’t even think the concept of C being the ISA for some abstract machine is a bad concept. However, and I think it gets to the heart of your point, the compiler writers only do this or adopt this attitude when it allows them to hand wave. There isn’t the consistency that should be present in an abstract machine implementation. Now that I’ve rambled, I may make the most of this Stay-at-Home situation and write something up using the C as abstract machine concept.
- afiori 7y agoThen C is an ill-defined abstract machine.
- 7y ago
- cryptonector 7y agoBut is Rust a more faithful model of HW? I'm happy to accept that C sucks (it does) and that Rust and others are superior (they are). But if you stop at the quoted statement, you've not said much. I upvoted the submission blindly, then read it, then un-upvoted it. TFA is not useful. It would have been better to not write TFA at all. There already are many many very good articles about how Rust is better than C.
- M2Ys4U 7y ago> But is Rust a more faithful model of HW? As far as I know Rust doesn't claim to be, or have legions of people claiming it is.
- steveklabnik 7y agoI don't really understand why Rust is in this discussion at all. This isn't a post about Rust. (And Rust is not really any better than C in this regard. At least, in a vacuum. I guess you could make the argument that it's better because fewer people have false beliefs about it, but that's not an argument I'm making, either in the blog post nor here.)
- saagarjha 7y agoProbably the obvious reason: that anything you write that has even the most tangential relevance to Rust means that people will think you're talking about Rust…
- DasIch 7y agoNo, it isn't but I don't see anyone making the claim that Rust is a faithful model of the hardware. That's quite common take on C though, which is not that wrong, if you go back in history far enough. It's quite wrong today though.
- MivLives 7y agoInteresting this is less of blog post and more of an announcement that a blog post will not be written.
- fortran77 7y agoAnd yet a content-free post is gobbled up on Hacker News.
- deleted 7y ago[deleted]
- rumanator 7y agoSteve Klabnik, of Rust fame, has a good history of writing insightful and interesting articles. If you feel he isn't delivering value then feel free to output your own content instead of contributing to drive down the signal/noise ratio of HN's comments section with inane comments on other people's tastes.
- steveklabnik 7y agoYes, I did not expect this to get posted here, for this reason. The first post got a ton of attention, the second one not so much. The self-quote for the thesis for this article comes from a conversation with tptacek in the HN thread from the first post.
- antirez 7y agoActually I look forward for enough momentum to be created in the community, to allow new C standards to change the way undefined behaviors are conceived, and make them as specified as possible, and even when they cannot in reasonable unique ways, to provide reference possible behaviors to select in order to have the least unexpected outcome for the programmer. Especially now that low level programming is abstracting away, exactly but not only because of Rust itself, we need a C that is more C than what it became in recent years. After all we don't really need to change the language, but just the new specifications and the compilers implementations of UB.
- hedora 7y agoLast I checked UB was undefined by the standard, but compilers still need to define their behavior on each architecture. Dictating that all architectures implement UB the same way would have significant overhead, since it would force programs that don’t rely on UB to run in emulation on all but one architecture (at best).
- Hello71 7y agothat's implementation defined
- MereInterest 7y agoUndefined behavior does not need to be consistent, either across different programs, or within the same program. It does not need to be consistent within different times that the program is run, and it does not need to be documented anywhere. It does not need to be sensible, does not need to be predictable, and does not need to give any diagnostics to warn the programmer. Undefined behavior means that you have passed outside of the realm governed by the standard, and that HERE BE DRAGONS. Implementation-defined behavior works as you say, where each compiler can define how it responds to certain circumstances.
- gpderetta 7y agoYou are never going to get any guaranteed sensible behaviour for a double free or an use after free [1]. In comparison to those giant issues, all other instances of UB are minor. [1] well, you can today by swapping malloc for a GC-enabled implementation, but the fact is that almost nobody does.
- csours 7y agoThere's the computer, and then there's the computer, and then there's the computer and then there's the computer: The computer is the thing that has the web browser running on it. The computer is the thing that has the code editor running on it. The computer is the thing that has the compiler running on it. The computer is the thing that provides a virtual hardware interface for running programs. The computer is the thing that the virtual hardware interface interacts with. The computer is the thing inside the hard drive/graphics card/other component that the computer talks to. The computer is the thing inside the processor that pre-processes, jits, or otherwise transforms commands from the computer for the computer so the computer ... ... ... https://xkcd.com/722/ https://xkcd.com/722/
- fctorial 7y agoThere's the c1(physical computer), and then there's the c2(os runtime), and then there's the c3(silicon) and then there's the c4(turing machine): The c1 is the thing that has the web browser running on it. The c1 is the thing that has the code editor running on it. The c1 is the thing that has the compiler running on it. The c2 is the thing that provides a virtual hardware interface for running programs. The c3 is the thing that the virtual hardware interface interacts with. The c3 is the thing inside the hard drive/graphics card/other component that the c2 talks to. The c4 is the thing inside the processor that pre-processes, jits, or otherwise transforms commands from the c2 for the c3 so the c1 ... ... ... Is this correct?
- csours 7y agoSure, but you can also run non-trivial code in the web browser. I wasn't being super-precise with my comment, and my point is that there is no one thing that "is the computer". There are many computers in your computer, and many definitions of what a computer is. I've never had to go below the HAL, or inside the JIT, but to some people that's where "the" computer really is. If that's where the computer really is, then I'm not a computer programmer (HINT: I'm not, but I do write code sometimes and get paid for it). So if I write code, but it doesn't tell the computer what to do, what am I even doing? Well, I write code that gets consumed by pre-processors and lexers and parsers and compilers and linkers and build agents and I don't know how the soup works, and you probably don't either, you may know more or less of the of the alpha-bits in the soup, but it's still soup. The soup is turned into jello and fed to a virtual machine, which is a fake computer, but it works well enough. --- If I were to be more precise, I would say that there's a von Neumann machine C0 that is represented by some hardware abstraction layer C1 by a operating system kernel. There may be a virtual machine C2 running in the C1 context. But, inside that C0 von Neumann machine there are a bunch of microprocessors that may be called computers that may have Turing complete instruction sets. --- Or you could say, anything that can be Turing complete is a computer, in which case your web browser is a computer (among many others).
- spicymaki 7y agoWait until they learn that machine code is not exactly how the computer works either. The hardware is doing things to your code you might not expect.
- ForHackernews 7y agohttps://blog.erratasec.com/2015/03/x86-is-high-level-language.html https://blog.erratasec.com/2015/03/x86-is-high-level-languag...
- ThrowawayR2 7y agoAgreed, The example the author uses in his previous post on the topic talks about cache-unaware code but it's perfectly possible to write cache-unaware code in machine language as well. I'd say "C is not how the computer works ... but it's much, much closer than nearly every other language."
- pdimitar 7y agoI feel your statement is actually much closer to the danger. C is pretty close to the hardware indeed and that misleads people into thinking that C is actually exactly how the hardware works. It's a very easy trap to fall into and I've seen many colleagues do just that.
- dpc_pw 7y agoM............................................C M..............................................Java Look. C is much closer to how the machine (M) works.
- snazz 7y agoJava’s GC and lack of pointer arithmetic should push it a little further to the right, no?
- stonemetal12 7y ago
- lidHanteyk 7y agoIt's far past time to put C to bed. D, Go, Java, Zig, etc. are all languages that one can use to do approximately C-like things without as much danger. I am tired of seeing a literal Twitter feed of memory unsafety security bugs [0]. We can do better. [0] https://twitter.com/LazyFishBarrel https://twitter.com/LazyFishBarrel
- adrianN 7y agoGood luck rewriting all the programs that are written in C without introducing new security problems.
- lidHanteyk 7y agoFeel free to peruse the Twitter feed that I linked; if most bugs are due to memory corruption, then literally rewriting in place may still be a net negative in terms of total bug count! This is the main argument of Zig [0]; they offer technologies to incrementally rewrite C projects in Zig without losing compatibility. Their compiler can compile C code [1] just like GCC or Clang can. [0] https://ziglang.org/ https://ziglang.org/ [1] https://andrewkelley.me/post/zig-cc-powerful-drop-in-replacement-gcc-clang.html https://andrewkelley.me/post/zig-cc-powerful-drop-in-replace...
- BubRoss 7y agoDon't forget modern C++ and the well designed but forgotten Clay language. The reality is that go and java aren't system languages, they are just fast. More than that though the C and C++ competitors don't have the tools and libraries. When all these new languages get made, they never ease back on the language part and prioritize the next rough area. The language is argued about debated and added to with features for years or decades. Meanwhile build systems, guis, text editing with suggestions and syntax checking etc. all go into the pile of being a mess of half supported tools pieced together as an exercise in frustration for the brand new curious user.
- Tomte 7y agoC has never been "how the computer works", its abstract model is way too… well, abstract. But there is an interesting catch to it: because C is so important, and programmers at large know so little "real C", vendors do their damndest to make it work for them. A well-known microcontroller forum in Germany is constantly pushing that you need to make your code safe in the case of concurrent access to a variable by a main loop and an interrupt. By making it volatile. Strictly speaking that's plain wrong. You need some kind of mutex. Practically speaking, no embedded C compiler vendor would dare use an "optimizing opportunity" and surprise his customers there.
- icedchai 7y agoYes, except it's "less abstract" than any other language in mainstream use...
- Tomte 7y agoYou're right. But that wasn't my point. My point was that C isn't the close-to-the-machine language that many programmers think it is. That other languages don't qualify, either, is beside the point. Ruby or Java aren't mistaken to be close-to-metal. Point in case: you don't even see anything about Harvard vs. von Neumann architecture in portable C sources. Not to speak of micro code or anything like that.
- icedchai 7y agoRuby and Java aren't mistaken to be close-to-metal because they aren't. C is primarily about memory access and structure at a relatively low level. How do you explain that most operating system kernels and device drivers are written in C? Again, C is much closer to the machine than anything else in mainstream use. The C "abstract machine" is mostly a myth.
- Tomte 7y agoAgain, I don't dispute that C is much closer to the metal than Java. I'm disputing that the C execution model is adequately and exhaustively modelling the idiosyncracies of real existing modern hardware, where "modern" means "almost anything in my lifetime".
- alekratz 7y agoSomeone told me back in high school that "C is just shorthand for assembly", which I think about a lot. Does anyone else feel that way?
- Ididntdothis 7y agoI think that goes way too far. Assembly is a completely different beast from C and way more complex. There is a lot stuff you can do with assembly that C can’t.
- CalChris 7y agoI agree that they are different beasts, but is there anything that assembly can do with data which C can't do? Or are there only control efficiencies which assembly can provide which C can't?
- Ididntdothis 7y agoX86 has a lot of instructions that aren’t directly available to C and provide huge speed up. Often the optimizer will use them anyway but there plenty of cases where handcrafted assembly is much faster than anything C can achieve.
- tenebrisalietum 7y agoC lets you manipulate memory close to the level assembly allows, and C function pointers, unions, and strings are a very assembly-like thing. But assembly doesn't have the following concepts built into it, you have to manage those yourself if you want them: - The notion of functions and return values. CALL/RET implements subroutines, not functions. - Linkage that is more complex than jumps or call/returns. The ABI between units of code is something you have to define and do youself. - The notion of associating types with variables. Variables in assembly are simply labels for memory locations, but don't really constrict action or tell you how many memory locations are in the variable. Types, including valid actions, data widths, etc. are completely up to you and must be done manually in assembly.
- 7y ago
- diath 7y agoPeople simply have to come to terms that modern computers are nothing like their beloved PDP-11.
- pizlonator 7y agoThe problem with the “C is an abstract machine” nonsense is that it’s just not how it works. I get that it’s what the spec says. But C compilers are super careful to compile structured assembly style code without breaking it, even though they don’t formally promise to do so. That’s because lots of large C code based assume structured assembly semantics and probably always will.
- jcranmer 7y ago> But C compilers are super careful to compile structured assembly style code without breaking it, even though they don’t formally promise to do so. You have never worked on a C compiler, I take it. All production compilers will at some point turn even straight-line code into a DAG and relinearize it without care to the original structure of code. Any semantics beyond that which is given in the C specification (which are purely dynamic, mind you) are not considered for preservation. In particular, static intuitions about relative positions (or even the number!) of call statements to if statements or other control flow are completely and totally wrong and unreliable. This is the main reason why people keep harping on the "C is an abstract machine." When people think of machine code, there is an assumption about the set of semantics that are relevant to the machine code, and that set is often much, much broader than the set of semantics actually preserved by the C specification.
- pizlonator 7y agoI work on compilers for a living. Structured assembly semantics are what C users in a lot of domains expect and production compilers like clang at -O3 will obey the programmer in all of the cases that are necessary to make that code work: - Aliasing rules even under strict aliasing give a must-alias escape hatch to allow arbitrary pointer casts. - Pointer math is treated as integer math. Llvm internally considers typed pointer math to be equivalent to casting to int and doing math that way. - Effects are treated with super high levels of conservatism. A C compiler is way more conservative about the possible outcomes of a function call or a memory store than a JS JIT for example. - Lots of other stuff. It doesn’t matter that the compiler turns the program into a DAG or any other representation. Structured assembly semantics are obeyed because of the combination of conservative constraints that the compiler places on itself. But bottom line: lots of C code expects structured assembly and gets it. WebKit’s JavaScript engine, any malloc implementation, and probably most (if not all) kernels are examples. That code isn’t wrong. It works in optimizing C compilers. The only thing wrong is the spec.
- overgard 7y agoTo be fair, even assembly language isn't how the computer works (gets translated into micro code). Not to mention other integral components like the GPU that are coded in an entirely different model. I think what's fair to say is: the "abstract C machine" tends to have a minimal amount of concepts on top of the machines instruction set, compared to other languages, and generally provides the least friction if you need to poke a memory address or layout a structure in a very specific way. It's just easier to say it's closer to the metal because that's a mouthful.
- dooglius 7y agoNot really, assembly language is extremely close to microcode, much much closer than it is to C. C has a whole bunch of baggage like pointer provenance, inability to read uninitialized memory, doesn't understand cache aliasing, etc that don't fit hardware well.
- radarsat1 7y ago> pointer provenance, inability to read uninitialized memory what do you mean by these two? not sure about the former. as for the latter, of course you can read uninitialized memory, unless you mean something else?
- umanwizard 7y agoNo, reading uninitialized memory in C is UB.
- tspiteri 7y agoAs far as I know (and I could be wrong), reading uninitialized memory in C is not UB, but gives an indeterminate value, which may be either an unspecified value or a trap representation. If it is a trap representation, accessing it is indeed UB, but if all possible values of your memory are valid, e.g. if you have an unpadded integer where every bit representation means something valid, then it is not UB, though it is still an unspecified value which does not even have to be consistent: you could get different values when reading the same uninitialized location twice. Edit: Some excerpts from the C standard: 6.7.8 Initialization 10 If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. 3.17.2 indeterminate value either an unspecified value or a trap representation 3.17.3 unspecified value valid value of the relevant type where this International Standard imposes no requirements on which value is chosen in any instance 6.2.6 Representation of types 6.2.6.1 General 5 Certain object representations need not represent a value of the object type. … Such a representation is called a trap representation.
- xwdv 7y agoThis may be a little off topic but it is something that until now I’ve never questioned in my entire career: Is the c in C supposed to stand for “computer“? If not, what is it?
- jamesmunns 7y agoC was a successor to B/BCPL. https://en.wikipedia.org/wiki/B_(programming_language) https://en.wikipedia.org/wiki/B_(programming_language)
- CDSlice 7y agoAccording to Wikipedia, C is named C because it resulted from work done by Dennis Ritchie to improve the language B, and C comes after B. B came from Ken Thompson making a cut down version of the language BCPL, so he just kept the first letter. https://en.wikipedia.org/wiki/C_(programming_language) https://en.wikipedia.org/wiki/C_(programming_language)
- slfnflctd 7y agoIt almost implies that at the time, they realized a plethora of languages would emerge but were hoping everyone would stick with their alphabetic convention. Instead, someone skipped straight to S, someone else stepped back to R, and then everyone said screw it and started making up their own funny names & acronyms. I've read some intriguing things about D, though (which came along more recently, interestingly enough). Apparently it's in production at several large companies.
- JdeBP 7y agoThat creation myth rather falters on the fact that a fair number of languages had already emerged. This was the 1970s, not the 1950s. No-one expected language namers to follow some universal alphabetic convention beginning with BCPL.
- archgoon 7y agoIt's the successor to the B programming language (also written by Ritchie and Thompson), which was derived from "BCPL": Basic Combined Programming Language.
- oconnor663 7y agoMy favorite take on the severity of the UB problem, https://blog.regehr.org/archives/1520 https://blog.regehr.org/archives/1520 : > Tools like [Valgrind] are exceptionally useful and they have helped us progress from a world where almost every nontrivial C and C++ program executed a continuous stream of UB to a world where quite a few important programs seem to be largely UB-free in their most common configurations and use cases...Be knowledgeable about what’s actually in the C and C++ standards since these are what compiler writers are going by. Avoid repeating tired maxims like “C is a portable assembly language” and “trust the programmer.” Unfortunately, C and C++ are mostly taught the old way, as if programming in them isn’t like walking in a minefield.
- jonhohle 7y agoStatic analysis tools should be the standard part of any build process, but especially with C/C++. I’ve mentioned before here, but when I found a reasonable number of bugs in critical library used throughout one of the FAANGs written by their most senior and brilliant engineers by running a fizzier on it for a few hours, my opinion of those languages changed. Integrating Valgrind and Clang’s checker, and running AFL for many CPU years was critical in unearthing some really funky crashes, hangs, overflows. Without those tools it’s not clear that those bugs would have been fixed. In fact, one of them affected me a few months prior and AFL helped uncover the codepath that was failing.
- enhray 7y agoI don’t think that this bugginess is an inherent property of these languages, because there are other practices that could lead to reduction in total bug count and severity, apart from integrating additional tooling. Out of curiosity, how many bugs you found by using these tools could have been avoided by using a “watertight” memory management system [0], with strong decoupling of pointer and object lifetimes? [0] https://floooh.github.io/2018/06/17/handles-vs-pointers.html https://floooh.github.io/2018/06/17/handles-vs-pointers.html
- AaronFriel 7y ago
- hyperpallium 7y agoIs the world ready for lower-level languages? e.g. cache-aware. (assembly isn't) In a way, GPU shader languages "fit" parallel GPU architecture (though not cache-aware). Maybe... limited loop code-length to fit in cache; No pointer chasing (though you can workaround anything in a TM). Some java subsets for very limited hardware might be instances.
- notduncansmith 7y agoYou may want to read about Java Card: https://en.wikipedia.org/wiki/Java_Card https://en.wikipedia.org/wiki/Java_Card
- Impossible 7y agoGPU languages have some cache aware constraints, especially if you're working with the graphics pipeline vs compute where you have more constrained inputs and outputs. Shared memory is also often used as a user managed cache. Cell SPUs had explicit user managed cache and host DMA, and Intel ISPC and Unity Burst compiler/ECS (variants of C and C#) are good examples of programming environments that try to more explicitly encourage parallelism and/or optimal cache utilization.
- gpderetta 7y ago> Cell SPUs had explicit user managed cache and host DMA just a nitpick, but explicitly user managed caches aren't. They are really better known as scratchpads. A cache is supposed to be mostly transparent except for the performance implications.
- derefr 7y ago> Assembly isn’t What you mean is that the popular Instruction Set Architectures (x86, ARM) don’t expose these pragmatics. (Though the microcode architectures of the processors executing these ISAs probably do.) There are other ISAs (e.g. Itanium, most Very Long Instruction Word ISAs) that do expose these pragmatics, constraining what instructions can appear when in an instruction stream. Which in turn means that assembly code for these ISAs needs to be written with awareness of these pragmatics.
- wooby 7y ago"C is JQuery for the computer." -- Micha Niskin
- fit2rule 7y agoI've been coding since C was a new language, and surfed multiple computer revolutions in all and sundry phases, and for personal interests have recently returned to the 80's era for a broader attack at the 8-bit platforms of the time. This has required a fair bit of assembly language for old machines with a much more minimal profit motive - in fact, non-existent - just so that I can keep my machines alive - which is the reason I'm digging into things as a bit of a challenge to myself. There is so much great code to read, when you can disassemble. And, even when you can't. I have a veritable fleet of old systems, many of which are still getting new titles released at astonishing levels of proficiency, yearly now .. CPC6128, ZX (Next!), C64, Atmos, BBC, etc., all have new tools being written for them, including C compilers. One thing I note is that the tools are everything, because all tools get 'degraded' by new hardware releases. Hardware isn't driven by the compiler designer - the compiler designer is nothing until the hardware guy prints something. Returning to older computers has meant understanding their architecture, and surprisingly enough after 30 years of mainstream programming, going back to this world is rewarding. There is a lot of joy in writing in C for the 6502, or even Z80, in real mode. But, always disassemble. And, in each case, its quite easy to disassemble - get an understanding of registers and memory usage and code inefficiencies, and so on.
- AndrewOMartin 7y agoWhich is why God(bolt) gave us Compiler Explorer.
- deleted 7y ago[deleted]
- bluetomcat 7y ago"Real hardware" is also an abstract machine. Until you get to the level of each individual transistor, it's hardware abstractions all the way down. Caches, reorder buffers, load and store buffers, instruction decoding are all abstract concepts sitting at a much higher level than the individual transistor. Those abstractions are there mostly for the purpose of speeding up code execution, but also for enabling hardware designers to think about the machine in terms of real-world concepts and not just as an incomprehensible mind-blowing collection of a few billion transistors.
- SuperscalarMeme 7y agoAnd I bet you physicists argue that transistors are just abstractions of semiconductors
- j9461701 7y agoWhich is, in turn, merely an abstraction over the actual quantum physics that governs what's really happening on the silicon. And quantum physics might itself one day may be found to be a higher level abstraction of what's really really going on, as happened with Newtonian physics before it. It's abstractions all the way down. I don't know why they're so maligned by programmers, they're the only way any work gets done.
- diydsp 7y agoheh and it's even worse than that, because near the quantum level, we're mainly finding reflections of our own psychology, psyche and societal norms. This is why saying sth is "not how the machine works" is a fallacy of black and white thinking and not useful unless one is ready to be very specific abt how it resembles the machine and doesn't. wrt C, the smartest thing to do is use it wisely and avoid dragons, the same way we e.g. use chemistry to make useful products without performing operations in unstable environments. And surround it with an appropriate layer of cultural expectations - keeping humans in the loop. You don't just do what the computer tells you, you use it to help you make judgments, but ultimately take responsibility yourself. One can see this in Rust's efforts to not only develop a language, but a conscious culture around it. This will be successful until, like a 51% attack, it is outmaneuvered. Anyway...
- SuperscalarMeme 7y agoI don't think anyone suggests using C as an alternative for microarchitecture classes. C still remains one of the best ways to access hardware relative to other software languages. No language is "how computers work" unless you're writing Verilog, but C is the closest to the metal relative to other software paradigms while still being more convenient than assembly.
- gens 7y agoC is a high level language. C is close to how a computer works. Assembly is the next step down, and is not nearly as hard as the internet would lead you to believe. Step down from that; read a book like "Computer Architecture: A Quantitative Approach", and learn about cpu-s and memory (also Agner Fog's site, official amd and intel doc, many other). Down from that is electronics (logic gates, 8bit adder, etc., down to transistors and capacitors). And beyond is physics. Everything else is either computing theory or buzzwordy bullshit. To repeat: C is a high level language, no matter what anyone says.
- deleted 7y ago[deleted]
- sys_64738 7y agoC is like water. Atomically it is the DNA of all other programming languages. There's a reason why C is generally the fastest language with smaller binaries, and there's a reason why language like Python fallback to C for doing anything processor intensive. C will still be here when the latest fad languages of today are long forgotten.
- 317070 7y agoWell, it will be still here in the same way Fortran is still here. I.e. while now it does not seem to bad, there will come a time where people will wonder why anyone put up with coding in C, when it was so prone to making bugs with things that could be automated away. In exactly the same way we now frown on goto statements. But, underneath it all, there will be this layer of C-code on top of this fortran code on top of this assembler code.
- fctorial 7y agoIn clojureland we fallback to java for doing anything processor intensive.
- myrrlyn 7y agoNot a word of what you just wrote is true.
- 0xdeadbeefbabe 7y agoEqually dangerous as swimming with piranhas. Programming is so exciting if not self indulgent. Edit: Oh I get it--your manager, who doesn't believe in leaky abstraction or UB, will beat you if the program fails.
- dirtydroog 7y agoRust this, Rust that. Tiresome.
- sgift 7y agoWhat do you mean? The post doesn't contain anything about rust.
- jcranmer 7y agoOne of the blog posts I keep meaning to write is in the vein of "Why C is not portable assembly." Ironically, most of my points about C failures aren't related to UB at all, but rather the fact that C's internal model doesn't comport well to important details about machines: * There's no distinction between registers and memory in C. A function parameter that is "register volatile _Atomic int" is completely legal and also makes absolutely no sense if you want C to be a "thin" abstraction over assembly. * There's no "bitcast" operator that changes the type of a value without affecting the value. The most common workaround involves going through memory and praying the compiler will optimize that away (while violating strict aliasing semantics to boot). * No support for multiple return values (in registers). There's structs, but that means returning via memory because, well, see point 1. * Missing machine state in the form of vector support (which is where the lack of the bitcast becomes particularly annoying). The floating-point environment is also commonly poorly supported. * Missing operations such as popcount, cttz, simultaneous div/rem, or rotates. * Traps are UB instead of having more predictable semantics. * No support for various kinds of coroutines. setjmp/longjmp is the limit. You can't write zero-cost exception handling in C code, for example. Even computed-goto (a source-level equivalent of jump to a location held in a register) has no C representation, though it is present in some compiler extensions.
- dirtydroog 7y ago> * Missing operations such as popcount, cttz, simultaneous div/rem, or rotates. gcc/clang offers builtins for most of these. And if you give the compiler the right march parameter it'll quite likely turn your hand-rolled code for these operations into the x64 instruction you're targeting. Try it on Compiler Explorer.
- andrepd 7y agoThere's no "bitcast" operator that changes the type of a value without affecting the value. The most common workaround involves going through memory and praying the compiler will optimize that away (while violating strict aliasing semantics to boot). Access through a union allow the same region of memory to be interpreted as different types. No support for multiple return values (in registers). There's structs, but that means returning via memory because, well, see point 1. No mainstream compiler will ever not optimise that.
- btilly 7y agoA good way to think of it is that C is how computers worked 40 years ago. A lot has changed since then, but computers put up a lot of effort to pretend that they still work similarly, and most other programming languages have put up a lot of effort to figure out how to make things work for a "C computer".
- JdeBP 7y ago40 years ago was the home computer revolution. A lot of computers did not work like that. They had things like segmentation, zero pages, workspace register files, shadow registers, BCD arithmetic, and software interrupts. A few years later they had things like heterogeneous multiple processors, PAD, and trap/interrupt gates. The big iron of the time (and a few years later) had some things that did not work like C, too, such as single-level storage addressing, tagged architectures, and capability-based addressing. Thinking that the C language is a representative model for computer history, or indeed for computer architecture, is a bad way of thinking of this. During the 1980s and 1990s there was a lot of shoehorning all of that architectural stuff into C compilers, with extra keywords and the like. (e.g. __interrupt, _Far, _Huge, __based, _Decimal, _Packed, digitsof, precisionof, and so forth)
- btilly 7y agoWell, the original C was pretty much exactly how a PDP-11 worked. And the PDP-11 was a source of design inspiration for the original Intel x86 and Motorola 68000 chips. So there were computer chips sold in the 1970s that worked a lot like C thinks. You are right that there were also ones that didn't. Going forward from close to 1980 you added more and more features to all architectures that diverge.
- asveikau 7y agoI think the biggest point where C is more "how the computer works" vs. a lot of languages is when you write an allocator. I've noticed in, say, an interview context, that people without a lot of C experience have a lot of trouble reasoning about how an allocator might work, or where memory comes from, or even that some constructs in their preferred language result in memory allocation. With C you can't hide these details. Yes there are abstractions beneath you, both in software (your OS has set up the MMU) and hardware (cache, out of order execution) and also in the C standard itself (assumptions about pointer types, the precise meaning of the stack). This doesn't take away from the point that reasoning about allocations is more of a thing.
- xllao 7y agoWhat is the output of Klabnik? Has he written anything substantial or does he just evangelize?
- myrrlyn 7y agohttps://eleroth.files.wordpress.com/2012/01/hadvar.png https://eleroth.files.wordpress.com/2012/01/hadvar.png
- GnarfGnarf 7y agoUB = Undefined Behaviour
- xkriva11 7y agoSome time ago, I saw an article that described a very crazy hypothetical architecture that still fits the C standard and uses the undefined behaviors in various insane ways. It was named like "Computer platform from hell" or so. Unfortunately, I was not able to find it again. Does anyone know about something like that? I think that the hegemony of C for low-level programming is harming us significantly because it puts the other models to obscurity. Try to write in C for something like F21 chip or J–Machine...
- zlynx 7y agoThe Death Station 9000, designed by the Top Men from highly rated government contractors, built to meet and exceed all mandated specification documents. Undefined behavior or use of anything not strictly included in POSIX.1c may result in the launch of nuclear weapons.
- juped 7y agoDo C programmers really think this? I hear it a lot, but only from non-C programmers who hold C in awe. I think they may have heard it from a different cohort of C programmers, though.
- calebm 7y agoIt's always dangerous to mistake the abstraction for the underlying Reality.
- SloopJon 7y agoThere was an ACM article with a similar sentiment recently: "C Is Not a Low-level Language - Your computer is not a fast PDP-11." https://queue.acm.org/detail.cfm?id=3212479 https://queue.acm.org/detail.cfm?id=3212479 HN discussion: https://news.ycombinator.com/item?id=16967675 https://news.ycombinator.com/item?id=16967675
- dirtydroog 7y agoWhile the presence of UB is annoying, but necessary, the real issue is that compiler writers use it as a means of performing optimisations instead of warnings. So you end up with a really efficient, but broken, program.
- nwmcsween 7y agoA test for this is to code some relatively but not too simple of a program in both C and Rust using idiomatic code (don't knowingly pick some corner case for either language), compile with -O0 -g0 and be able to _understand_ the resulting output with regards to the program written. I'm not championing the use of either Rust or C and in my opinion languages should be for people not for computers.
- killmov3s 7y agoUB is bullshit so this is all wrong.
- bjourne 7y agoI know this article has been up a few times already on HN. What I think Steve is missing is that all modern computer hardware is designed around how C works! 40 years ago you might have had hardware in which there was a real mismatch between how it worked and C worked. Not so much these days. How C works and how x86-64 assembly works is very similar. Of course, that is not the whole story and you could argue that how x86-64 assembly works is not how the "computer" works because it is a high-level abstraction of the CPU... But then what does it mean to talk about how the computer works?
- zelly 7y agoReposting this classic, "C Is Not a Low Level Language" https://queue.acm.org/detail.cfm?id=3212479 https://queue.acm.org/detail.cfm?id=3212479
- ken 7y agoShould I learn Verilog to understand “how the computer works”?
- geofft 7y agoMIT 6.004 has students construct a minimal CPU (basically a simplified Alpha processor) out of logic gates, precisely to teach them "how the computer works".
- krupan 7y agoIn short, no. Verilog is very nearly a general purpose programming language, with some syntactic sugar for doing userspace/green/lightweight threads (that it confusingly calls processes). It is used to model digital hardware, but the language itself doesn't really give you any insight into how to construct those models. Creating the model is still up to you.
- myrrlyn 7y agoNo; you should learn Verilog to build a computer. It's a common aspect of Computer Engineering curricula, very educational, and ultimately … not all that useful for most software work, even when doing direct hardware interface.
- rs23296008n1 7y agoWhich language, other than assembly, most accurately represents how modern computers work? What high language could I use that gives me most performance because it accurately matches the underlying platform?
- strategarius 7y agoIs someone thinking so? Really? THIS is how computer works: https://software.intel.com/en-us/articles/intel-sdm https://software.intel.com/en-us/articles/intel-sdm I remember we started our University course of low-level programming from writing in machine codes. No jokes, took binary representation of assembly instructions from that manual and wrote in HEX editor. Then we disassembled simple C applications, understanding unfolding our high-level instructions into x86 assembly. Passing parameters through registres, through stack, two models of stack restoration (yeah, cdecl and stdcall, that moment I realized what does it mean), and other stuff you won't be ever bothered to think about writing in C/C++. And only after that started writing in actual Assembly. THIS is knowledge how computer works. If you know only C, you know nothing.
- Diesel555 7y agoAssembly is how the computer works. Wait no - Binary is how the computer works. Wait no, NAND gates and ALUs are how the computer works. Every level of abstraction is just that. A layer of abstraction. You can pick any layer, then go down and say "learn that".
- proninyaroslav 7y agoDoes it mean that Rust is more situable for the study of low-level programming?