Argument variables in C - c

I am writing a method that takes in a number n and n ints(a variable number) and this function will return the sum of the ints not including n. I am stuck on how to access each paramater individually. Here is what I have so far, I read about it online and hopefully I am on the right track.
method that seem to be useful found on the net are:
va_start()
va_arg()
va_end()
int sumv(int n, ...)
{
va_list list;
int sum = 0;
while(n>0)
{
//*********************
//this is the part where I am stuck on, how do I get each paramater?
//I know it will be an int
//*********************
n--;
}
return sum;
}

It should look something like this:
int sumv(int n, ...)
{
va_list list;
va_start(list, n);
int sum = 0;
while(n>0)
{
sum += va_arg(list, int);
n--;
}
va_end(list);
return sum;
}

You're basically looking for this:
#include <stdio.h>
#include <stdarg.h>
int sumv (int n, ...) {
va_list list;
int sum = 0;
va_start (list, n);
while (n-- > 0)
sum += va_arg (list, int);
va_end (list);
return sum;
}
int main (void) {
printf ("%d\n", sumv (5, 1, 2, 3, 4, 5));
return 0;
}
This prints the sum of the first five natural numbers, 15.
The basic idea is to va_start, giving both the list to use and the final argument in the function before the variable arguments begin.
Then, each call to va_arg gives you the next argument of the type specified (int here). This particular code calls it based on your counter but you could equally use a sentinel value at the end such as a negative number, provided that negative numbers aren't valid in the arguments.
Then, once you've processed all the arguments, use va_end to terminate the processing.

Related

a parameter list with an ellipsis can't match an empty parameter name list declaration

