`sum(2,4,6)`

should be 10 not 12 ... your first parameter is a counter for the rest of the parameters. If you want the answer to be 12 you should call `sum(3,2,4,6)`

I m trying to learn C++; the problem comes with variable arguments the program is written as below:-

#include<iostream> #include"stdarg.h" using namespace std; int sum(int count,...) { if(count<=0) return 0; va_list arg_ptr; va_start(arg_ptr,count); int s=0; for(int i=0;i<count;i++) s+=va_arg(arg_ptr,int); va_end(arg_ptr); return s; } int main() { cout << sum(2,4,6) << endl;// runs fime as cout << sum(2,4) output is 6 fine but cout << sum(2,4,6) gives output 10 //which i suppose must be 12 cin.get(); cin.ignore(); }

Mantu Singh1.9K

The output from

`sum(2,4,6)`

should be 10 not 12 ... your first parameter is a counter for the rest of the parameters. If you want the answer to be 12 you should call `sum(3,2,4,6)`

Comments

Thanks a lot Got it!

One doubt pls

cout << sum(5,4,6) << endl; //5 -no of args still runs with

//junk value like4245556

Is there any clearer type safe way to do this like

param arrays in C#

One doubt pls

cout << sum(5,4,6) << endl; //5 -no of args still runs with

//junk value like4245556

Is there any clearer type safe way to do this like

param arrays in C#

My 5.

In this case you are still pulling integer values from uninitialized memory space and getting whatever happens to be at that memory address.

Have a look at this article http://www.codeproject.com/Articles/7704/Arrays-in-C-CLI - might be of use

Hi.

For sum(2,4,6), 10 is correct result.

For sum(2,4), 6 is wrong.

The first argument (count) of the sum function tells how many numbers will follow, so ...

sum(2,4,6) tells to sum 2 numbers which values are 4 and 6, for a total of 10.

sum(2,4) tells to sum2 numbers, but the second is not provided, so it will be read from a wrong memory location (probably from the stack location where the first argument, currently 2, is stored).

sum(2,4) should be replaced with sum(1,4).

Regards,

Daniele.

For sum(2,4,6), 10 is correct result.

For sum(2,4), 6 is wrong.

The first argument (count) of the sum function tells how many numbers will follow, so ...

sum(2,4,6) tells to sum 2 numbers which values are 4 and 6, for a total of 10.

sum(2,4) tells to sum2 numbers, but the second is not provided, so it will be read from a wrong memory location (probably from the stack location where the first argument, currently 2, is stored).

sum(2,4) should be replaced with sum(1,4).

Regards,

Daniele.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada
+1 416-849-8900 x 100