Question

I'm trying to make some function that will do similar effect like printf.

Before I'm making these function I'm learning about va_list, va_start, va_arg... I've made a simple code:

int main()
{
    success("Hello", 356);
}
void success(char* format, ...)
{
    va_list list;
    char *String;
    va_start(list,format);
    String = va_arg(list,char*);
    printf("%s",String);
    va_end(list);
    getchar();
}

This code should fail with runtime error (sending integer while expecting to get string).

I'm trying to avoid the runtime error, I want to print some error message if va_arg fails and exit the program but I don't know how to check if va_arg failed.

I've searched a solution but I couldn't find any. I can't use try->catch because I'm programming in C.

Was it helpful?

Solution

You can't. Because the variable argument functions like your success() has no knowledge of what type of arguments it receives, not even how many arguments.

The best you can do is to use certain format specifier in the format parameter to provide information such as how many variable arguments and/or what type they are. And hope when this function is called, the caller would follow this law. This is what the printf() family functions do.

Reference: How can I discover how many arguments a function was actually called with?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top