incrementing values with array parameters

That's the best subject line I can think of to explain this problem. I just finished the first semester of C++, but unfortunately didn't get that far into arrays. Very disappointing. I'm trying to simply increment the values in an integer array by using a seperate function that should increment each indexed value. The program works fine when a void function is used to handle the loop and all the output. But returning a value for each index seems to be a problem. The program compiles in VC++ with warning C4715. Here's the code and the output.

#include <iostream>

int one_more(int a[], int sz);

int main()
{
using namespace std;

int arr[] = {2, 4, 6, 8, 10, 12}, size = 6;
int i, new_num;

cout << "This is a test.\n";

for(i = 0; i < size; i++)
{
new_num = one_more(arr, size);
cout << new_num << endl;
}

return 0;
}

int one_more(int a[], int sz)
{
for(int i = 0; i < sz; i++)
return ++a[i];
}

This is a test.
3
4
5
6
7
8

As you can probably see, the first value is continually incremented, when all values in the initialized array should be incremented and displayed. That's all there is to say about that. I'd very much appreciate any input.
The problem is that a return statement effectively ends the function (to put it simply) and transfers control back to main(). So when you run your code, it will increment the first variable then return ++a[i] back to main().
Hey, that was quick. This is a great forum. I understand what you're saying, Archaic, but I didn't think that was a problem. I expected the function to be called and run repeatedly until the outer loop ended. That was the plan. Can that work?
Last edited on
That won't work. As soon as the program encounters the return statement the function will transfer control back to main(), and the contents of the function will get removed from the stack, so the for loop and its progress will be gone.

I think a solution to this would be to have a for loop within a for loop. Something like:

1
2
3
4
5
6
7
for (int i = 0; i < sz; i++)
{
    for (int j = 0; j < sz; j++)
    {
        a[j]++;
    }
}


Since arrays are passed by reference you can just use a void function and not worry about returning anything.


What's up? That was great. Especially that low-level explanation. You know your programming, Archaic. I understand that void is the right thing to do in this case. I just wanted to make a return value work, and understand as much as I can about each procedure. That's all. Just so you know, I changed the outer function to this:

int one_more(int a[], int sz)
{
for (int i = 0; i < sz; i++)
{
for (int j = 0; j < sz; j++)
a[j]++;
return a[i]++;
}
}

It still compiled with the same warning, but this time worked as I'd hoped. I guess the compiler can detect that it's not the best way to do what I want to do. So I'll keep that in mind. Thanks.
Topic archived. No new replies allowed.