How to declare user defined function with variant no of arguments in c? like printf.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sajad ahmed
    New Member
    • Dec 2010
    • 1

    #1

    How to declare user defined function with variant no of arguments in c? like printf.

    for example the printf function can take different no of arguments:
    printf("%d%d",x ,y); //here it takes only 3 arguments
    printf("%d%d%d" ,a,b,c); // n here it takes 4 argumets

    how can we declare user defined function like that, that can take many arguments,

    i know when we use argv, argc as arguments in the main function. but i want a non main function behave like that.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Yep you can declare a varidac function just like printf and scanf.

    You use the ellipsis to the the compiler that a variable number of arguments with variable type follows, this is how printf is declared with an ellipsis int printf ( const char * format, ... );.

    In the code of the function you use the macros in stdarg.h (or cstdarg for C++) to access the variables passed.

    Comment

    • johny10151981
      Top Contributor
      • Jan 2010
      • 1059

      #3
      Code:
      #include <stdio.h>
      #include <stdarg.h>
      void sum(char *msg, ...)
      {
      int total = 0;
      va_list p;
      int arg;
      va_start(p, msg);
      while ((arg = va_arg(p,int)) != 0) {
      total += arg;
      }
      printf(msg, total);
      va_end(p);
      }
      follow the above simple example

      It will add up all integer numbers.

      But if you send String instead of integer you wont get any error/warning message.

      If you want to manage various type variable you will have to think something like printf function

      Comment

      Working...