In C (and some other C-like languages) we have 2 unary operators for working with pointers: the dereference operator (*
) and the 'address of' operator (&
). They are left unary operators, which introduces an uncertainty in order of operations, for example:
*ptr->field
or
*arr[id]
The order of operations is strictly defined by the standard, but from a human perspective, it is confusing. If the *
operator was a right unary operator, the order would be obvious and wouldn't require extra parentheses:
ptr*->field vs ptr->field*
and
arr*[id] vs arr[id]*
So is there a good reason why are the operators left unary, instead of right. One thing that comes to mind would be the declaration of types. Left operators stay near the type name (char *a
vs char a*
), but there are type declarations, which already break this rule, so why bother (char a[num]
, char (*a)(char)
, etc).
Obviously, there are some problems with this approach too, like the
val*=2
Which would be either an *=
short hand for val = val * 2
or dereference and assign val* = 2
.
However this can be easily solved by requiring a white space between the *
and =
tokens in case of dereferencing. Once again, nothing groundbreaking, since there is a precedent of such a rule (- -a
vs --a
).
So why are they left instead of right operators?
Edit:
I want to point out, that I asked this question, because many of the weirder aspects of C have interesting explanations, for why they are the way they are, like the existence of the ->
operator or the type declarations or the indexing starting from 0. And so on. The reasons may be no longer valid, but they are still interesting in my opinion.