我应该写回报;在一个空洞返回功能? [重复]

时间:2022-09-10 23:52:01

This question already has an answer here:

这个问题在这里已有答案:

Say I have a void-returning function,

假设我有一个返回空值的函数,

void foo(void)
{
    // code
}

or

要么

void foo(void)
{
    // code
    return;
}

I wonder which one is better in practice? Are there any potential problems in the first one?

我想知道哪一个在实践中更好?第一个是否有任何潜在的问题?

2 个解决方案

#1


1  

Both cases are completely equivalent.

In the second example return; is completely redundant and I see no reason to use it.

在第二个例子中返回;是完全多余的,我认为没有理由使用它。

#2


1  

In your cases above, it is not necessary to write the return since both are equivalent.

在上面的例子中,没有必要写回报,因为两者都是等价的。

There are cases, however, where you want to write return because your function paths are branched and you want to have early return in one or more branches (but not all branches) for good reasons (such as simplification or readibility)

但是,有些情况下,您希望编写返回值,因为您的函数路径是分支的,并且您希望在一个或多个分支(但不是所有分支)中提前返回,原因很充分(例如简化或可读性)

For example, consider the following case:

例如,请考虑以下情况:

void foo(){
    if (a){
        //do something
    } else {
        //do something else
    }
}

The function paths are branched and suppose you want to reduce the indentation of your code by removing else block. Then you could write the code above with early return as follow:

函数路径是分支的,并且假设您希望通过删除else块来减少代码的缩进。然后你可以在早期返回时编写上面的代码,如下所示:

void foo(){
    if (a){
        //do something
        return;
    }
    //do something else    
}

In such case, you may consider of using early return in a void-returning function.

在这种情况下,您可以考虑在void返回函数中使用提前返回。

#1


1  

Both cases are completely equivalent.

In the second example return; is completely redundant and I see no reason to use it.

在第二个例子中返回;是完全多余的,我认为没有理由使用它。

#2


1  

In your cases above, it is not necessary to write the return since both are equivalent.

在上面的例子中,没有必要写回报,因为两者都是等价的。

There are cases, however, where you want to write return because your function paths are branched and you want to have early return in one or more branches (but not all branches) for good reasons (such as simplification or readibility)

但是,有些情况下,您希望编写返回值,因为您的函数路径是分支的,并且您希望在一个或多个分支(但不是所有分支)中提前返回,原因很充分(例如简化或可读性)

For example, consider the following case:

例如,请考虑以下情况:

void foo(){
    if (a){
        //do something
    } else {
        //do something else
    }
}

The function paths are branched and suppose you want to reduce the indentation of your code by removing else block. Then you could write the code above with early return as follow:

函数路径是分支的,并且假设您希望通过删除else块来减少代码的缩进。然后你可以在早期返回时编写上面的代码,如下所示:

void foo(){
    if (a){
        //do something
        return;
    }
    //do something else    
}

In such case, you may consider of using early return in a void-returning function.

在这种情况下,您可以考虑在void返回函数中使用提前返回。