简体   繁体   English

强制函数返回 NULL 而不是预先确定的 return_type

[英]Forcing a function to return NULL instead of it's predetermined return_type

Below is a command parsing function.下面是一个命令解析函数。 It splits user input at the "-" .它在"-"处拆分用户输入。

If "time-10" is passed in, 10 is returned.如果传入“time-10” ,则返回10 If no "-" is found I want to return NULL so I know that no "-" was found and the program can make decisions passed on that information.如果没有找到“-” ,我想返回NULL,这样我就知道没有找到“-” ,程序可以根据该信息做出决定。 However, because the function return type is char I have to return a char pointer, and am currently satisfying this requirement by returning the original argument.但是,因为函数返回类型是char我必须返回一个char 指针,并且目前通过返回原始参数来满足这个要求。

Is there a way around this, or do I HAVE to return a Char pointer and write code that determines if that return value equates to, 'no - found' ?有没有办法解决这个问题,或者我是否必须返回一个 Char 指针并编写代码来确定该返回值是否等于“未找到”

char * second_arg(char * arg) {  
    char * j = strchr(arg, '-');
    if(j==NULL) {
        return arg;
    }
    return ++j;
}

The function return type is not char ;函数返回类型不是char it is char * .它是char * Since the function already returns a pointer to char , it is very easy to return NULL.由于该函数已经返回一个指向char的指针,因此很容易返回 NULL。

Just change the line return arg;只需更改行return arg; to say return NULL;return NULL;

Tim Randall posted the right answer.蒂姆·兰德尔 (Tim Randall) 发布了正确答案。 A little code-golf oriented solution could also be:一个面向代码高尔夫的小解决方案也可以是:

char * second_arg(char * arg) {  
    char * j = strchr(arg, '-');
    return j?++j:j;
}

If j is NULL , it's also false in C. ++j increments the variable before the evaluation of the line (I suggest to add comments to this code :)).如果 j 是NULL ,它在 C 中也是false的。 ++j在评估该行之前增加变量(我建议为此代码添加注释:))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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