Why do I get the wrong answer?

When I run this code I get a sum of 473 instead of a correct sum of 495. Why am I not getting the right answer?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream>

using namespace std;

int arysum(int *, int);

int main()
{
	int const size = 9;
	int ary[size] = {33,55,77,99,88,66,44,22,11};
	int sum;

	sum = arysum(ary, size);

	cout<<sum<<endl;

	return 0;
}

int arysum(int *p, int size)
{
	int sum = 0;
	if(size == 1)
	{	
		cout<<*p<<endl;
		return *p;
	}
	cout<<*p<<endl;
	sum = *p + arysum(++p, --size);

	return sum;

}
In function ‘int arysum(int*, int)’:
29:32: warning: operation on ‘p’ may be undefined [-Wsequence-point]

I am not sure why your code doesn't work, but I rewrote it as so and it works this way.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<iostream>

using namespace std;

int arysum(int *, int);

int main()
{
	int const size = 9;
	int ary[size] = { 33, 55, 77, 99, 88, 66, 44, 22, 11 };
	int sum;

	sum = arysum(ary, size);

	cout << sum << endl;
	return 0;
}

int arysum(int *p, int size)
{
	int sum = 0;
	if (size == 1)
	{
		cout << *p << endl;
		return *p;
	}
	cout << *p << endl;
	sum = *p;
	++p;
	--size;
	sum += arysum(p, size);
	return sum;
}



The reason it wasn't working has something to do with your arguments in sum = *p + arysum(++p, --size);
Last edited on
Thanks for the help! I will rewrite it like that.
sum = *p + arysum(++p, --size);
I suspect undefined behavior (but I have not traced it to prove it).
I doubt there is a required order for the evaluation among *p, ++p, and the call to arysum. So which value of p is used for *p.

The rewrite eliminates any ambiguity.
Topic archived. No new replies allowed.