# Thread: Give value of a function to variable is different from print its value

Enjoy an ad free experience by logging in. Not a member yet? Register.
1. ## Give value of a function to variable is different from print its value

I did this small program that sums the values of all the elements in the array recursively.
At first I executed it and everything went fine, with the function that implements the recursive sum printing the value as I expected in the line
Code:
`cout << soma << endl;`
However when trying to print it's value outside the function, it doesn't work, either way.
In the first:
Code:
`  cout << somaRecursiva(a,0,0,tamanho) << endl;`
it prints always zero and in the second:
Code:
``` b = somaRecursiva(a,0,0,tamanho);
cout << b << endl;```
it prints a random value

So what I am doing wrong?

Code below and thanks for my input.

Code:
```int somaRecursiva (int a [], int indice, int soma, int tamanho);

main () {
int a [] = {1,2,3,4,5};
int tamanho=5;
int soma=0;
int indice=0;
int b;
cout << somaRecursiva(a,0,0,tamanho) << endl;
printf ("\n");
printf ("\n");
b = somaRecursiva(a,0,0,tamanho);
cout << b << endl;
}

int somaRecursiva (int a [], int indice, int soma, int tamanho) {
if (tamanho == indice) {
cout << soma << endl;
return soma;
}
else {
soma+= a[indice];
indice++;
cout << soma << endl;
cout << indice << endl;
somaRecursiva (a, indice, soma, tamanho);
}
}```

2. Try changing the first (a[]) argument to a pointer, as in
Code:
`int somaRecursiva( int* a, int indice, int soma, int tamanho);`
What you are doing is copying the array on each pass to the recursive function, which is sometimes not dealt with properly, depending upon the compiler, compiler settings, etc. By passing as a pointer, it doesn't copy the array. It just passes a pointer to it.

3. Ok, I rewrote it, but didn't change anything. Here is the new code, using a pointer
Code:
```int somaRecursiva (int * ptr, int soma, int * prt2);

main () {
int a [] = {1,2,3,4,5};
int * ptr = &a[0];
int * ptr2 = &a[5];
int tamanho=5;
int soma=0;
int b;
cout << somaRecursiva(ptr,0,ptr2) << endl;
printf ("\n");
printf ("\n");
b = somaRecursiva(ptr,0,ptr2);
cout << b << endl;
}

int somaRecursiva (int * ptr, int soma, int * ptr2) {
if ((*ptr) == (*ptr2)) {
cout << soma << endl;
return soma;
}
else {
soma+= *ptr;
ptr++;
cout << soma << endl;
somaRecursiva (ptr, soma, ptr2);
}
}```

4. \$spacer_open \$spacer_close
5. Well, the two argument forms are effectively the same - type [] vs. type* a. However, the latter is preferred, especially if you may pass a malloc'd array. I'll have to analyze the behavior of your code before I comment further.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•