这是在C或Perl中终止for循环的合适方法吗?

Kin*_*Jnr 2 c perl coding-style

我在代码库中看到了一段类似的perl代码,想知道这个(设置i=100)是否是一个摆脱for循环的好方法?这有什么陷阱吗?

int a[100];

...

bool check_if_array_contains_29()
{
    bool result = false;
    for(int i=0; i<100; ++i)
    {
        if(a[i] == 29)
        {
            result = true;
            i = 101;
        }
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

这更像我会做的事情.

bool check_if_array_contains_29()
{
    bool result = false;
    for(int i=0; i<100 && !result; ++i)
    {
        if(a[i] == 29)
        {
            result = true;
        }
    }
    return result;
}
Run Code Online (Sandbox Code Playgroud)

编辑-1:

我不是在寻找perl中的oneliner来实现功能.真正的代码(功能)要复杂得多.这只是我简化的一个例子来解释我的观点(提前终止for循环).

pst*_*jds 9

你为什么不这样做:

bool check_if_array_contains_29()
{
    for(int i=0; i < 100; ++i)
    {
         if (a[i] == 29)
           return true;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

编辑:
我知道有些人觉得多个return语句都很糟糕,应该不惜一切代价避免,但对我来说,在一个方法中多次返回会使代码更易于阅读和遵循.

编辑2:
其他版本,以便如果方法需要有一些副作用或执行一些额外的操作,您可以使用break语句,或者您可以调整for循环条件,或者您可以添加一些标签和一些gotos.

bool check_if_array_contains_29_take2()
{
    bool result = false;
    for (int i=0; i < 100; ++i)
    {
        if (a[i] == 29)
        {
            result = true;
            break;
        }
    }

    // Do Other Stuff
    return result;
}

bool check_if_array_contains_29_take3()
{
    bool result = false;
    for (int i=0; !result && i < 100; ++i)
    {
        result = a[i] == 29;
    }

    // Do Other Stuff
    return result;
}

// Special edition for those who can't get enough goto
bool check_if_array_contains_29_and_do_more_stuff_without_early_return()
{
    bool result = false;
    for (int i=0; i < 100; ++i)
    {
        if (a[i] == 29)
        {
            result = true;
            break;
        }
    }

    if (!result)
        goto error;

    // Do some other stuff in the code here
    goto done;

done:
    return result;
error:
    result = false;
    goto done;
}
Run Code Online (Sandbox Code Playgroud)

  • LLVM项目的编码标准特别建议早期返回,因为在长时间的功能中,它清楚地表明不会再发生处理,而不是强迫读者继续扫描以查看是否会发生.他们对为什么早期回报实际上是一种更清洁的方法有一个非常好的写作.我知道这个问题是针对"C"语言发布的,但在C++中,使用auto_ptr或类似方法可以解决早期返回的资源释放陷阱问题. (2认同)