Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Many of the friends I made in my CS classes were terrible with pointers. I never really understood why they didn't grasp pointers, but it was a major stumbling block for them in C/C++


    I never really understood why they didn't grasp pointers
The root of the problem is the language designers' loose use of star. "star something" is contained in a phrase that means one thing at declaration, "star something" has a different meaning the rest of the time.

    #include <stdio.h>
    void eg(int i) {
        int *j = &i; // "huh? Put the address of i into *j?"
        *j = *j + 1;
        printf("%d\n", *j);
    }
    int main() {
        eg(4);
    }
With more detail. In the line..

    int *var = something;
.. the system assigns to the pointer. Yet in..

    *var = 6;
.. it assigns to the contents of the pointer.

Common usage creates further room for confusion:

    int *var; // <- this is what people write
    int* var; // <- instead of this
If they'd made the syntax ".int var", and then used * solely for dereferencing, people wouldn't have these problems learning pointers. Consider

    #include <stdio.h>
    void eg(int i) {
        .int j = &i;
        *j = *j + 1;
        printf("%d\n", *j);
    }
    int main() {
        eg(4);
    }
Further confusion comes from (1) special arrangements around string declaration and (2) printf use of %s to expect a string pointer when %d and %f expects (non-pointer) simple int and simple float.

    char* something = "huh? so now this does goe into *something?";


That's because of the (visually) 'wrong' use of * (wrong in the sense that it's unintuitive). The key is that * is part of the type of the declaration, not of the variable; an int* is not an int. So

  int *j = &i;
is more correctly expressed and easier to understand when written like

   int* j = &i;
The only reason to put the * in front of the variable name is when declaring several pointers in one line. So the solution is to only use it that context, or not doing it at all.


This bothers me so much about C/C++ syntax. int* a, b; should clearly declare two int pointers, not one int pointer and one int.

Stroustrup wrote something somewhere where he explained that int* a; is more appropriate for use in C++ because C++ is supposed to be more focused on types, and int * a; is more appropriate for C because of something about C's philosophy, but I can't remember what. I wish they would have changed the syntax for C++, but I guess he couldn't have while still keeping C++ a superset of C.

edit: found it: http://www2.research.att.com/~bs/bs_faq2.html#whitespace

"A ``typical C programmer'' writes ``int p;'' and explains it ``p is what is the int'' emphasizing syntax, and may point to the C (and C++) declaration grammar to argue for the correctness of the style. Indeed, the * binds to the name p in the grammar.

A ``typical C++ programmer'' writes ``int* p;'' and explains it ``p is a pointer to an int'' emphasizing type. Indeed the type of p is int*. I clearly prefer that emphasis and see it as important for using the more advanced parts of C++ well."


To avoid this sort of thing, I use:

    #include <stdio.h>
    void eg(int i) {
        int *j; // "j is a pointer and (hence) *j is an int"
        j = &i; // "Put the address of i into *j? Yup"
        *j = *j + 1;
        printf("%d\n", *j);
    }
    int main() {
        eg(4);
    }

Perhaps this is because I am just used to it, but I really see very little room for confusion here. The common usage avoids confusion, if you do not insist on assignment at the time of declaration.

To address your second confusion, just keep in mind that strings are char arrays and an array's name is actually a pointer. Again, I find this very straightforward.


    I really see very little room for confusion here.
I don't understand how you reach that conclusion. You might understand it, I don't see how you can say there is very little room for confusion.

Yes, if you know about declaration follows use, it makes sense.

Yes, if you "keep in mind that strings are char arrays and an array's name is actually a pointer" then it makes sense.

You can get by by knowing to avoid some constructs.

If you know how the c compiler works, pointers make sense.

If you know C then you know C.

But when you're new to the language, you don't know these things and that's what this part of the thread is discussing.

Another responder wrote:

    The key is that * is part of the type of the
    declaration, not of the variable; an int* is
    not an int.
The grammar is structured as though it's not. Consider this:

    int* c, d;
Since star is part of the type, if the language was designed well then both of them would be int pointers. But in that case, only c is. d is an int. Awful.


>> I really see very little room for confusion here.

> I don't understand how you reach that conclusion. You might understand it, I don't see how you can say there is very little room for confusion.

Please do not put words in my mouth. I wrote "I see very little room for confusion" not "There is very little room for confusion". I tried to make it clear that I was talking about my personal experience; and I was talking about my personal experience since I was hoping it would help, not to defend the syntax of C.

