Reputation: 35
I am confused about the output of following 2 programs. Could someone explain the precedence and associativity rules?
Program 1:
char arr[] = "geeksforgeeks";
char *p = arr;
*p++;
printf(" %c", *p);
Program 2:
char arr[] = "geeksforgeeks";
char *ptr = arr;
while(*ptr != '\0')
++*ptr++;
printf("%s %s", arr, ptr);
Upvotes: 1
Views: 108
Reputation: 38919
First let's simplify your program into something that's comparable:
char arr[] = "geeksforgeeks";
char* p = arr;
*p++;
printf("%s %c\n", arr, *p);
char* ptr = arr;
++*ptr++;
printf("%s %c\n", arr, *ptr);
Next lets look at the operator precedence and hypothesize what we expect to happen:
So we expect *p++
to have no effect, other than advancing p
to the 2nd position because:
p
p
without the increment in addressAnd we expect ++*ptr++
to increment the current character and advance ptr
to the 2nd position because:
ptr
ptr
without the increment in addresschar
at the address ptr
And by looking at this Live Example you can see that our hypothesis was correct, we even get a warning that:
Value computed is not used [-Wunused-value]
*p++
Our results are:
geeksforgeeks e
heeksforgeeks e
Upvotes: 1