Adding together numbers.

Heya,
I'm having trouble with a very simple problem; adding numbers. Here's my code so far:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <cstdio>
#include <vector>
template<class T>
T sum(std::vector<T> list,unsigned max,unsigned iter=0)
{
    iter<max?
        list[iter]+sum(list,max,iter+1)
        :
        list[max];
}
main()
{   std::vector<double> l;
    l.push_back(1.0);
    l.push_back(2.0);
    printf("%d",sum<double>(l,1));
    }
No matter what I do, I always get 0! D:
Last edited on
You don't have a return statement in your function.
main() should be int main()
And you should check that iter or max is smaller than the vector size ( list.size() )
main() gives just a warning, a literal value is equal to returning that value. (Putting 0; as function content is the same as return 0;, so iter<max?list[iter]+sum(list,max,iter+1):list[max]; equals return iter<max?list[iter]+sum(list,max,iter+1):list[max];)

The final code (according to you):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <cstdio>
#include <vector>
template<class T>
T sum(std::vector<T> list,unsigned iter=0)
{
    return iter<(list.size()-1)?
        list[iter]+sum(list,iter+1)
        :
        list[list.size()-1];
}
int main()
{   std::vector<double> l;
    l.push_back(1.0);
    l.push_back(2.0);
    printf("%d",sum<double>(l));
    }
Still prints 0.
Nevermind, fixed it. printf("%d",...) should have been printf("%f",...).
(Putting 0; as function content is the same as return 0;, so iter<max?list[iter]+sum(list,max,iter+1):list[max]; equals return iter<max?list[iter]+sum(list,max,iter+1):list[max];)
That's not true
ISO/IEC 14882:2003 ยง6.6.3, 2:
Flowing off the end of a function is equivalent to a return with no value; this results in undefined
behavior in a value-returning function.

Hm, true, it doesn't work that way. But I remember doing something similar in another code once.. odd.
IIRC with G++ it works the way you say, but on MSC++ it doesn't even compile
Topic archived. No new replies allowed.