Sometimes a particular point of view allows you to understand something; in some cases it makes the previously mystifying point "trivial" or "obvious". I am sorry that the POV that helped me so much does not help you at all.


I see, and thanks for clarifying.

The point of my earlier post was to describe strong reasons for people to have trouble with pointers.


> if the language was designed well

Do you mean to reinforce that the language is not beginner-friendly, or are you really asserting that makes the language poorly-designed? If it's the latter, you should really at least explore some other factors before making the conclusion. It seems to me that it's a relatively minor distinction once you know it, so from a design perspective that may simply be a tradeoff for some other advantage.


    Do you mean to reinforce that the language is not
    beginner-friendly, or are you really asserting that
    makes the language poorly-designed? 
I was seeking to account to ramidarigaz why his CS classmates didn't understand pointers.

I think poor grammar is poor design - i.e. part of the type affects both variables (int), the other part doesn't (star).

The other issue is use of star to in one place to mean create reference, in others to mean dereference. That was the focus of my first post.

    from a design perspective that may simply be a
    tradeoff for some other advantage.
I've yet to see evidence of any. What sort of things were you thinking about?


If you remember that the experiment here was to make declaration follow use, it makes sense. I consider it a failed experiment, but it does make sense.


I would hazard to guess its due to two things: 1) a lack of understanding about how the machine works, and in particular the way the memory is organized; and 2) lack of explanation of why anyone would need to use pointers. Introducing pointers in the context of a linked list, or explaining call-by-reference would probably help make things more concrete.


I have friends who had to take an intro to C++ as their first (and only) programming class.

I heard them talking about passing arguments to functions as "call by reference" many times, and it was obvious they had no idea what they were talking about, just regurgitating what the instructor said.


K&R chapter 5.5, Character Pointers and Functions, explains pointers and shows how they are used in C. It's probably the clearest explanation of pointers ever written, and it doesn't require any understanding of hardware or assembly language (though that would help).

I remember reading those three pages over and over and experimenting with the code until I got it. I probably spent several days studying the pointer chapter back when I was a teenager. The light bulb eventually went on and C pointers made sense -- until learning C my programming experience was mainly with time-shared BASIC. The stepwise refinement of an indexed array version of strcpy() to a pointer-based version is a masterpiece of programming writing -- I still refer programmers I am mentoring to that chapter.

Finishing the strcpy() example with the one-liner

  while (*s++ = *t++) ;
the authors write "Although this may seem cryptic at first sight, the notational convenience is considerable, and the idiom should be mastered, because you will see it frequently in C programs." I've found that programmers either get that line of code or they don't, and those who don't haven't mastered their craft.


Getting it or not is one thing, but I'd advocate keelhauling anyone who wrote that sort of thing in production.

The "notational convenience" is more obnoxious than anything. But, then, I'm not particularly a fan of terseness for the sake of being terse.


I'm not a fan of wordiness for the sake of being wordy. If you think the code is terse just to show off you are missing the point. There's a difference between writing obscure code and writing concise idiomatic code -- see "The Elements of Programming Style" by Kernighan and Plauger. I'd rather Kernighan, Ritchie, Thompson, Pike, et al. write my production code than someone who thinks C pointer idioms are a punishable offense.

"That sort of thing" has been in production in the C libraries, the UNIX kernel, and all of the brilliant utilities that make up UNIX for over 30 years. It's also very much in production code at Google.

You might want to read Paul Graham's thoughts on succinct code at http://www.paulgraham.com/power.html and Rob Pike's "Notes On Programming in C" at http://doc.cat-v.org/bell_labs/pikestyle.


I've read both of those links in the past, thanks. And while, yes, "idiomatic" (read: terse and annoying) code is in use in all those areas, I don't have to see it.

Code should be pleasant to read wherever possible. That simply is not, to my mind, pleasant to read. It's one step away from Perl line noise (which I avoid, too). You may disagree with this, and that's fine--different strokes for different folks. I have no interest in seeing it in code I have to maintain; you might, and that's OK by me.

