Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are parenthesis needed to get the address of a struct member from a pointer to the struct as in "&(s->var)" vs "&s->var"?

Tags:

c

I have a struct str *s;

Let var be a variable in s. Is &s->var equal to &(s->var)?

like image 232
joker Avatar asked Apr 24 '11 00:04

joker


People also ask

How do I find the address of a member of a struct?

In C, we can get the memory address of any variable or member field (of struct). To do so, we use the address of (&) operator, the %p specifier to print it and a casting of (void*) on the address.

Can we have a pointer pointing to a struct yes or no?

Pointers to Structures Like we have pointers for int, char and other data-types, we also have pointers pointing to structures.

Can a struct point to itself?

Self Referential structures are those structures that have one or more pointers which point to the same type of structure, as their member. In other words, structures pointing to the same type of structures are self-referential in nature.

Can a struct have itself as a member?

Although a structure cannot contain an instance of its own type, it can can contain a pointer to another structure of its own type, or even to itself.


1 Answers

Behavior-wise, yes they are equivalent since the member access -> operator has a higher precedence than the address-of & operator.

Readibility-wise, the second one &(s->var) is much more readable than &s->var and should be preferred over the first form. With the second form, &(s->var), you won't have to second-guess what it's actually doing as you know the expression in the parentheses are always evaluated first. When in doubt, use parentheses.

like image 97
In silico Avatar answered Oct 04 '22 15:10

In silico