Reputation:
Is operator ->
allowed to use in C instead of .
? Does its availability depend on compiler we are using? Is ->
operator available in the last C standard or does it come from the C++ standard? How those two differ?
Upvotes: 5
Views: 16116
Reputation: 234795
In C, c->m
is equivalent to (*c).m
. The parentheses are necessary since .
has a higher precedence than *
. Any respectable compiler will generate the same code.
In C++, unless ->
or *
is overloaded, the equivalence is as above.
Upvotes: 14
Reputation: 896
Operator ->
is standard in C. Both .
and ->
allow to access a struct
field. You should use .
on a struct
variable and ->
on a struct pointer
variable.
struct foo {
int x;
int y;
}
struct foo f1;
f1.x = 1;
f1.y = 3;
struct foo *f2 = &f1;
printf("%d\n", f1.x); // 1
printf("%d\n", f2->x); // 1
The *
operator is called dereference operator
and returns the value at the pointer address. So (*f2).x
is equivalent to f2->x
.
Upvotes: 1
Reputation: 171167
In C, a->b
and (*a).b
are 100% equivalent, and the very reason for introduction of ->
into C was precedence—so that you don't have to type the parentheses in (*a)
.
In C++, operator *
and operator ->
can be overridden independently, so you can no longer say that a->b
and (*a).b
are equivalent in all cases. They are, however, 100% equivalent when a
is of a built-in pointer type.
Upvotes: 5
Reputation: 446
In general case, yes - compiler should produce the same code for both. But these operators can be overloaded and thus have different functions.
Upvotes: 0
Reputation: 294407
There are 3 operators here, *
, .
and ->
. This is important, because .
and ->
both have precedence 1, but *
has precedence 2. Therefore *foo.bar
is not the same as foo->bar
and parenthesis are required, like in (*foo).bar
.
All are original C operators and have been around forever.
Upvotes: 5