Firstly, I'd recommend avoiding global variables. While they can occasionally be useful, when you move on to larger projects they can cause all kinds of problems, so I would strongly advise you DON'T get into the habit of using them.
If you want to pass data from your function out to the calling code, the principal ways are:
1) Return values. A function can return a single object. This can be a single value, or it can be an object such as a vector:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
// This function returns the sum if a + b
int Sum(int a, int b)
{
int theSum = a + b;
return (theSum );
}
// It can be called like this:
void AnotherFunc(void)
{
int mySum = Sum(3, 5);
// This will print the value 8
std::cout << mySum << std::endl;
}
|
2) If you specify your function arguments to be references, using the & symbol, then if the function makes changes to their values, then the calling code will see the changed values:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
void IncrementValues(int& a, int& b)
{
a = a + 1;
b = b + 1;
}
void AnotherFunc(void)
{
int a = 2;
int b = 3;
IncrementValue(a, b);
// The following will print the values 3 and 4 for a and b
std::cout << "a is " << a << " and b is " << b << std::endl;
}
|
3) If you specify your function parameters as pointers, then any changes the function makes to the values pointed to by those arguments will also be visible to the calling code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
void IncrementValues(int* a, int* b)
{
*a = *a + 1;
*b = *b + 1;
}
void AnotherFunc(void)
{
int a = 2;
int b = 3;
IncrementValue(&a, &b);
// The following will print the values 3 and 4 for a and b
std::cout << "a is " << a << " and b is " << b << std::endl;
}
|
Edit: Using functions is one of the very basic foundation skills of writing in C or C++. If you don't understand it, you really need to go back to your texts and learn about them properly. You won't get far in programming without them.