karthikbalaguru said:
#include<stdio.h>
int main(void)
{
char *p="Hello",*p1;
p1=p;
while(*p!='\0')
++*p++;
printf("%s %s",p,p1);
return 0;
}
For the above code,
is it correct to get the output as ' Ifmmp' ?
Yes, since the behaviour of this program is undefined. In particular,
it attempts to modify the characters of a string literal. Because the
behaviour is undefined, any possible behaviour is as `correct' as any
other.
Here's a similar program whose behaviour is not undefined.
#include <stdio.h>
int main(void)
{
char buf[] = "Hello";
char *p = buf;
while (*p)
++*p++;
printf("%s %s\n", p, buf);
return (0);
}
This program outputs ` Ifmmp' on my system. This is a likely result on
systems which use ASCII-based character sets; other character sets may
produce other results. (In particular, I forget where the intra-letter-
block gaps are in EBCDIC.)
Why does it do this? Well, let's start with the article subject:
++*p++. This parses as
++(*(p++))
So, first, we grab the value of p and put it aside somewhere. Now, we
increment p. We retrieve the old value we put aside, and then increment
the character value found at that address. The result is as if we'd
written
{ char *q = p; p++; (*q)++; }
(Warning: I've introduced too much sequencing in this description. The
update of p may happen at any stage of the proceedings: it might happen
before or after the update of the character pointed to by the old value
of p, and so on.)
So: the while loop does this:
if the character code pointed to by p is nonzero, then:
increment the code by one
move the pointer p along one
and try again
In ASCII, the character codes for letters form two contiguous block (for
upper- and lower-cases), so you see the letters advancing through the
alphabet. Well, except for `z' and `Z', which didn't turn up.