This is from the book: C++ Weekend Crash Course, pg 142. It is designed to concatenate two strings, and put a hyphen in the middle. It compiles; it works, but I don't understand why it works.
The two strings are entered in main() as szString1 and szString2. During execution, they are sent to the void function concatString() where they are operated on under different names -- szTarget and szSource. When control passes back to main(), the cout is szString1.
I do not understand how the variable szString1 got modified by the void function. I thought void functions didn't return anything. (I understand the call; I don't understand the return.)
Thanks for your help!
// Concatenate.cpp : Defines the entry point for the console application.
// this will concat two strings with "-" in the middle
#include "stdafx.h"
#include <iostream>
#include <string.h> //required for string functions
using namespace std;
//prototype declaration
void concatString(char szTarget[], char szSource[]);
int _tmain(int argc, _TCHAR* argv[])
{
// read the first string
char szString1[256];
cout << "Enter string #1: ";
cin.getline(szString1, 128);
// now the second string
char szString2[128];
cout << "Enter string #2: ";
cin.getline(szString2, 128);
// concatenate a hyphen onto the first string
concatString(szString1, "-");
// now add the second string
concatString(szString1, szString2);
//and display the result
cout << "\n" << szString1 << "\n";
return 0;
}
void concatString(char szTarget[], char szSource[])
{
// find the end of the first string
int nTargetIndex = 0;
while(szTarget[nTargetIndex])
{nTargetIndex++;}
//tack the second to the end of the first
int nSourceIndex = 0;
while(szSource[nSourceIndex])
{
szTarget[nTargetIndex] = szSource[nSourceIndex];
nTargetIndex++;
nSourceIndex++;
}
//tack on the terminating null
szTarget[nTargetIndex] = '\0';
}