skvatss
skvatss

Reputation: 35

what is the output and explain how?

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

Answers (1)

Jonathan Mee
Jonathan Mee

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:

  1. Postfix increment (Happens 1st because it has the highest precedence of the three operators)
  2. Dereference (Happens 2nd because operators of precedence 2 associate Right-to-left)
  3. Prefix increment (Happens last because it is the leftmost operator of the lowest precedence)

So we expect *p++ to have no effect, other than advancing p to the 2nd position because:

  1. Postfix increment p
  2. Dereference the address of p without the increment in address

And we expect ++*ptr++ to increment the current character and advance ptr to the 2nd position because:

  1. Postfix increment ptr
  2. Dereference the address of ptr without the increment in address
  3. Increment the value of the char 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

Related Questions