I was just playing with Variable Arguments in C.
I wrote a function that keeps adding the numbers
(till you get a zero in the argument of the function)
Here's something I couldn't figure out:
The following code works :
but this one doesn't :Code:#include <stdio.h> #include <stdarg.h> void add(char *say, ...) { int answer = 0; int temparg = 0; va_list argumentlist; va_start(argumentlist, say); while ((temparg = va_arg(argumentlist, int)) != 0) { answer = answer + temparg; printf("temparg is %d\n", temparg); } printf("%s %d\n", say, answer); va_end(argumentlist); } main() { add("Addition result: ", 1, 0); add("Addition result: ", 1, 2, 0); add("Addition result: ", 1, 2, 3, 0); }
The only difference is in the while loop condition..Code:#include <stdio.h> #include <stdarg.h> void add(char *say, ...) { int answer = 0; int temparg = 0; va_list argumentlist; va_start(argumentlist, say); while (va_arg(argumentlist, int) != 0) { temparg = va_arg(argumentlist, int); answer = answer + temparg; printf("temparg is %d\n", temparg); } printf("%s %d\n", say, answer); va_end(argumentlist); } main() { add("Addition result: ", 1, 0); add("Addition result: ", 1, 2, 0); add("Addition result: ", 1, 2, 3, 0); }
what could the reason be ?
Also, although I read the same paragraph several times,
I still didn't understand the real purpose of
va_list
va_start
va_end
if I say, va_list mahurshi
does it mean that "mahurshi" is like an array ?
why do we need to va_end ?
Thanks for your time and patience in reading this!
------------------------------------------------------------------------
If anyone is too proud to answer my questions politely,
I encourage him/her not to answer. No offence. Thanks.
------------------------------------------------------------------------



LinkBack URL
About LinkBacks



