12 ms·
> I've come to the conclusion that C is best understood if you think about it in terms of the way that an assembly language programmer would think about doing t
by pcwalton 11y ago
> I've come to the conclusion that C is best understood if you think about it in terms of the way that an assembly language programmer would think about doing things.
I don't agree. That leads people to incorrect conclusions like "int addition wraps around on overflow" (mentioned in the article), "null pointer dereferences are guaranteed to crash the program", "casting from a float pointer to an int pointer and dereferencing it is OK to do low-level tricks", and so forth. C is a language that implements its own semantics, not the semantics of some particular machine. Confusing these two ideas has led to lots and lots of bugs, many detailed in John's other blog posts.
It might be useful to teach these intuitions to beginning programmers who already know assembly language before learning C (though are there more than a vanishingly few number of those anymore?) But teaching assembly language as part of, or as some sort of prerequisite for, teaching C strikes me as a waste of time and likely to lead to wrong assumptions that students will eventually have to unlearn.
- robertelder 11y agoI think you do have a point about possibly misleading people in relation to signed overflow, since that is common hardware behaviour, but for the point about null pointer de-reference, I believe thinking in terms of assembly would actually help people realize that referencing memory location 0 (if that is what null was defined to), will not immediately crash your program. It is not special, it's just another memory location. Your point about teaching assembly as being a waste of time also has some merit. Of course people still do program in assembly, but it is only becoming more and more rare to actually need someone to program assembly, which is why it just isn't emphasized as much any more and it makes C seem like an even stranger language for someone who started on Python or Javascript.
- pcwalton 11y ago> I believe thinking in terms of assembly would actually help people realize that referencing memory location 0 (if that is what null was defined to), will not immediately crash your program. It is not special, it's just another memory location. No, it is special. Dereferencing it is undefined behavior. It is not guaranteed to result in a load at address zero.
- robertelder 11y agoThe cited incorrect assumption was "null pointer dereferences are guaranteed to crash the program", which is, as you implied, not true because it won't necessarily crash the program. C places additional restrictions which say that the program can actually do anything (undefined behaviour). The main reason I keep coming back to assembly language with C, is that C cannot do anything that assembly language cannot do. It only places additional restrictions on assembly, which is a bit easier to grasp (bitwise operations, add, subtract etc.). Once you understand the fundamental operations of the processor, you can start to learn the copious corner cases that is the C programming language.
- scott_s 11y ago> C cannot do anything that assembly language cannot do. I know where you're going with this, but I don't agree with this statement. C provides the abstraction of structs and unions, which do not exist in assembly. Arrays are also an abstraction which does not exist in assembly - yes, assembly provides the mechanisms to easily compute addresses for arrays, but that is different than having a named entity for many objects. The direction you're going is that C is a thin abstraction over assembly, which I agree with. But that is different than saying C has a one-to-one mapping, which is what I think your statement implies.
- robertelder 11y agoMy name is Robert Elder and I approve this message.
- RodgerTheGreat 11y agoWith modern compilers and modern CPUs, C isn't a particularly thin abstraction. Many serious misconceptions stem from naive assumptions about how C will be translated into assembly which are invalidated through compiler code transformations- often with results that surprise even expert compiler maintainers. Please do not spread the idea that C has any straightforward or predictable relationship with assembly language.
- jhomedall 11y agoBecause dereferencing a null pointer is undefined behavior, the compiler is free to assume it won't ever happen. This, in turn, can lead to the compiler optimizing or reordering code in a counter-intuitive manner, completely changing the behavior of a program that you thought you understood. The compiler might emit machine code that attempts to read the memory at location 0. It would also be perfectly within its rights to optimize away that branch of code (if it can prove that it always dereferences null). The code might even appear to work now, and completely break in the next version of the compiler.
- animeweedlord 11y agoThe page containing address zero (NULL) is almost always unmapped in environments with virtual memory, specifically to catch NULL pointer dereferences. That's not the source of the problem. The problem is that dereferencing a NULL pointer is "undefined behavior," and modern compiler writers abuse every instance of undefined behavior to implement negligible optimizations that subtly break programs for little gain.
- nkurz 11y agoYou're right that trusting the assembly intuitions leads to danger when confronted with a standard compliant optimizing compiler. But on the other hand, unless one understands how processors actually execute code, I don't think it's possible to write high performance C. And if one isn't writing for high performance, probably one shouldn't be using C. I like the suggestion in a sibling about teaching C in the context of programming a microcontroller. I think this might bridge the gap a bit: encourage the right intuitions, without creating dangerous misconceptions.
- haberman 11y agoI agree with both of you to some extent. Despite the fact that C implements its own semantics, those semantics are downright bizarre and hard to gain intuition about unless you have some mental model of the machine. For example, here are some of the things that confused me when I first learned C: - why isn't there an actual string data type? (just char*) - why do some people use "char" to store numbers? - whats the deal with pointers? - why are pointers and arrays kinda sorta interchangeable? Until I learned how things work at the assembly language level, I could not gain an intuitive understanding for why C works the way it does.
- Chathamization 11y agoYou don't really need to know assembly to understand those, though. Usually classes will go over the basics - how things are stored in memory, the stack and the heap, etc., and that's enough to answer those questions.
- haberman 11y agoIf all you tell me about the machine is its memory layout, you haven't told me nearly enough to explain the oddities of C. For example, I could imagine a machine with identical memory layout to C, but that supported a hugely parallel, variable-size data bus where an operation like "x = y" (string assignment by value) could copy an entire string in a single operation. The reason C doesn't support this is because generally at the assembly language layer you can only operate on memory in register-sized chunks, and every load or store of a register's worth of memory takes time. So assignment of a string by value requires a loop, just like it does in C.
- Chathamization 11y agoI'm not sure I understand your example. Knowing how arrays (or pointers) are handled in C is enough to understand why you can't have string assignment by value. How C treats things is all you really need to know if you want to use the language. This isn't just true for C. In my experience, people tend to have more difficulty with string assignment in Java than C, but you usually don't hear people say that they need to go to a lower level to really understand Java. Understanding the why is interesting - like it is for any language. And like in many languages, the why tends to be complicated and somewhat arbitrary at times. If you're really interested in the why rather than the what, a book on the history of C will probably be more useful than learning assembly.
- nickpsecurity 11y agoVery true. I counter this cross-platform assembly notion whenever I can as they're not the same thing. One reason for its weirdness, also only assembly it's tied to, is that it was specifically designed to utilize a PDP-11 well. It and anything depending on it is mapped to what makes sense on a PDP-11. We don't use PDP-11's today. So, the C model neither makes sense nor matches assembler of today's CPU's. We've certainly developed ways to implement it efficiently. It wasn't designed for that, though.
- ori_b 11y agoWhy is the PDP-11 so different from today's CPUs, and what about it made C implementations for it more efficient? The only thing I can think of is postincrementing registers. Other than that, the instruction set seems to me to be remarkably close to what you could see on a contemporary CPU.
- _chris_ 11y agoI'm gonna go out on a limb and guess "memory model"; both consistency and coherence issues.
- ori_b 11y agoIn that case, I'm not really aware of any language that exposes this to the user, outside of assembly.
- nickpsecurity 11y agoMany languages restrict or eliminate the use of pointers. C doesn't. So, it exposes whatever model it expects underneath to its users.
- nickpsecurity 11y agoA contemporary x86, RISC, mixed (ISA + accelerators), or what other CPU? I think CPU is a broad term. :) Anyway, Wikipedia has a detailed write-up that assembly experts can base a comparison on: https://en.wikipedia.org/wiki/PDP-11_architecture https://en.wikipedia.org/wiki/PDP-11_architecture It wasn't that PDP-11 made C implementations more efficient. It's that C was a BCPL specifically designed to compile easily and run fast on their PDP-11. That's why I can't overemphasize C's actual history vs the lore that people repeat. It's literally an ALGOL language with every feature that couldn't compile on 60's and 70's era hardware chopped off with some extensions added latter. http://pastebin.com/UAQaWuWG http://pastebin.com/UAQaWuWG Worked fine for a PDP-11. Yet, forcing its memory model or tradeoffs into a language used on different hardware can cause unnecessary problems. In contrast, Hansen's Edison language deployed on PDP-11 had only five statements (extreme simplicity haha) but would map efficiently to most architectures. As would Pascal and Modula-2 that inspired it & were safer. http://brinch-hansen.net/papers/1981b.pdf http://brinch-hansen.net/papers/1981b.pdf https://en.wikipedia.org/wiki/Modula-2 https://en.wikipedia.org/wiki/Modula-2
- ArkyBeagle 11y agoOf course it has its own semantics. I've seen the idea of "the 'C' virtual machine". You got a running start on the differences it has from most assemblers ( each of which will have semantic differences from each other ). I think his point that "The idea of stack frames, heaps, registers, pointers are completely foreign to them..." is the critical point.
- andrewflnr 11y agoIt still seems easier to present C as "a bit like assembly except for..." than "a bit like Java except for...".