Code style for accessing structures via pointers

Discussion in 'Mac Programming' started by jiminaus, Jan 2, 2011.

  1. jiminaus macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #1
    I thought I new C pretty well. Until today when I learnt C's && and || operators are short-circuiting. I've been needlessly writing nested if's for years.

    Now I see in lloyddean's code he put up the in "Getting duplicate numbers" thread that he consistently uses the following code:

    Code:
    (*p)._end
    
    where "p" is pointer to a structure with a member called "_end".

    I would have expected the following instead:

    Code:
    p->_end
    
    I thought these two were completely equivalent. But now I'm not sure. Are the exactly the same?
     
  2. TreborM macrumors member

    Joined:
    Jun 26, 2010
    #2
    The -> is simply syntactic sugar for a pointer dereference

    The . operator is for direct member access.
    The arrow dereferences a pointer so you can access the object/memory it is pointing to.
    The . operator has greater precedence than the * operator, so . is evaluated first. That's why you need parenthesis in:
    Code:
    (*p)._end
    
    Note that the -> operator cannot be used for certain things, for instance, accessing operator[].

    Trebor.
     
  3. lloyddean macrumors 6502a

    Joined:
    May 10, 2009
    Location:
    Des Moines, WA
    #3
    The piece was meant to be somewhat instructional and required that particular usage in a couple of places so I thought it best to be consistent so as not to confuse overall.
     

Share This Page