Question

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.

Was it helpful?

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.

OTHER TIPS

C is a very free-form language, and whitespace (tab, space, newlines etc.) are disregarded by the parser.

information -> x = 0;

is the same as

information->x=0;

and

information
->
x
=
0
;

This is a matter of taste, and is therefore probably better for https://softwareengineering.stackexchange.com/.

Generally, I think the standard is to have no space. In my C code, I write arithmetic operators as x + y etc, and member-access operators as a->y etc. This is because members and their owners can be though of as "one unit", whereas arithmetic is an operation on multiple, distinct values, whose only relationship is that they happen to be used together in your expression. Members, on the other hand, or fundamentally bound to their owners, and the lack of space signifies that.

Use whichever one you like - it doesn't make much difference. Still, if you want to know what's used more frequently, it's the space-less version.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top