0

I am completing my CISCO course on C and I got a doubt in the following function.

Can someone please explain me the logic of the function, especially the use of --destination here?

char *mystrcat(char *destination, char *source) 
{
    char *res;
    for(res = destination; *destination++; ) ;
    for(--destination; (*destination++ = *source++); ) ;
    return res;
}
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • In addition to answers: if you are confused on what increment does to a pointer, search for "C Pointer arithmetic". Also note operation order, specifically in (*destination++) case, which has deference and arithmetic. – Nicko Po Mar 29 '18 at 17:10
  • In addition to answers: do not do this in your code, use pre-existing system libraries. – Yury Schkatula Mar 29 '18 at 17:12

2 Answers2

3

The first loop is looking for the string teminator. When it finds it, with *destination being false, the pointer is still post-incremented with *destination++.

So the next loop starts by decrementing the pointer back to pointing to the '\0' terminator, to start the concatentation.

In the second loop, each character is copied until the string terminator is found with (*destination++ = *source++); which is evaluated as the loop control. Again, this will include the required string terminator being copied.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
  • To be clear the answer to the OP's question is the 2nd paragraph above. The `--destination` is the initialization of the second loop above that decrements the `destination` pointer. – bruceg Mar 29 '18 at 17:13
0

This is a very complicated function for something that shouldn't be written so difficult.

--destination is a weird feature of C. I'm assuming you already know that variable++ increments the variable by one. Similarly variable-- decrements the variable by one. The thing is, when the ++ or -- comes after the variable name, that operation is done after the line is executed as a whole, when it is before the variable, C does the arithmetic first, then evaluates the full line.

For an example:

int c = 5  
print(c++)  -> outputs '5'
print(c)    -> outputs '6'

but

int d = 5
print(++d) -> outputs '6'
print(d)   -> outputs '6'

This is because in the second example, the increment is evaluated before the entire line is evaluate.

Hope that helps.

Oisin
  • 2,082
  • 2
  • 12
  • 8
  • I can't agree it's weird, it's just a way to control execution order. Yes, overall syntax is cumbersome, but hey, this is C, nerd-people only :) – Yury Schkatula Mar 29 '18 at 17:16
  • @Oisin I don't think the standard says exactly *when* the pre and post increments are performed - which is why the [FAQ](https://stackoverflow.com/questions/949433/why-are-these-constructs-using-undefined-behavior-in-c) about using them in the same sequence is undefined behaviour. – Weather Vane Mar 29 '18 at 17:19