11 ms·
To become a good C programmer (2011)
- dsfuoi 10y agoThis is the first time I have seen sizeof used like this: sizeof( &array[0] ) This looks equal to: sizeof( array ) at first glance, which would give the size of the entire array in bytes, but of course the &array[0] expression is really: &*( array + 0 ) which simplifies to: array + 0 which is a pointer. And using sizeof on it gives the size of a pointer to int. Edit: (&* array) will also give a pointer. --- This is just a really convoluted way to write 2: &array[2] - &array[0] &*(array+2) - &*(array+0) (array+2) - (array+0) 2 - 0 Again I have never seen this written in such fashion.
- userbinator 10y agoThe array->pointer "decay" (as the standard calls it) has 3 exceptions, of which two are when an array is the operand of "sizeof", and when it is the operand of "&". (The third involves a string initialiser, which is not relevant here.) So your reasoning is not quite correct, it should really be that you think of sizeof( &array[0] ) as being sizeof( &(something) ) where "something" could be of any type T, and so the '&' operator yields "pointer-to-T", to which sizeof will yield the size of a pointer.
- dsfuoi 10y agoFabien is hinting at the confusion: sizeof(&array[0]) != sizeof(array) &array[0] and array decay to the same thing, the pointer to the first element if they are used in an expression. But sizeof gives a different result, because array+0 'decays' to a pointer, and array doesn't.
- bluetomcat 10y ago> and when it is the operand of "&" Another slightly confusing aspect is that `&array` gives you a "pointer to array" (which has the same value as `&array[0]`, but is of a different type). Most importantly, it behaves differently in pointer arithmetic (the implied offset is the size of the array, rather than the size of its elements).
- robertelder 10y agoHere are the relevant parts of the C standard: C89 3.3.3.4 "The sizeof operator... When applied to an operand that has array type, the result is the total number of bytes in the array." C89 3.2.2.1 "Except when it is the operand of the sizeof operator or the unary & operator, or is a character string literal used to initialize an array of character type, or is a wide string literal used to initialize an array with element type compatible with wchar_t, an lvalue that has type ``array of type '' is converted to an expression that has type ``pointer to type '' that points to the initial member of the array object and is not an lvalue." Additionally, here is a thread of Linus Torvalds pointing out even more of the confusing nature of arrays and sizeof in C: https://lkml.org/lkml/2015/9/3/428 https://lkml.org/lkml/2015/9/3/428
- ucs 10y agoAdditionally, here is a thread of Linus Torvalds pointing out even more of the confusing nature of arrays and sizeof in C: I really like the idiom for passing sized arrays suggested at the end of that LKML thread[1]: pass them by reference! void func(int (*arr)[256]) { printf("arr size: %ld\n", sizeof(*arr)); } int main(void) { int array[256]; func(&array); } [1] https://lkml.org/lkml/2015/9/7/147 https://lkml.org/lkml/2015/9/7/147
- Chathamization 10y agoI doubt Torvalds telling everyone that sizeof was a function helped with this confusion.
- scarmig 10y agoK&R is often recommended, and it's certainly fun to read and accessible. But I've also heard it's outdated, and doesn't rally focus much on modern C software design, mostly because the world knew little about it when K&R was written. Thoughts?
- robertelder 10y agoIt is still relevant due to the fact that K&R C is still extremely (but not completely) forward compatible with even the most modern c++ standards. Many software design best practices have changed since then, but if you read a more modern book some of the first principles of the C language will have to be either repeated or omitted by a modern book.
- satysin 10y agoK&R is still a great book but there are also other great books. Programming in C by Kochan and A Modern Approach by King are two fantastic books and much more suited to a true beginner than K&R is IMHO. Also Head First C and 21st Century C (second edition) are great books to read. The exercises in K&R are superb though and I highly recommend taking the time to do them all while you read K&R which I still feel you should, it is a small book so shouldn't take long to read.
- ktRolster 10y agoSince we're throwing out books, "The Absolute Beginner's Guide to C" (by Perry) has helped a number of people who felt completely overwhelmed by programming in general...
- dsfuoi 10y agoI think the style should be avoided; code shouldn't be compact and variable names should be descriptive. Artificial example: for( int i = 0 ; i < c+j ; i += b ) should be: for( int count = 0 ; count < sum+extra ; count += skip ) It may be allowed to use i in place of count here, but this is the only place where single name variables should be permitted and only if i is really just a simple array index iterator.
- vshan 10y agoLots of good book suggestions in the Ask HN thread I had posted earlier: https://news.ycombinator.com/item?id=11560509 https://news.ycombinator.com/item?id=11560509
- simplicio 10y agoI found that, after learning the basics of the language via K&R or a similar book, the best way to get a good understanding of C and its weird corner cases and eccentricities is just to go through the comp.lang.c FAQ page. http://c-faq.com/index.html http://c-faq.com/index.html It's pretty comprehensive, and I found the level was pretty good for a "not total newbie, but still not familiar with the subtilties" level that can be kind of hard to find resources for.
- 0x09 10y agoThis, the standard document itself (it's not very long, and drafts are freely available), and the C tag on stackoverflow (often contains comprehensive answers by well informed people) are my recommended resources. http://port70.net/~nsz/c/c11/n1570.html http://port70.net/~nsz/c/c11/n1570.html http://port70.net/~nsz/c/c11/n1570.pdf http://port70.net/~nsz/c/c11/n1570.pdf http://stackoverflow.com/questions/tagged/c http://stackoverflow.com/questions/tagged/c A good way to casually browse SO for interesting information is filtering by questions in the last <time period> and ordering by votes. http://stackoverflow.com/search?tab=votes&q=%5bc%5d%20is%3aquestion%20created%3a2016-04-01..2016-05-01 http://stackoverflow.com/search?tab=votes&q=%5bc%5d%20is%3aq...
- blaisio 10y agoMaking a blogging engine in C would be very informative (though difficult).
- genop 10y ago"And no good book is as good as disassembly output." [x] Strongly agree [ ] Agree [ ] Neutral [ ] Disagree [ ] Strongly disagree For me, C, i.e., GCC, is most useful as a faster way to generate assembly for a particular CPU than typing it out from scratch. I use GCC as a code generator. I'd like to see more free asm code generators, but I am not holding my breath. I do appreciate C as a medium for distributing reasonably efficient software.
- umanwizard 10y agoI don't really understand what this means. How is that different from how anyone else uses a compiler?
- animeweedlord 10y agoAs in thinking in terms of what assembly you want the compiler to produce, and not trusting it to do so. Whereas people that program in higher level languages tend to think mostly in terms of the language semantics.
- omginternets 10y agoI think he means that he works like this: 1. Write some C 2. Dump the corresponding assembly code 3. Modify the code by hand
- genop 10y ago4. Assemble 5. Load into assembly debugger 6. Learn There is "C", the language, which can be relatively simple. Or hopelessly opaque depending on the author. I think of C the language as just a shorthand for assembly. Only because that's how I use it. http://www.lysator.liu.se/c/bwk-tutor.html http://www.lysator.liu.se/c/bwk-tutor.html But then there is "C" in practice: the specifications, the "standard" libraries, preprocessors, Makefiles, autoconf, etc.
- umanwizard 10y ago
- jsnk 10y agoWhat's a good practical but small enough project you can do with C? Typically if you are learning Ruby or Node, people recommend creating a blog. What's something like that for C?
- liveoneggs 10y agowhy not a blog? A pseudo device driver is a fun/easy project (at least for netbsd), writing a simple lib and interfacing it with ruby or node is also a good weekend project.
- clishem 10y agoA recursive descent parser.
- eternalban 10y agoGo and grab yourself the latest edition of the excellent Advanced Programming in Unix by Stevens [1]. C in practical action. (Yes, I'm in the dive in the deep end learning camp.) [1]: http://kohala.com/start/ http://kohala.com/start/
- stevetrewick 10y agoA virtual machine and assembler. This is actually pretty straightforward and lots of fun.
- mastax 10y agoAlong the same lines: an emulator for an old computer or games console.
- methodover 10y agoYou could make a small game with SDL, perhaps?
- Annatar 10y agoOne can make a commercial game title with C and SDL. Case in point: Star Control 2, a commercial title with a cult following, which had subsequently been open sourced, then modified to use SDL. Still works all the way from Windows through mobile phones to Solaris, thanks to portable C and the SDL library, and is an excellent game to boot. Original ran on DOS and the 3DO gaming console.
- optforfon 10y agoThe more I learn C the more I hate it. At first it seems simple and easy but reading "Expert C Programming" is reading a laundry list of what's really messed up with the language. 80% of the problems would be solved by some sane syntactic sugar that compiles down to C
- dsfuoi 10y agoWhy are you learning it?
- ams6110 10y agoI would say generally I feel that way about any language I've learned. Initially they are pretty easy and the examples given include slick solutions to contrived problems. Then you get into wanting to do real work and you learn about all the corner cases and ambiguities and landmines that are hidden farther afield. Can anyone name a language that they've grown to like more the more they learned about it? I would guess maybe only those in the LISP family would make the cut.
- RodericDay 10y agoI'm not a super genius programmer by any means, but I've had a lot of pleasant surprises learning about the depths of Python.
- renox 10y agoI disagree: no static typing --> annoying runtime errors, no 'use strict'..
- jsmith0295 10y agoWhile I like static typing, there's a lot more that goes into making a language good or bad than that. On the whole, python seems pretty good to me. I'd take it over Java 90% of the time.
- 10y ago
- halayli 10y agoYou can be an excellent C programmer but still create horrible abstractions. Programmers underestimate the art that goes into that.
- joshumax 10y agoWhen I first started out with C (and back at that time it was the first programmimg language I started learning) I read a majority of the "standard" books and felt rather confident in my understanding of the basics, but when it came to actually writing C, I never felt like I was writing good, pragmatic code. So I started combing through the sources of popular FOSS software like gtk, musl libc, Linux, OpenRC, gcc, etc, submitting bugfixes for a few of them, and asking for code reviews on mailing lists until I finally thought that I was doing okay. I still felt like my knowledge was lacking though, so I decided to learn the internals of the modern x86 machine by writing a hobby OS resembling MINIX (I think I even got X working at one point). Despite still not being the best programmer, it really helped with my understanding of why things are done in C like they are.
- greenpenguin 10y agoThis sounds like a good way to learn, but I would worry about picking up bad habits. Do you have any recommendations of (C) projects etc. that are particularly well written?
- autarch 10y agoI cannot recommend Understanding and Using C Pointers by Richard Reese highly enough (http://www.amazon.com/Understanding-Using-Pointers-Richard-Reese/dp/1449344186 http://www.amazon.com/Understanding-Using-Pointers-Richard-R...) Learning C syntax is pretty easy. Learning to use the standard library is mostly a matter of reading man pages and other people's code. But I found understanding pointers and memory management completely opaque until I read that book. It definitely brought me from "beginning C hacker flailing about" to "intermediate C hacker flailing about in a more dangerous way".
- javajosh 10y agoVery cool. I would like to see a similar recommendation for TCP/IP, DNS, and perhaps HTTP 1/2, including SSL. (Although I suppose you could start with C and then just get involved with the linux kernel, linux net utils, and nginx. But that's like, hardcore.)
- MichaelMoser123 10y agoi think 'TCP/IP Illustrated' is good if you want to get into networking.
- kyled 10y agoLearn assembly then c will be easy
- icdxpresso 10y agoI'm interested in learning about reverse engineering and malware analysis. Is learning C the proper first step in getting my hands dirty? I used C++ in a few college courses, but I've been primarily a Java developer for the past two years.
- tboneatx 10y agoDefinitely C, and you will also need to know a fair bit of assembly. Also familiar yourself with the PE (portable executable) format and learn how to use IDA disassembler and possibly SoftICE (Not sure if it still works, but it was/is a very powerful kernel debugger)
- agumonkey 10y agoWhat other experiences, non C based, will make you a better C programmer too ? ADA, ML, Forth ? some other academic domain ?
- onetimePete 10y agothe biggest virtue of a c-programmer is temporary forgetfulness. forget for the moment, that all of the old-guard-tech foundations is basically a castle made of glued together jello filled rubber ducky's. forget all the tricks needed to jump through that final hoop in assembly. forget even those hopeful endeavors of the languagewiser that stood up, and then came back because performance is a bitch and there use cases to edgy. forget all those library's that overpRomised, undereallocated and disspointered. forget all the futile attempts to steer this boat, carried on the hands of the likes of you, towards some sail-able waters. blissful unawareness settles in, while every "good c-programmer" near you starts to spit fire as soon as management declares a new megalomaniac project in C worthy the effort and thus starting. forget that strange feeling of elated Shame of being the best to repair the most broken car in town. Then, and only then, you will be a "good" C-Programmer, one that knows all the tricks of trade, while not getting wiser.