4 ms·
As a teaching assistant for a class (http://www.cs.cmu.edu/~410/ http://www.cs.cmu.edu/~410/) where students write a whole lot of code in C, please introduce th
by rpearl 15y ago
As a teaching assistant for a class (http://www.cs.cmu.edu/~410/ http://www.cs.cmu.edu/~410/) where students write a whole lot of code in C, please introduce the address-of (&) operator and explain how to obtain pointers without using malloc(). Do this before the concept of the heap is ever introduced at all.
Be careful when explaining the compiler and how a program actually runs. I've found that a lot of student problems come from "the compiler is magic" when it really isn't (maybe related to my other surprised comment below, about how people "don't get C"--they attribute too much magic to the compiler.) Maybe even emphasize that every piece of C code can be translated in a fairly easy fashion to a pretty small amount of assembly.
For the preprocessor, emphasize that it is a solely textual replacement, with no symbolic evaluation. Explain why:
#define FOO BAR + BAZ
or
#define MAX(x,y) (((x) < (y)) ? (y) : (x))
will go horribly wrong (the first in 5*FOO, the second in MAX(x++, y++)).
- sausagefeet 15y agoI find it is much more helpful, when teaching C, to avoid the word 'address', and call (&) the pointer-to operator. Thinking of pointers as numbers (which the address-analogy does) tends to be harmful for newer C programmers because they want to treat them like numbers.
- palish 15y agoThey are numbers (either 32-bit or 64-bit). Nothing more, nothing less. I don't understand why you wouldn't want to think of them that way. For example... const char* current = "ohai thar"; const char* end = current + strlen( current ); assert( end >= current ); size_t bytecount = (end - current); (size_t is an unsigned type, so if 'end' is less than 'current', it will overflow. If you want to allow for that, use ptrdiff_t.)
- sausagefeet 15y agoNo, they aren't numbers. The standard is quite clear on this. Consider old DOS architecture where you had a section and offset. Your code is also not well-defined C. C only lets you perform subtraction between two pointers in the same block, this code is at best implementation defined and worst undefined (I can't remember).
- __rkaup__ 15y agoYou'd still need to explain pointer arithmetic somehow.
- sausagefeet 15y agoThat is easy since pointer arithmetic is only valid inside a contiguous block. You don't need to talk about it in terms of a pointer being a number at all.
- rat 15y agocan you get around the second without typeof(a gnu extension)?