(To be fair, however, I have little interest in working with or, god forbid, maintaining C or C++ code under any circumstances. They press the buttons of a group of developers to which I don't belong.)


I imagine terseness was a lot more valuable when everyone was programming on an 80x25 (or smaller) terminal or even punch cards. I've seen a few examples of code like this from early libc implementations of functions like strcpy, malloc, etc. Take a look at the source code of BSD libc -- some of that stuff is historic.

I myself never got much into the terseness game, since apart from a brief stint using gwbasic and later QuickBasic at 80x25, I learned programming using DJGPP in DOS with the RHIDE IDE. The IDE could trick the VGA into displaying something like 132x60, leaving plenty of room for descriptive code.


The Go language tutorial and examples look right at home alongside K&R. Likewise jQuery and other Javascript libraries, where terseness is valued due to bandwidth rather than screen size.

The idiomatic C style is so natural to me now I don't see it as a defect to fix or a game I'm playing. It's how I learned to program in C because I learned from K&R, and if they aren't the authorities I don't know who is. When I see wordy and bloated Java-style code it reminds me of the years I spent writing COBOL. Ultimately, though, it's not efficiency or a desire to show off or confuse other programmers that influences my style. To me code that does what it needs to with no extra fluff is beautiful.

When I see

  while (*s++ = *t++) ;
I know what it does -- I don't need any comments or "descriptive" variable name or an explicit test for a null byte to make it clearer. If a programmer comes across a line of code that he or she doesn't understand the fault may be with the author, but it may be with the reader. In my experience there are a lot of unskilled programmers who quickly decide that any code they look at is badly written and should be thrown out. I don't think I should dumb down my code just so programmers less fluent with C can understand it. I have to consult a dictionary sometimes when I read Cormac McCarthy or Nabokov but I don't think they should write with easier words for my sake.


"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." --Brian Kernighan Not to mention people aren't as smart as you debugging/understanding it. Also that code relies on the order of operations which I wouldn't recommend outside of math because it can be confusing. And it doesn't check that s isn't null.

Java is considered verbose for a number of reasons. It has a number of variable modifiers, it uses long names(which are generally good but can be stupid, especially in some cases of identifying multiple abstraction levels), and because it lacks type inference for generics and collection literals. c frequently makes the opposite mistakes with tiny cryptic or non whole word names. C lacks generic programming, it does do a decent job with initializers but unfortunately those can only be used at initialization.


The point of the example is to explain pointers by starting with a more familiar concept: indexed arrays. It would help if you were referring to the book; the authors note more than once that "the programs are intended to be illustrative, not bullet-proof."

Understanding the precedence and order of evaluation of operators is fundamental to mastery of any programming language (chapter 2.12 in K&R). All C code must "rely on" the order of operations, and if an indirect assignment through a pointer with post-increment is confusing... well that's the point I was making in the first place.


Good quote, but there is nothing particularly clever in the line above. It is in the same league as if (something) or something ||= something_else.


This type of code used to run faster when compilers did less. It makes no difference now. I think that is why it has stuck around. I prefer to write C that uses array references where it makes things clearer.


Don't think so. Kernighan et al. are the first to say code should be clear first and made fast only if it matters. This is clear code. It may (or may not) be faster than an array-based version but that's not the point of the exercise in K&R -- the point is to teach how pointers work.


You'd be surprised what the compiler still doesn't do. For example, when writing a toy high-performance memory allocator for a university class, I was able to gain a significant[1] performance boost by replacing __attribute__((packed)) structs with pointer arithmetic #defines for the allocation block descriptors, with an identical memory layout.

[1] I don't remember the exact gain, but it was at least 10%.


For me, the indirection of pointers was one of the fundamental CS concepts that required real effort to understand.

Before that point, I had never clearly separated the concept of a variable and its value. It took a huge conceptual leap to think about a variable that didn't hold a value, but rather, the location of a value. It took some serious mental gymnastics to deal with pointers n-levels deep.

Mind you, this was actually Perl references, not pointers, so I didn't even have to try to comprehend doing math on them.

After a while, of course, it became second nature.

My favorite aspect of CS is that every so often, I run into a wall of conceptual understanding that requires completely changing how I think in order to move forward. Have you never had moments like this, or were they just different topics?


Actually learning about the stack was one of my big 'aha!' moments. I sorta' knew it existed, but I didn't really comprehend it.


Mainly because variable declarations are "backwards" in C. People try to read code left to right, but C declarations should be read right to left. Pile one things like the dual use of the static keyword, typedefs, and having multiple consts in a declaration figuring out the type of a variable can be a real chore. Dan Saks has a great article that hits on just the issues with const. http://dansaks.com/articles/1998-06%20Placing%20const%20in%2...


Or the classic "clockwise spiral rule" http://c-faq.com/decl/spiral.anderson.html :)


I can't speak for your friends, but while I had zero problems with pointers conceptually, I still had trouble using them in C. The problem wasn't the simple case of declaring a pointer and taking its reference, the difficulty came when the programs got complex and required agreement between function declarations, actual parameters in calls, and use within the functions.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: