警告:(343) 隐式 return 在非空函数的末尾

warning: (343) implicit return at end of non-void function

当函数返回指针标记时,我收到以上警告。以下代码不完整,请缩短以避免混淆。

  char *ServerResponds()        
    {
        char copy_wifi_data[EUSART_BUFFER_SIZE];                               
        uint16_t i = 0; int tok_count = 0;            

        static char *token;
        token = strtok(copy_wifi_data, ":");               //Converting wifi data to tokens.

        while(token != NULL)
        {  
            if(tok_count == 1)
            {
                return token;
            }

            token = strtok(NULL,":");  
            tok_count++;
        } 
    }

出现警告是因为在 tok_count == 1 为假的情况下没有 return 语句。

char *ServerResponds()        
{
    char copy_wifi_data[EUSART_BUFFER_SIZE];                               
    uint16_t i = 0; int tok_count = 0;            

    static char *token;
    token = strtok(copy_wifi_data, ":");               

    while(token != NULL)
    {  
        if(tok_count == 1)
        {
            return token;
        }

        token = strtok(NULL,":");  
        tok_count++;
    } 
    /* <--- there is no return if control flow reaches this point */

}

您可以在函数末尾添加一个 return 0; 来解决这个问题,但您必须记录此行为并确保调用者准备好处理空 return 值.

该函数不会通过所有可能的执行路径return一个值。

虽然您可以在 while 循环之后添加 return NULLreturn token,但从单个函数中获取多个 return 点可能被认为是不好的做法 - 这与许多常见的编码标准,在大多数情况下都是不明智的。

    //Converting wifi data to tokens.
    static char *token  = strtok(copy_wifi_data, ":");               
    while( tok_count == 0; token != NULL )
    {  
        token = strtok(NULL,":");  
        tok_count++;
    }

    return token ; 

也就是说,不清楚 while 循环的目的是什么,或者为什么 tokenstatic。它在语义上等同于:

    //Converting wifi data to tokens.
    char *token = strtok(copy_wifi_data, ":");               
    if( token != NULL )
    {  
        token = strtok(NULL,":");  
    }

    return token ;