output of the program

can anyone please explain me the output of the program
1
2
3
4
5
6
7
8
9
#include<stdio.h>
main()
{
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
getchar();
}
"whatever" is a const char*
I think you cannot understand expression ++*p++;
To understand it I will rewrite it as a sequence of actions

p++; // returns current value of the pointer and increases it

*p++; // dereferences the pointer so it correcponds to a value of type char

++*p++; increases the value in the object of type char.

For example if *p++ is equal to 'h' (the first letter of the character literal) then ++*p++ will increase 'h' and its value will become 'i'

So the loop while(*p!='\0') ++*p++; tries to change the string literal "hai friends" to something as "ibj gsjfoet"

However you may not change string literals in C/C++. So the behaviour of the program is undefined and can result in throwing an exception.

Moreover if to accept that the program will not throw an exception pointer p will points to '\0' after the loop. So in the next statement printf("%s %s",p,p1); there will be displaying nothing for the first argument.

The correct code shall look the following way. I am assuming that it is written in C


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<stdio.h>

int main( void )
{
   char s[] = "hai friends";
   char *p = s;
   
   printf( "%s\n",  s );

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

   printf( "%s\n",  s );

   getchar();
}



EDIT: I removed some typo from the code.:)
Last edited on
why is the expression been parsed from right to left...why isnt precedence working here.....p should be dereferenced 1st and the postfix operation and then prefix???
The postfix operator has the highest priority among others operators in the expression. All other operators in the expression are parsed from right to left. There are such rules in C/C++.
Last edited on
Topic archived. No new replies allowed.