#include <iostream>
#include <cstdarg>
usingnamespace std;
int main (int argc , char* argv[])
{
int varFunc(float,int, ...);
varFunc(2.36f, 3, "Jai Shri Ram \n","This is not hello world","\nRather a variable argument's program");
return 0;
}
int varFunc(float iArg ,int roh , ...)
{
va_list x;
va_start(x,roh);
int i = 0;
while(cout<<i++) // iam printing it to count the number of times this loop is executed before the error is caused
{
char *rj = va_arg(x,char*);
if(rj == 0) // i think that this statement is never becoming true throughout whole loop
{
cout<<"hello";
break;
}
cout<<rj;
}
va_end(x);
return 0;
}
I think there is some problem with that if statement in function varFunc
va_arg will not necessary return null if there is no more arguments to read. Isn't roh the number of strings passed in? In that case you can use that to make sure the loop don't run more than roh iterations.
@HiteshVaghani1
cout << *rj; will print the first char in the string.
@Peter87 : no , roh is just a normal argument which can be used for any other task , anyways in which case va_arg returns null ?? ... also is there any good article of "variable argument" you know ?
@HiteshVaghani1 : thanks but when i said how can i print them i meant how to rectify that error
va_arg returns null if you give a null pointer as argument. varFunc(2.36f, 3, NULL);
You have to know, from previous arguments, if there are more arguments to read. You could remember to always pass a null pointer as the last argument, but if you forget to do so things will go wrong. That is one of the problems with va_arg.
If you are using C++11 it could be done much more safely by using variadic templates or std::initializer_list.