My college professor recently gave us a task of implementing our own smart pointer classes. In his boilerplate code for copying strings I found this piece beautiful syntactic sugar:
while (*sea++ = *river++);// C Sting copy
I looked further into this code and found that it is the exact code as found in strcpy.c and further explanation of how it works, in the following stackoverflow question: How does “while(*s++ = *t++)” copy a string?
When I tried to use this syntactic sugar in my following code it gave garbage as a result and deleted the string stored in "river":
#include<iostream>
#include<cstring>
using namespace std;
void main()
{
const char *river = "water";// a 5 character string + NULL terminator
char *sea = new char[6];
while (*sea++ = *river++);
cout << "Sea contains: " << sea << endl;
cout << "River contains: " << river << endl;
}
RESULT:
I know that I can simply achieve the desired result with the following code instead:
int i = 0;
while (i<6)
{
sea[i] = river[i];
i++;
}
But this is not the answer I want. I would like to know is there something wrong with the implementation of my while loop or the instantiation of my char pointers?