10 ms·
Teaching C (2016)
- DrNosferatu 4y agoWhat about the Deitel books?
- macintux 4y agoNot only an insightful post, but also a fair number of interesting comments. A couple of resources I found in the comments: * A short list of safety rules for C: https://en.wikipedia.org/wiki/The_Power_of_10:_Rules_for_Developing_Safety-Critical_Code https://en.wikipedia.org/wiki/The_Power_of_10:_Rules_for_Dev... * A much longer document, 42 rules for coding in C and C++: https://pvs-studio.com/en/blog/posts/cpp/0391/ https://pvs-studio.com/en/blog/posts/cpp/0391/ Update: also, a 210-comment thread from 2018: https://news.ycombinator.com/item?id=18334476 https://news.ycombinator.com/item?id=18334476
- jvanderbot 4y agoWe're 4 years away from the time when TFA predicts no new projects will begin with C. I wonder how the claim holds up? Certainly not well in the embedded space, and Rust mainline kernel development seems still a few years away at least. I'd argue there's some transition in space fsw to c++, but that's not really significantly different than C+classes, since most c++ features and std:: are not allowed. When does automotive, iot, and other spaces anticipate tansitioning?
- macintux 4y agoTo be fair to the author, the claim is that it's at least a decade away.
- arinlen 4y ago> We're 4 years away from the time when TFA predicts no new projects will begin with C. I'm not sure if this is representative, but most of my recent FLOSS projects have all been C89 libraries. The rationale is that it's trivial to add C bindings in any language, it's extremely fast to build, and it runs everywhere.
- andrewmcwatters 4y agoThis is the exact reason I build and ship using C89.
- chrchang523 4y agoIn your case, how much compatibility is lost from using C99 over C89? (I'm comfortable with C99 and still write some low-level multiplatform code in it, but losing the ability to declare variables where they're first used is a bridge too far for me...)
- SubjectToChange 4y agoJust for reference, projects like SQLite use C99. IMO, targeting C89 is only warranted when you know for a fact it's needed. After all, not only is C99 a good improvement but toolchains stuck on C89 are not the type of toolchain I'd want to support.
- arinlen 4y ago> In your case, how much compatibility is lost from using C99 over C89? Until somewhat recently C89 was the latest version of C that was supported by the MSVC compiler. Support for C99 was always terribly broken and Microsoft chose to claim it did supported C99 but without supporting mandatory features, which meant they did not in fact supported C99. This sad state of affairs only changed significantly in 2020, with a lowkey announcement. https://devblogs.microsoft.com/cppblog/c11-and-c17-standard-support-arriving-in-msvc/ https://devblogs.microsoft.com/cppblog/c11-and-c17-standard-...
- pjmlp 4y agoThey claimed support for C99 to the extent required for ISO C++ compliance, plus some features critical for a couple of their developers. Likewise, even with the updated C11 and C17 support, it isn't 100% there, only good enough, because C++ is what matters for Windows developers when not using .NET.
- elteto 4y agoFWIW I’ve seen space FSW instances where both std:: was allowed and forbidden. One instance was soft real-time FSW running on a customized Linux. Most (sane) C++ was allowed, exceptions were not disabled, just disallowed, std:: was allowed during initialization, but not past that, memory allocation was only allowed during initialization as well, although a stray allocation at runtime was only fatal in testing, not during flight. It was logged in both cases and considered a critical issue. PR reviews had strict checklist rules regarding allowed syntax/features. It was very productive using all of the necessary C++ features, within reason, to write code.
- pjmlp 4y agoAutomotive standards like AUTOSAR have been using C++ for quite some time and now are looking into Rust as well. https://www.autosar.org/news-events/details/autosar-investigates-how-the-programming-language-rust-could-be-applied-in-adaptive-platform-context/ https://www.autosar.org/news-events/details/autosar-investig... Note that MISRA is also adopting AUTOSAR on their standards.
- svnpenn 4y ago> We're 4 years away from the time when TFA predicts no new projects will begin with C. True, but AFT gives us at least 8 years.
- commandersaki 4y agoAlso worth teaching: -fno-strict-aliasing.
- lifthrasiir 4y agoThere is a comment mentioning this. I do have a somewhat different view that you should minimize the number of "reinterpreting" casts (stealing the C++ terminology) in general, which is often ill-advised at the first place. This practice frequently eliminates the need for -fno-strict-aliasing.
- synergy20 4y agofully agree, use strict-aliasing only after profiling and on your bottleneck code, if necessary, otherwise, just use no-strict-aliasing(linux kernel uses it too)
- astrange 4y ago`-fno-strict-aliasing` is even less formally defined than C itself is, so I don't think it's a good tool, you're just hoping it works for your program and not actually checking. UBSan/ASan cleanliness is a better goal.
- synergy20 4y agosince linux kernel depends on it, I would assume it's solid. I do use UBSan/ASan as well, but I can't enable them for production run, and I can with no-strict-aliasing, which is at least safer than without-it.
- einpoklum 4y agoI disagree. That is, when teaching C, I never gave examples avoiding any aliasing, and if it somehow came up, I advised against it. But I don't think it's a good idea to invest teaching time in compiler options regarding aliasing; it's too specific for an introductory C course.
- bluetomcat 4y agoC should be taught like any other language. One should understand the historical context in which a language was born and why it gained popularity. A lot of "vintage" C code is indeed bad because elementary software engineering principles were not widely understood back then. Pascal code of the same vintage isn't significantly better, either. We've walked a way in collectively understanding the importance of modularity, cohesion and coupling and balancing complexity, and that smart isn't always better in the long run.
- qsort 4y agoI slightly disagree. C still is, and will continue to be for the foreseeable future, the lingua franca, the least common denominator. Acknowledging how C comes with a very... interesting set of tradeoffs that make it uniquely well-suited for certain purposes and at the same time incredibly dangerous is a worthwhile proposition if one is aiming to truly understand C development.
- bluetomcat 4y agoTrue, but a good C course should explain exactly those concepts and what kind of problems (in relation to assembly and other HLLs) was C meant to solve back at the time. I would highlight the following: * Structured programming support, which means nested loops and conditionals without a primary need for "goto" jumps, enabling a sense of "depth" that is missing in the "flat" world of assembly * Expression-oriented syntax, meaning that operators (even those having a side-effect) return a value of a certain type, and can be nested, again enabling recursive program structure versus a flattened one * Global symbol allocation and resolution, which means that a programmer uses names rather than addresses to refer to global variables and functions * Abstraction over function calling conventions, which enables the programmer not to worry about function prologues and epilogues and the order of pushing arguments on the stack or in registers * Automatic storage management, meaning that a function-scope local variable is used by the programmer with its name and the compiler decides whether to put it in a register or at a certain offset in the stack frame * Rudimentary integer-based type system that has the distinction between a scalar and a fixed-size collection of scalars laid-out sequentially (arrays), and special integers called "pointers", supporting a different set of operations (dereferencing to a certain type and adding or subtracting other integers from them, without any safety guarantees whatsoever) Nothing more, nothing less. Not understanding these foundations is the source of major pain.
- whateveracct 4y agoI learned C mostly on pen-and-paper exercises at my university. Lots of drawing the stack and heap.
- unwind 4y agoThat is ... a bit weird, since C does not assume, recommend or require that non-heap variables are implemented using a stack. It's weird to teach a language while also ripping a hole in one of its main abstractions and assuming stuff about how that works, in my opinion.
- turtledragonfly 4y agoGenuinely curious: do you know of any C implementations that do not use a stack for such cases? It seems so prevalent that locally-scoped variables are often referred to as "stack variables" in casual conversation, but I'm curious of cases where it's not true...
- shadowofneptune 4y agoI was curious about this, and I found this passage in the 2007 draft of the C standard: > 6.5.2.2.11: Recursive function calls shall be permitted, both directly and indirectly through any chain of other functions. This either means using stack frames, or heap-allocating activation records and tying them together with references. Second is a much rarer approach.
- dcminter 4y agoDidn't sparc targetted C use register windows? Cursory searching didn't clarify much for me though.
- whateveracct 4y agoIt was semantic, not necessarily a literal mapping to memory. It absolutely was a correct way of modeling and explaining how C programs can be understood to work.
- deleted 4y ago[deleted]
- hnthrowaway0315 4y agoJust curious, is there a C system programming book that gradually feeds the readers with progressive (in difficulty) sys programming projects? I red CSAPP and that is a good one, but the scope of the projects is a bit limited.
- rramadass 4y agoYou may find UNIX Systems Programming: Communication, Concurrency and Threads by Kay Robbins & Steven Robbins useful.
- anta40 4y agoTry Bruce Molay's Understanding UNIX/LINUX Programming: A Guide to Theory and Practice. It teaches us various Linux/Unix concepts like signal, threads, file I/O, socket, etc. On some chapters, we'll be guided to re-implement various built-in tools like who, ls, sh, pwd. Very interesting from developer point of view.
- mannykannot 4y ago"The other way of teaching undefined behavior, by looking at its consequences, is something that we should spend a bit of time on, but it requires a different kind of thinking and we probably won’t expect the majority of students to pick up on all the subtleties — even seasoned professional C programmers are often unaware of these." I feel that last phrase exemplifies why this should be given quite a lot of attention. It is also the sort of thing that will lead a student to a deeper insight into the language and how it differs from the other procedural languages that they are likely to already be familiar with (the same can be said for memory management, BTW.) Such a course might be something of a grind, but if so, it would inculcate the right sort of attitude for programming competently in C! For dessert, take a quick look at some Obfuscated C winners.
- blinkingled 4y agoRMS recently released reference manual for GNU C - I am finding it to be direct and succinct. Edit: I used to teach C to a group of undergrads and one question that came up often was around the special significance of the main function and order of definition of functions. The RMS book addresses this very succinctly - Every C program is started by running the function named main. Therefore, the example program defines a function named main to provide a way to start it. Whatever that function does is what the program does. The main function is the first one called when the program runs, but it doesn’t come first in the example code. The order of the function definitions in the source code makes no difference to the program’s meaning. https://lists.gnu.org/archive/html/info-gnu/2022-09/msg00005.html https://lists.gnu.org/archive/html/info-gnu/2022-09/msg00005... If you understand basic concepts of programming but know nothing about C, you can read this manual sequentially from the beginning to learn the C language.
- tamsaraas 4y agoC is an achievement that must be unlocked by programming in different other high-level languages for years. Without this - C will be pointless lecture.
- suprjami 4y agoAs someone who loves C, I don't want to gatekeep it like this.
- swatson741 4y agoFeels like that's true of most things you learn in college at the level of detail in which their taught.
- projektfu 4y agoHow strange, I was going to respond to a question about this code: https://git.musl-libc.org/cgit/musl/tree/src/string/memchr.c https://git.musl-libc.org/cgit/musl/tree/src/string/memchr.c and the user has completely disappeared along with their comment/question. Anyhow, you can think about the __GNUC__ part as an attempt to fast-forward the loop by testing size_t-length chunks for the character by XOR-ing the chunk with a repeated string of that character. The first loop aligns the pointer for the fast-forward. The final loop is then used to test the unaligned part, which when not using __GNUC__, would be the complete loop. I felt the need to answer because I'd done the work.
- enahs-sf 4y agoAs I think about teaching my son programming, I think I would start with C and assembly because although it’s super low level, it gives you a fundamental understanding of how the machine works. The debugging and problem solving skills these languages impart will also be invaluable.
- SubjectToChange 4y ago>... it gives you a fundamental understanding of how the machine works. ISO/GNU C is unfit for programming classes of devices as ubiquitous as smartphones, or virtually any type of SoC. There is a reason CUDA/OpenCL/ROCm/SYCL exist and why they can't be programmed like usual C if you want performance.
- CJefferson 4y agoHonestly, I don't think C is a good match for "how the machine works". If you look at the assembler an optimising compiler produces from C, it can take hours to learn how to map the C to the assembler. Also, all the business with "undefined behaviour" (which they will hit soon, and often) isn't how computers work either -- assembler has (very little) undefined behaviour, if you write to a random memory location it is written to (unlike in C where maybe it is, maybe it isn't). My recommendation would be to teach them whatever is the quickest way to something they enjoy, wether that be Python, Minecraft, Roblox, Javascript for web dev, or C if they (for some reason) really want to start by doing kernel programming or something like that. You can learn all the "fine details" later, they have a lifetime to do it :)
- CJefferson 4y agoHaving taught C at University, I found the hardest bit being how many "well, but..."s to give. C feels like a very simple language, but there are lots of subtle corners which probably don't need teaching at first. On the other hand, I think it's important to hammer home "undefined behaviour" early. There are too many guides that say writing outside the bounds of an array "writes to memory outside the array", which simply isn't true. It might write, it might not, who knows, undefined behaviour means all bets are off. In general I feel a lot of practical teaching of C is teaching about undefined behaviour, which is something many other languages (Java, Python, Haskell, Rust), either don't have, or where they do beginners won't stumble across it.
- Doxin 4y agoA good tactic may be to teach D instead. It's rather close to C (especially with the -betterC flag which disables among other things the garbage collector) but fixes some of the more egregious flaws. No spiral rule. Proper modules. No preprocessor (but CTFE and mixins instead). It stays close enough to C that undefined behavior exists but far enough away to avoid nasal demons.
- bitwize 4y agoIt's high time we declare C "unsafe at any speed" and cease teaching it to every student. Only those who really need it (legacy C codebase, microcontroller with a toolchain that doesn't yet support Rust) need to learn it.
- lionkor 4y agoHow do you tell apart a student that will later work on a legacy C codebase from one that won't?
- bitwize 4y agoYou don't. Let them learn C when they need to use C. Consider it a specialist language that is only used for certain tasks, like Fortran or COBOL -- not something everybody has to know.
- wudangmonk 4y agoI completely agree. Rust exists already so I do not understand why all the other languages need to continue existing. Only those that use Rust can be considered to be a good person since using Rust is the morally responsible thing to do. The question then becomes, why do we want more evil people in the world?. Does that make any sense? because that's exactly what you get when you don't use Rust.
- zbird 4y agoRust doesn't even have a formal specification at this time. Technically speaking, everything in Rust is undefined behaviour. That's a hard sell for, e.g., people writing safety-critical systems. Another problem recently was that compiling Rust required downloading a binary blob from Mozilla. That's a no-go for many projects.
- pjmlp 4y agoAUTOSAR is looking into it, while Ada Core is collaborating with Ferrous Systems to bring Rust to the kind of clients that usually use Ada. Meanwhile Microsoft has finally acknowledged picking C for Azure Sphere was a bad idea for its overall security story, and is now adding Rust support.
- shadowofneptune 4y agoC Programming: A Modern Approach was my first introduction to programming outside of writing a few python scripts (didn't know I could define my own functions, for example). With just it and MVSC I was able to pick up a lot of the general concepts and practices, Last project I made while studying the book was a clock for decimal time and French Republican dates in ncurses. This was only back in 2020, so it still is relevant.
- bowsamic 4y agoI have nothing to say other than that I love C and I will always love C. That love affair began when I first walked through the tutorial chapter of K&R, and it never died down. I'm not sure what it is, but it is just beautiful to me.
- deleted 4y ago[deleted]
- Sin2x 4y agoSince 2020 there was a new good book on C from Robert Seacord from the C Standards committee: https://nostarch.com/Effective_C https://nostarch.com/Effective_C