0

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)?

1

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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)?
Method signature int pluss(int ar[],int a) is equivalent of int pluss(int *ar,int a). So you are passing pointer to first element of array, so any local change in the method is always going change the original array in main. To avoid this behavior you may pass each array element as integer value.
0

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;
}

1 Comment

Or use std::array<int, 1>, which is essentially like that struct s but with additional other features.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.