Here is a smaller program I made but the concept is much the same, what I understand( which is obviously not the case ) with this program is:

The function returnFunc is called 3 times in main

Each time is is called it returns a value from the array

Is the index being reset each time the function returns a value?

#include <iostream>
using namespace std;

main() {

    int funcReturn();
    
    cout << "Program should call function which will then return elements in array" << endl;
    
    
    for(int i = 0; i < 3; i++) {
    cout << funcReturn() << endl;
    }
    
    
    
    
}


int funcReturn() {
    
    int a[3] = {33, 44, 55};
    
    for( int i = 0; i < 3; i++) {
        return a[i];
    }
}

Recommended Answers

All 3 Replies

int funcReturn() {
    int a[3] = {33, 44, 55};
    for( int i = 0; i < 3; i++) {
        return a[i];
    }
}

This is not doing what you think it is. After it hits the return statement
it returns. And every time you call this function, the "i" will be always 0.

Try using static like so( warning not a good way )

int funcReturn() {
   static int index = -1;
   index = (index+1) % 3;
    int a[3] = {33, 44, 55};
    for(;i < 3; i++) {
        return a[i];
    }
}

A better way is to pass an array to function. Also you are missing the
"int" part in "int main()". main has to be declared int by def.

#include iostream
using namespace std;

int funcReturn(int& index);

int main()
{
     for(int i=0; i<3; i++)
     {
          cout << funcReturn(i);
     }

     return 0;
}

int funReturn(int& index)
{
     int a[3] = {33, 44, 55};
    
     return a[index];
}

excellent,thank you :D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.