Search code examples
cpointersstrchr

why *s and *s++ have the same value in the following situation?


char *s;
char buf [] = "This is a test";

s = strchr (buf, 't');

if (s != NULL)
    printf ("found a 't' at %s\n", s);
printf("%c\n",*s);
printf("%c\n",*s++);
printf("%c\n",*s++);
printf("%c\n",*s++);
printf("%c\n",*s++);

This code outputs:

found a 't' at test
t
t
e
s
t
Program ended with exit code: 0

In my view, *s should be t and *s++ should be e. But why they have same value in this code ?


Solution

  • In the expression *s++, ++ is the post-increment operator. That means following happens, in-order:

    • The value of s is gotten
    • Then s is incremented
    • Then the old value of s is de-referenced

    So,

    printf("%c\n",*s);     // Prints the character at s
    printf("%c\n",*s++);   // Prints the character at s
                           // ***and then*** increments it
    

    They will both print the same character.


    If you want your example code to behave like you think it should, simply remove the first printf without the post-increment on s:

                            // s points to the 't' 
    
    printf("%c\n",*s++);    // Prints 't'. Afterward, s points to the 'e'
    printf("%c\n",*s++);    // Prints 'e'. Afterward, s points to the 's'
    printf("%c\n",*s++);    // Prints 's'. Afterward, s points to the 't'
    printf("%c\n",*s++);    // Prints 't'. Afterward, s points to the NUL terminator