Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

40,026 questions

51,982 answers

573 users

How to create a function with dynamic number of parameters in C++

1 Answer

0 votes
#include <iostream>
#include <stdarg.h>

using std::cout;
using std::endl;

int sumAll(int parameters, ...)
{
	va_list varList;

	va_start(varList, parameters);

	int sum = 0;
	for (int i = 0; i < parameters; i++)
	{
		int n = va_arg(varList, int);
		sum = sum + n;
	}

	va_end(varList);

	return sum;
}

int main()
{
	int rv = sumAll(3, 1, 2, 3);

	cout << "Sum = " << rv << endl;

	cout << "Sum = " << sumAll(5, 7, 8, 9, 10, 11) << endl;

	return 0;
}


/*
run:

Sum = 6
Sum = 45

*/

 



answered Feb 17, 2018 by avibootz

Related questions

1 answer 164 views
4 answers 300 views
4 answers 183 views
4 answers 198 views
1 answer 166 views
...