I've noticed something interesting in C++ programming. I've always done tricky stuff with pointers and references to have functions deal with arrays. Doing exercises again out of a C++ book has shown me an easier way, I didn't even know was there. It's weird to me.
When dealing with arrays, it seems if I pass an array to a function although I cannot return an array - if the array is changed it changes for the whole program. The array is seemingly global. Hence this code works (GCC 4.7)...
#include <iostream>
using namespace std;
int read_inputs(double inputs[], int capacity) {
int current_size = 0;
cout << "Please enter values, Q to quit:"<<endl;
bool more = true;
while (more)
{
double input;
cin >> input;
if (cin.fail()) {
more = false;
} else if (current_size < capacity) {
inputs[current_size] = input;
current_size++;
}
}
return current_size;
}
void multiply(double values[], int size, double factor)
{
for (int i = 0; i < size; i++)
{
values=values * factor;
}
}
void print(double values[], int size)
{
for (int i = 0; i < size; i++)
{
if (i > 0) {cout << ", ";}
cout << values;
}
cout << endl;
}
int main() {
const int CAPACITY = 1000;
double values[CAPACITY];
int size = read_inputs(values, CAPACITY);
print(values, size);
multiply(values, size, 2);
print(values, size);
return 0;
}