Search code examples
cpointersstandardsarrows

Space between arrow operator in C


I was notified the other day that I shouldn't use pointer arrows in a certain way in C. What I did was this:

struct info {
    int x;
    char *data;
}

int main() {
    struct info *information;
    information -> x = 0; /*Notice the spacing here between information and -> x*/
    information -> data = "";
}

What I usually see

struct info *information;
information->x = 0;

I just wanted to ask, is this just a regular coding standard thing?
I just feel -> is a lot cleaner than p->stuff.


Solution

  • It doesn't matter from a syntactic point of view, it's insignificant whitespace.

    I would say that (anectdotally) the style without spaces is much more common. I find it nice since it somehow reflects the "tightness" of the structure containment. Of course, I write almost all other binary operators with spaces, i.e.

    a->b = 1 + 2;
    

    and never

    a -> b = 1+2;
    

    or

    a->b = 1+2;
    

    It's just personal preference, in the end. Of course in many professional environments that's lifted to "project/company style guide dictates that this is how it's done, here".

    Also, when working directly with structures using the . operator, I use that the same way. Always:

    a.b = 1 + 2;
    

    and never:

    a . b = 1+2;
    

    I think the former formatting works for me since, as I tried saying above, the two things on the sides of the operator are part of the same thing, "a.b" is a term, not two. With +, it's two operands are independent so there the spacing makes more sense to me.