#define FOO (NULL) int main(int...">

Avoiding the warning about "null argument where non-zero"

Compiling the following code:

#include <string.h>
#define FOO (NULL)

int main(int argc, char *argv[])
{
    char *foo;

    if (FOO)
        foo = strdup(FOO);

    return 0;
}

leads to the following compiler warning:

foo.c: In function β€˜main’:
foo.c:9:3: warning: null argument where non-null required (argument 1) [-Wnonnull]
   foo = strdup(FOO);
   ^

However, strdupit will not be called if FOOthere is NULLdue to verification if (FOO). Is there any way to avoid this warning?

Thank!

+4
source share
2 answers

If the idea is to assign a value foo, if foodefined, you can try:

//#define FOO "lorem ipsum"

int main()
{
    char *foo;
    #ifdef FOO
        foo = strdup(FOO);
    #endif
}

It also has the advantage that all code is ifnot included when it is not required.

+3
source

, strdup , , strdup NULL.

, , - , , .

NULL , , NULL.

.

if (FOO) foo = strdup(FOO?FOO:"");

if (FOO) foo = strdup(FOO + !FOO);

"" ( , ), strdup NULL, if , , NULL.

, , , :

#define NON_NULL(x) ((x)?(x):"")

, :

#define NON_NULL(x) ((x)?(x):(abort(),""))

GNU ?: ( ), (x) .

#define NON_NULL(x) ((x)?:"")

, :

#define NON_NULL(x) ((x)?:(abort(),"")

- , , -, :

if (FOO) foo = strdup(NON_NULL(FOO));

, NON_NULL - .

0

All Articles