dpp312
dpp312

Reputation: 15

Why is the output different? (putting array in a function problem)

I want the output to be: 1 2 2 2

But why is the output: 1 2 3 4

What's wrong with this code?

#include <iostream>
using namespace std;

int arr[] = {0};

int pluss(int ar[],int a){
ar[0]++;
cout<<ar[0]<<endl;
if(a==0){
    pluss(ar,a+1);
    pluss(ar,a+1);
    pluss(ar,a+1);
    }
}

int main() {
pluss(arr,0);
return 0;
}

EDIT: So, the "ar" is global and not local to one child function? how to make it so the "ar" is only local to one child function? I mean: the "ar" in the first pluss(ar,1) is different from the "ar" in the second pluss(ar,2)?

Upvotes: 0

Views: 31

Answers (2)

Armali
Armali

Reputation: 19395

how to make it so the "ar" is only local to one child function?

If you don't like to pass each array element as integer value, you could wrap the array in a struct, since structures are passed by value rather than by reference.

#include <iostream>
using namespace std;

struct s { int a[1]; } arr = {0};

int pluss(struct s ar, int a)
{
    ar.a[0]++;
    cout <<ar.a[0] <<endl;
    if (a==0)
    {
        pluss(ar, a+1);
        pluss(ar, a+1);
        pluss(ar, a+1);
    }
}

int main()
{
    pluss(arr, 0);
    return 0;
}

Upvotes: 0

vcp
vcp

Reputation: 962

Your code is equivalent of :

int main() {
pluss(arr,0);
pluss(arr,1);
pluss(arr,1);
pluss(arr,1);
return 0;
}

Since each call to pluss definitely increments the array element, before printing it, expected output is 1, 2, 3, 4.

Upvotes: 2

Related Questions