Search code examples
cif-statementc-stringsfunction-definitionnull-pointer

C - checking if strings contain any non-null characters


I have a function with two strings parameters. I have to check if both strings contains any non-null characters. Here is an example code:

void fun(const char* str1, const char* str2)
{
    if (!str1 || !str1[0] || !str2 || !str2[0])
    {
        return;
    }

    // process
}

Is that a standard approach in C or you recommend other solution ?


Solution

  • It is enough to write the condition like

    if ( !str1[0] || !str2[0] )
    

    that is when the function follows the convention of C Standard string functions when passing a null-pointer invokes undefined behavior.

    It is the caller of the function that shall guarantee that the passed pointers are not null pointers.