Consider the following code:
#include <stdarg.h>
#include <stdlib.h>
#include <stdio.h>
void foo(const char *arg, ...) {
va_list args_list;
va_start(args_list, arg);
for (const char *str = arg;
str != NULL;
str = va_arg(args_list, const char *)) {
printf("%s\n", str);
}
va_end(args_list);
}
int main(int argc, char **argv) {
foo("Some", "arguments", "for", "foo", NULL);
foo("Some", "arguments", "for", "foo", 0);
return 0;
}
As we can see, foo()
uses variable arguments list to get a list of strings and then print them all. It's supposed that the last argument is null pointer, so arguments list is processed until NULL
is detected.
Function foo()
is called from main()
in two different ways, with NULL
and 0
as the last argument.
My question is: is the second call with 0
as the last argument is correct?
I suppose, that we shouldn't call foo()
with 0
. The reason is that in this case, for example, compiler can't guess from the context that 0
should be treated as null pointer. So it processes it as a usual integer. Then foo()
deals with 0
and cast it to const char*
. The magic begins when null pointer has internal representation different from 0
. As I can understand it leads to the failure in check str != NULL
(because str
will be equal to 0
casted to const char*
which differs from null pointer in our situation) and wrong program behavior.
Are my thoughts right? Any good explanation is appreciated.