Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C and pointer notation

Tags:

c

pointers

Opening up the Postgres codebase, I see that much of the C code is written by having pointers with the -> notation in such a way that:

(foo)->next = 5;

I know that pointer notation has levels of precedence, such that -> = (*foo). and is not the same as *foo.

However, does it mean anything when the parentheses are outside the variable name and de-referencing the address of next or is it merely a convention that is endemic to a coding style?

like image 611
mduvall Avatar asked Sep 24 '09 02:09

mduvall


2 Answers

Its a coding convention that I've not seen before.

But it doesn't change anything.

(foo)->next = 5;

is exactly equivalent to

foo->next = 5;
like image 189
abelenky Avatar answered Sep 29 '22 23:09

abelenky


It is a coding convention for safety.

In simple code, where foo is just a pointer, the parens are redundant.

(foo)->next = 5;

However, consider if there is or was the chance that foo might be defined by a macro so it is a more complex expression.

In that case, the parens might be required to avoid a compiler error or, worse, to avoid incorrect precedence. Imagine if it translated to an ugly expression like:

( ++get_foo() )->next = 5;

or a common cast:

( (db_record*)foo_ptr )->next = 5;

Something to bear in mind with idiomatic C code is that macros were often used as an abstraction mechanism for things we might do more explicitly in other languages ;-)

like image 32
Andy Dent Avatar answered Sep 29 '22 23:09

Andy Dent