I've written a method that takes a variable number of arguments. My problem is that the method is supposed to do one thing if there is only one argument, and something different if it recieves multiple arguments.
If it's one argument I'm supposed to get info from a global variable, but if its more than one I'm getting the info from the last argument given.

Here is what the method looks like and what it does when there is multiple arguments. Since the last argument always is 4 digits I know when to stop the for loop.

//Sends the message
void sendMessage(int tlfNumber1, ...) {
	//Initiating va_list element
	va_list argumentList;
		
	//Starting/getting the parameters
	va_start(argumentList, tlfNumber1);
	
	int i;
	int j;
	//Looping all the elements
	  for (i = tlfNumber1; j != 4; i = va_arg(argumentList, int)) {
		  /* Checking what parameter it is by converting the int argument to string and check the length of the string.
		   * If the argument was 4 digits it was the message_ID and therefore the last argument.
		   */
		  char paramAsString[20];
		  sprintf(paramAsString, "%d", i);
		  j = strlen(paramAsString);
		
		  printf("%d ", j);
	  }
}

So I need som way to check the number of arguments passed to this method.

Thanks

Typically the two options for a case like this are a count argument and a sentinel argument:

#include <stdio.h>
#include <stdarg.h>

/* gets a count of arguments */
void TestCount(int x, int n, ...)
{
    va_list args;

    va_start(args, n);

    printf("%d: ", x);
    while (--n >= 0) printf("%-3d", va_arg(args, int));
    putchar('\n');

    va_end(args);
}

/* gets a sentinel as the last argument to mark the end */
void TestSentinel(int x, ...)
{
    va_list args;
    int value;

    va_start(args, x);
    printf("%d: ", x);
    while ((value = va_arg(args, int)) != -1) printf("%-3d", value);
    putchar('\n');

    va_end(args);
}

int main()
{
    TestCount(0, 3, 1, 2, 3);
    TestSentinel(1, 1, 2, 3, -1);

    return 0;
}

Edited 7 Years Ago by Tom Gunn: n/a

Thanks alot. I used the count arugement to test if there only was one argument, and if there were multiple arguments I used sentinel to stop the loop.

This question has already been answered. Start a new discussion instead.