简体   繁体   中英

Nulls in variadic C functions

If I defined a variadic function:

#include <stdio.h>
#include <stdarg.h>

int f(char*s,...)
{ 
    va_list ap;
    int i=0;
    va_start(ap, s);
    while(s)
    {
       printf("%s ", s);
       i++;
       s=va_arg(ap,char*);
    }
    va_end(ap);
    return i;
}

int main()
{ 
    return f("a","b",0);
}

gcc (linux x64) compiles this and the exe runs and prints "ab ".

is there any need for a cast like:

return f("a","b",(char*)0)

on common systems?

The compiler can't auto promote pointer for variadic parameter, for example that why when you want to print a pointer in printf you must cast it to void * :

printf("%p", (void *)ptr);

The same rule applies to all variadic functions, compiler can't know that your function expect a char * , and 0 is by default just an integer so yes you need to cast it (char *)0 .


Even NULL must be cast with your function (char *)NULL


so why does main() work and when will it fail?

Your code don't really "work". Your code invoke undefined behavior, anything can happen, so no one can answer this. Here you are lucky, but next time maybe not.

Your code should work fine on any system that supports the SYSV x64 ABI standard . It may work on systems that use some other ABI standard that has similar requirements, and may fail on any system that uses some other ABI 1 . This is all undefined according to the C standard.


1 In particular, Microsoft does NOT follow the standard x64 ABI, they have their own standard.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM