Hello, I was reading a c++ book for beginners, and i came across a program that takes two strings and 'tack' one to the end of another, i understood most of it, but there was one part (a loop) that i didn't understand
1 2 3 4 5 6 7 8
void concatString(char* pszTarget, char* pszSource) //takes Source and tacks it
//to the end of Target
pszTarget++; //find the end of pszTarget
while(*pszTarget++ = *pszSource++); /*Here is the part i didn't understand*/
The while loop, according to the book, is suppose to copy pszSource to the end of pszTarget. What i don't understand is how the null character is also copied, and how (*pszTarget++ = *pszSource++) would eveluate to true or false, does the assignment operator return something?
Thanks in advance :D
In C++ each expression can have value that can be casted to bool. Everything except 0, '\0' and null evaluates to true. The three evaluae to false. Because of this, we can use various expressions as conditions for while loops.
It is important to remember, that assignment x = y is also an expression that evaluates to whatever value is being assigned, and that in turn can be cast to boolean and be either true (for anything) or false (for nothing, zero, null).
char Text = "I don't get it"; // The sentence has 15 letters
// (so Text to Text
// are filled, and by C++ magic a '\0'
// character is put in Text)
// Elements 16-199 are uninitialized.
char Source = "Please, explain"; // As above
char * pszTarget = Text; // pointer points to Text;
char * pszSource = Source; // points to Source;
while(*pszTarget) // Meaning untill pszTarget hits '\0', 0 or null
pszTarget++; // Point to next element
// - goes through Text to Text
// At this point pszTarget points at Text
while(*pszTarget++ = *pszSource++);
// Assigns Text value taken from Source
// Repeats for Text and Source by magic of ++ operators, and so on
// When reaches Source it turns out it is '\0',
// so '\0' is assigned to Text.
// Now, since the value of expression (x = y) is y,
// the value of (*pszTarget = *pszSource]) can be
// dereferenced as Text = Source - which is '\0' .
// And this is the breaking condition to the second while loop).