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循环).
你为什么不这样做:
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)