843 views
0 votes
0 votes
plz explain this code??

main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}

1 Answer

0 votes
0 votes

To, understand how the code is working, we need to first understand the most crucial part of the code i.e.

++*p++;

it will be solved in the following form:-

(++(*(p++)))

because of the following table:-

The operator precedence is as follows-

Operator

Description

Associativity


++ --

Postfix increment/decrement 

left-to-right

++ -- 

 
Prefix increment/decrement 
Dereference
right-to-left

As we can see from the table that post increment has higher priority than pre increment and * operator so it will be solved first and then pre increment and * has the same priority so they will be solved according to the associativity rule i.e. right to left.

therefore the expression will become like this:-

(++(*(p++)))

Now, coming to question:-

Diagrammatically it will look like this:-

Loop:-

while(*p!='\0') ++*p++;

which means p is moving, and if we apply what ever we have learnt from previous discussion it will look like this:

while(*p!='\0') (++(*(p++)));

Now the after checking the condition in the loop and become true it will enter into while loop and execute

1. increment the value of p : p + sizeof(data type of p);

2. go to that place where incrmented value point.

3. and then increment that value also // because of pre increment.

So, iterations are like this:-

p = 200 , value at p = h != '\0'; true enter and incr p to 201 and then incr value at 201 i.e "a to b"

p = 201 , value at p = b != '\0'; true enter and incr p to 202 and then incr value at 201 i.e "i to j"

p = 202 , value at p = j != '\0'; true enter and incr p to 203 and then incr value at 201 i.e "<space> to !"

and so on till null, when p reaches to null then condition become false and out of the loop. at this instance the pointers are p = 210 and p1 = 200.

As a result p prints nothing and p1 will print "hbj!gsjfoet".

Related questions

4 votes
4 votes
1 answer
2
ritwik_07 asked Jun 10, 2023
423 views
#include<stdio.h #include<string.h #define MAX(x, y) ((x) (y) ? (x) : (y)) int main() { int i = 10, j = 5, k = 0; k = MAX(i++, ++j); printf("%d %d %d", i, j, k); return ...
0 votes
0 votes
1 answer
3