Pointers to structures are used so often that there is a special operator for it: ->. The below expressions are equivalent:
(*x).y
x->y
Would it be fair to think of this operator simply as preprocessor macro defined as such:
#define (x)-> (*(x).)
Why or why not? Or was it coded as a operator from the start - and how would this be different / advantageous?
Just curious.
Yes, Both are two different ways to access structure member
y
.(*x).y
operator is.
DOT that works with value variableElement selection by reference
. that the reason*
used. meansx
is pointer to struct.x->y
operator->
is used calledElement selection through pointer
. This work with pointer to struct. that is the reason*
not used this time.Both works same.
No First it give an error: macro names must be identifiers. This error is because we can't have
->
operator as macro name.a valid macro name can be:
Also, note
->
and.
are differences operators as I state above. also their precedence are different so its bad idea to replace one operator with other.Additionally I would like to share today only i came to know that most C header files. Defined macros like:
for specific strcut element.
Notice
(x)
parenthesis aroundx
is to overwrite precedence of*
over.
. By default.
DOT has higher precedence over*
So that it can be use for pointer and simple variable. Below my example will be helpful I think.EDIT:
Better Option
I am extending my idea to access strcut elements, I defined new macro:
Not its not more for specif elements via macros.
Hope at-least OP love it :)
No.
The
->
operator has some specific semantics that cannot be enforced with a macro (which is a simple text substitution). Namely, the left-hand operand must be a pointer to a struct or union type, and the right-hand operand must be a member of the struct or union type, and the result of the expression must be an lvalue. You cannot enforce those rules with a macro.No, it wouldn't.
Because it's not a macro. It's a distinct operator defined in the language, that appears to be providing syntactic sugar for another functionality.