Please I don't know why I get "a parameter list with an ellipsis can't match an empty parameter name list declaration" when I run the code below. I believe I did everything right but my gcc compiler is given me that error.
#include <stdarg.h>
/**
* main - check the code
*
* Return: Always 0.
*/
int main(void)
{
int sum;
sum = sum_them_all(2, 98, 1024);
printf("%d\n", sum);
sum = sum_them_all(4, 98, 1024, 402, -1024);
printf("%d\n", sum);
return (0);
}
/**
* #sum_them_all - calculate the entire sum.
*
* #n: constant int param signifiying the total num to sum
* #... - ellipsis (other params)
*
* Return: the sum
*/
int sum_them_all(const unsigned int n, ...)
{
unsigned int i;
va_list ag;
unsigned int sum = 0;
va_start(ag, n);
for (i = 0; i < n; i++)
{
sum += va_arg(ag, int);
}
va_end(ag);
return (sum);
}```
You can solve this in one of two ways. First, you could move the main function after your sum_them_all function so that the compiler knows how to utilize this function. Second, you could add a function prototype at the beginning of your code before the function is called.
int sum_them_all(const unsigned int, ...);
Either way should resolve your issue.

Variable number of arguments in C programmng

Whenever we use variable argument function in C language, we have to provide the total number of arguments as the first parameter. Is there any way in which we can make a function with variable arguments without giving the total number of arguments?
[update from comment:]
I want to use functions like sum(1,2,3) should return 6. i.e, no counter should be there.
Several ways:
pass simple, explicit count (which you don't want in this question)
pass some format string, similar to printf and scanf
pass some "mode" parameter, and have each mode require specific varargs
have all varargs to be of same type, and require last argument to be some special value, AKA sentinel value, such as NULL for pointer list or max/min value of the type for integer types, or NaN for doubles.
However you do it, you have to have some way for the function to know the types of the varargs, as well as a way for it to know when they end. There is no built-in way in C, argument count is not passed to the function.
I want to use functions like sum(1,2,3) should return 6. i.e, no counter should be there
You could define a sentinel. In this case 0 might make sense.
/* Sums up as many int as required.
Stops adding when seeing the 1st 0. */
int sum(int i, ...)
{
int s = i;
if (s)
{
va_list ap;
va_start(ap, i);
/* Pull the next int from the parameter list and if it is
equal 0 leave the while-loop: */
while ((i = va_arg(ap, int)))
{
s += i;
}
va_end(ap);
}
return s;
}
Call it like this:
int sum(int i, ...);
int main(void)
{
int s = sum(0); /* Gives 0. */
s = sum(1, 2, 3, 0); /* Gives 6. */
s = sum(-2, -1, 1, 2, 0); /* Gives 0. */
s = sum(1, 2, 3, 0, 4, 5, 6); /* Gives 6. */
s = sum(42); /* Gives undefined behaviour! */
}
The sum() function alternatively could also look like this (but would do one useless addition of 0):
/* Sums up as many int as required.
Stops adding when seeing the 1st 0. */
int sum(int i, ...)
{
int s = i;
if (s)
{
va_list ap;
va_start(ap, i);
/* Pull the next int from the parameter list and if it is
equal 0 leave the do-loop: */
do
{
i = va_arg(ap, int);
s += i;
} while (i);
va_end(ap);
}
return s;
}
You don't have to supply that number of arguments. For instance, consider the signature for printf:
int printf( const char* format, ... );
It "finds out" how many arguments it needs by parsing the string you give it. Of course, your function needs to know the amount of arguments in some way, otherwise what sense does it make for it to take a variable number of arguments?
It is possible to create a variadic function which takes a count as the first argument, then use variadic macros to add the count value automatically:
#include <stdarg.h>
#define count_inner(a1, a2, a3, a4, a5, num, ...) (num)
#define count(...) count_inner(__VA_ARGS__, 5, 4, 3, 2, 1)
#define sum(...) sum_func(count(__VA_ARGS__), __VA_ARGS__)
int sum_func(int count, ...)
{
va_list ap;
va_start(ap, count);
int total = 0;
while(count--)
total += va_arg(ap, int);
va_end(ap);
return total;
}
Using the sum macro instead of sum_func allows the count to be omitted, provided there are between 1 and 5 arguments. More arguments/numbers can be added to the count_inner/count macros as required.
int main(void)
{
printf("%d\n", sum(1));
printf("%d\n", sum(1, 2));
printf("%d\n", sum(1, 2, 3));
printf("%d\n", sum(1, 2, 3, 4));
}
Output:
1
3
6
10
Well, the problem is that you have to somewhat indicate to the function that your argument list is exhausted. You've got a method from printf(3) which is that you can express the order and the type of arguments in your first parameter (forced to be a string arg) you can express it in the first parameter, or, for the adding, as the value 0 doesn't actually add to the sum, you can use that value (or some other at your criteria) to signal the last parameter. For example:
int sum(int a0, ...)
{
int retval = a0;
va_list p;
va_start(p, a0);
int nxt;
while ((nxt = va_arg(p, int)) != 0) {
retval += nxt;
}
return retval;
}
This way, you don't have to put the number of arguments as the first parameter, you can simply:
total = sum(1,2,3,4,5,6,7,8,9,10,0);
But in this case you have to be careful, that you never have a middle parameter equal to zero. Or also you can use references, you add while your reference is not NULL, as in:
int sum(int *a0, ...)
{
int retval = *a0;
va_list p;
va_start(p, a0);
int *nxt;
while ((nxt = va_arg(p, int*)) != NULL) {
retval += *nxt;
}
return retval;
}
and you can have:
int a, b, c, d, e, f;
...
int total = sum(&a, &b, &c, &d, &e, &f, NULL);

How to implement a running variable in a recursive function

At the moment I am coding a program in which I need a variable count that increments every time I call the function. In my case I have a recursive function and want to know how many iterations the program does.
I simplified the code by computing the factorial of a number.
My first approach does not work and ends up with warning messages:
#include <stdio.h>
int factorial(unsigned int i, int *count)
{
*count += 1;
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1, &count);
}
int main()
{
int i = 10;
int count = 0;
printf("%d Iterations, Factorial of %d is %d\n", count, i, factorial(i, &count));
return 0;
}
warning: passing argument 2 of ‘factorial’ from incompatible pointer type
My second approach does not work either but also does not ends up with any warning messages.
#include <stdio.h>
int factorial(unsigned int i, int count)
{
count += 1;
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1, count);
}
int main()
{
int i = 10;
int count = 0;
printf("%d Iterations, Factorial of %d is %d\n", count, i, factorial(i, count));
return 0;
}
How can I make it run? Any ideas? I use Ubuntu and gcc.
There is no need for static variables, as other solutions suggest. The following is correct:
int factorial(unsigned int i, int *count)
{
*count += 1;
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1, count);
}
int main(void)
{
int i = 10;
int count = 0;
printf("%d Iterations, Factorial of %d is %d\n", count, i, factorial(i, &count));
return 0;
}
One note: as the order of parameter evaluation in the printf statement is not guaranteed, as I understand it the value of count in the call to printf may either be zero (it is passed before factorial was called) or may be 10 (the value after factorial was called). Therefore, main could better be written as:
int main(void)
{
int i = 10;
int count = 0;
int fact= factorial(i, &count);
printf("%d Iterations, Factorial of %d is %d\n", count, i, fact);
return 0;
}
6.5.2.2 Function calls: 10 The order of evaluation of the function designator, the actual arguments, and subexpressions within the actual arguments is unspecified, but there is a sequence point before the actual call.
In your first case, factorial() function, count is of type int *. So, while calling the function recursively (in the return statement), do not pass address of count, just pass the count itself.
That said, as count is to be modified in the function call of factorial(), don't pass both of them (the variable and the function call which modifies the variable) in the same argument list as there is no sequence point in the elements passed as argument list, so you'll end up invoking undefined behavior.
Declare the count variable as static inside the factorial function itself.
static int count = 0;
There are two ways of solving this problem.
Declare a static variable in the recursive function to count the no of times it is called.
e.g.
int factorial(unsigned int i, int *count)
{
static int count2;
*count = ++count2;
if(i <= 1)
{
return 1;
}
return i * factorial(i - 1, count);
}
int main()
{
int i = 10;
int count = 0, fact;
fact = factorial(i, &count);
printf("%d Iterations, Factorial of %d is %d\n", count, i, fact);
return 0;
}
Have count as a pointer to integer, which can then be updated in each function to find the number of iterations.
e.g.
int factorial(unsigned int i, int *count)
{
(*count)++;
// Remaining lines the same as first solution.
}
The second solution will only work in some special types of recursive functions where the first function calls the second and the second calls the third, etc. It will not work for example in a recursive fibbonaci sequence algorithm.
The first solution is a more general one, and will work for all conditions.

Get variable arguments directly from stack

I'm playing with the stack and function's call parameters.
What I want to achieve here is to get the value of variable parameters directly using the stack.
It works (or seems to work) fine when I don't use variable parameters.
Here is what is working:
void test(int a, int b)
{
unsigned char *ptr;
int i;
ptr = (unsigned char*)&a;
for (i = 0; i < 4; i++)
{
printf("%d,", *ptr);
}
}
That works, I can retrieve the value of b;
The same code using
void test(int a, ...);
as function's prototype doesn't work.
I cant understand what's going on here.
Can you help me?
Thanks !
Edit:
Ok, then it seeems there is no stable and reliable way to do that kind of stuff on my own.
Lets say that in the callee function I know the data size (but not the type) of variable argument, is there a way to grab them ?
As long as you know or can determine the number of arguments, you can use the macros from <stdarg.h>:
#include <stdio.h>
#include <stdarg.h>
void test1(int n, ...)
{
va_list args;
va_start(args, n);
for (int i = 0; i < n; i++)
{
int j = va_arg(args, int);
printf("%d: %d\n", i, j);
}
va_end(args);
}
void test2(int a, ...)
{
va_list args;
int i = 0;
printf("%d: %d\n", i++, a);
va_start(args, a);
int j;
while ((j = va_arg(args, int)) > 0)
printf("%d: %d\n", i++, j);
va_end(args);
}
The difference is in how these two functions are called:
int main(void)
{
test1(4, 1, 3, 7, 9);
test2(1, 3, 7, 9, 0);
return(0);
}
The printf() family uses an alternative but equivalent technique; those functions scan the format string and determine the type of each argument (as well as the number of arguments) from the information in the format string. So, your main options are:
count - test1()
sentinel - test2()
format string - printf()
In functions with ... you can use va_* macro
void test(int a, ...) {
va_list ap;
va_start(ap, a);
// Your code
va_end(ap);
}

How can I pass any number of arguments in User define function in C?

How can I pass any number of arguments in User define function in C?what is the prototype of that function?It is similar to printf which can accept any number of arguments.
Look here for an example.
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
int maxof(int, ...) ;
void f(void);
main(){
f();
exit(EXIT SUCCESS);
}
int maxof(int n args, ...){
register int i;
int max, a;
va_list ap;
va_start(ap, n args);
max = va_arg(ap, int);
for(i = 2; i <= n_args; i++) {
if((a = va_arg(ap, int)) > max)
max = a;
}
va_end(ap);
return max;
}
void f(void) {
int i = 5;
int j[256];
j[42] = 24;
printf("%d\n",maxof(3, i, j[42], 0));
}
Such a function is calle variadic, but such functions are much less useful than they might at first seem. The wikipedia page on the topic is not bad, and has C code.
The basic problem with such functions is that the number of parameters cannot in fact be variable - they are must be fixed at compile time by a known parameter. This is obvious in printf:
printf( "%s %d", "Value is", 42 );
The number of % specifiers must match the number of actual values, and this is true for all other uses of variadic functions in C, in one form or another.

Resources