Lets say I have a struct
struct s
{
int a;
}
and a main function like this
int main()
{
struct s s1 = {.a = 10};
struct s *sptr = &s1;
sptr->a--;
printf("%d\n", sptr->a);
s1.a = 10;
--sptr->a;
printf("%d\n", sptr->a);
return 0;
}
Output :
9
9
As per operator precedence, ->
and --
have same precedence and left->right associativity.
In case of sptr->a--
, I can understand sptr->a
was done first and then --
was applied.
But in case of --sptr->a
, --
should be applied to sptr
first. This may lead to undefined behaviour but it should be the case. Why does this still work same as sptr->a--
?
As per operator precedence, -> and -- have same precedence and left->right associativity.
->
and postfix --
have the same precedence and left-to-right associativity, so sptr->a--
is (sptr->a)--
.
->
and prefix --
don't have the same precedence, --
is lower. Thus --sptr->a
is --(sptr->a)
.