Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my strCopy implementation work?

Tags:

c++

Here is an implementation of strCopy

void strcopy2(char *dst, char const *src){
    while ((*dst++ = *src++))
        ;
}

Our professor asked us to reproduce this code without using pointers, so I came up with the following function:

void strcopy(char dst[], char const src[]){
    size_t i = 0;
    while (dst[i] = src[i++])
        ;
}

It works well, but I realised, that under the hood the function must still be using pointers, as we nowhere return any value. In other words, I though the last function would use pass by value but this is obviously not the case. So what is happening under water, and is there actually any difference between the two methods?

like image 341
Slugger Avatar asked Oct 18 '16 10:10

Slugger


1 Answers

Not just under the hood… both dst and src, despite appearances, actually are pointers! The [] syntax in parameter lists is syntactic sugar (or syntactic pepper really) but it's lying to you; these are char* dst and char const* src for reals.

8.3.5/5 [dcl.fct] Functions:

After determining the type of each parameter, any parameter of type “array of T” or of function type T is adjusted to be “pointer to T”.

like image 132
Lightness Races in Orbit Avatar answered Sep 21 '22 02:09

Lightness Races in Orbit