int main()
{
char *p = "ayqm";
char c;
c = ++*p++;
printf("%c",c);
}
I thought it should print 'c' but it prints 'b'. Please explain.
int main()
{
char *p = "ayqm";
char c;
c = ++*p++;
printf("%c",c);
}
I thought it should print 'c' but it prints 'b'. Please explain.
It's due to operator precedence, it makes the postfix ++
operator increase the pointer and not the dereferenced value.
So your expression returns the first 'a'
which is increased by the prefix increase to 'b'
, but due to the above mentioned operator precedence the postfix increase is actually for the pointer.
The expression can be broken down as follows, which can clarify what happens.
c = ++*p++;
steps:
1) (*p) // (*p) == 'a'
2) ++(*p) // (*p) == 'b'
3) c = (*p) // c == 'b'
4) p++ // p -> 'y'
EDIT : edited to clarify modification of (*p) per comments
Here postfix has the highest precedence but it will the effect the value only after the statement. ++ and * have same precedence, and they have right associativity. There for it will work like this:
*p -> evaluates to a
then ++'a' which evaluates to 'b'