Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post increment with pointers in while loop in C

Tags:

c

c-strings

I am writing the strcat function

/*appends source string to destination string*/

#include <stdio.h>

int main()
{
    char srcstr[100], deststr[100];
    char *psrcstr, *pdeststr;

    printf("\n Enter source string: ");
    gets(srcstr);
    printf("\n Enter destination string: ");
    gets(deststr);

    pdeststr = deststr;
    psrcstr = srcstr;

    while(*pdeststr++)
        ;
    while(*pdeststr++ = *psrcstr++)
        ;

    printf("%s", deststr);
    return 0;
}

For srcstr = " world" and deststr = "hello" I get hello, when I expect to see hello world, which is what I see if I change the first while so

while(*pdeststr);
    pdeststr++;

why can't I write all in one line in the first while, just like in the second while?

like image 789
Hugo Avatar asked Dec 05 '22 13:12

Hugo


1 Answers

Your one line loop

 while(*pdeststr++);

Is equivalent to

while(*pdeststr)
    pdeststr++;
pdeststr++;

Because the postincrement operator is executed before the condition is tested, but after the value for the test is determined.

So you could cater for this with

 while(*pdeststr++);
 pdeststr--;
like image 63
Dmitri Chubarov Avatar answered Dec 29 '22 19:12

Dmitri Chubarov