0

Why does the following code go into an infinite loop:

#include<iostream>
using namespace std;

void printarray(int arr[], int n, int i);

int main(){
    int arr[] = {1,2,3,4,5};
    int n = sizeof(arr)/sizeof(arr[0]);
    printarray(arr,n,0);
    return 0;
}

void printarray(int arr[], int n, int i){
    if(i >=n)
        return;
    cout<<arr[i]<<"\t";
    return printarray(arr,n,i++);    //Replacing i++ by i+1 works fine
}

However, if I use i+1 instead of i++, the code works fine.As per my understanding i++ is effectively the same as i+1. Then what is the problem here?

yksolanki9
  • 429
  • 2
  • 7
  • 14
  • 1
    `As per my understanding i++ is effectively the same as i+1` What would make you think so? – dxiv May 01 '20 at 23:58

2 Answers2

2

i++ means "increment i after the comand finishes"

So you call the recursive function with always the same i. Only when the function returns iis incremented.

To achieve your goal use ++i instead.
Or better, as @dxiv pointed out, i+1

Ripi2
  • 7,031
  • 1
  • 17
  • 33
0

I think you should put ++i instead of i++

Mickael B.
  • 4,755
  • 4
  • 24
  • 48