By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,943 Members | 1,875 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,943 IT Pros & Developers. It's quick & easy.

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

P: 1
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.
Dec 9 '10 #1
Share this Question
Share on Google+
2 Replies


Banfa
Expert Mod 5K+
P: 8,916
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.
Dec 9 '10 #2

100+
P: 1,059
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <stdarg.h>
  3. void sum(char *msg, ...)
  4. {
  5. int total = 0;
  6. va_list p;
  7. int arg;
  8. va_start(p, msg);
  9. while ((arg = va_arg(p,int)) != 0) {
  10. total += arg;
  11. }
  12. printf(msg, total);
  13. va_end(p);
  14. }
  15.  
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
Dec 10 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.