loops - C difference between (++variable) and (variable++) -


i have c code here:

char *cat_copy(char *dest, char *src) {     char *start = dest;      while (*++dest);    //increment unless can't anymore.      while (*src++)     {         *dest = *(src - 1);         dest++;     }     return start; } 

i had use while (*++dest) work, instead of while (*dest++).

i read : "--" operator in while ( ) loop , in mind made sense use while (*dest++).

why doesn't work *dest++? , difference between *dest++ , *++dest.

while (*++dest); 

this increments dest , checks if points terminating null byte of string. @ end of string, leave dest pointing terminating null byte

while (*dest++); 

this increments dest , checks if did point terminating null, before incrementing happened. @ end of string, leave dest pointing character after terminating null.

since in following copying part want overwrite original terminating null of dest, first version works better.

the first version still has bug though. always increments dest @ least once, not correct thing if dest starts out empty string. separating *dest check dest++ increment makes loop clearer , handles case correctly:

while (*dest)    dest++; 

Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -