【发布时间】:2020-04-04 23:00:51
【问题描述】:
所以我有这个功能,它做什么并不重要,重要的是我使用 cppcheck 来检查错误,我得到这个消息:
消息:
(style) The scope of the variable 'i' can be reduced. Warning: Be careful when fixing this message, especially when there are inner loops. Here is an example where cppcheck will write that the scope for 'i' can be reduced:
void f(int x)
{
int i = 0;
if (x) {
// it's safe to move 'int i = 0;' here
for (int n = 0; n < 10; ++n) {
// it is possible but not safe to move 'int i = 0;' here
do_something(&i);
}
}
}
When you see this message it is always safe to reduce the variable scope 1 level.
功能:
void p(int idp, int price)
{
int i = 0;
if ((indentify_prod(sistem,idp) == 1) && (price > 0)) /* product exists in the sistem*/
{
sistem[idp].price = price;
while (i <500)
{
if (sistem[idp].ident == sistem_orders[i].set_prod[idp].ident)
{
if ((product_in_order(i,sistem_orders,idp) == 1) && (product_in_system(idp) == 1)){
sistem_orders[i].set_prod[idp].price = price;
}
}
i++;
}
}
else
{
printf("Impossivel alterar preco do produto %d. Produto inexistente.\n",idp);
}
}
我真的不明白这个警告就像缩小范围是什么意思?我尝试将 500 的值减少到 200,但它仍然给出相同的错误,我不明白为什么。
如果有任何帮助,我们将不胜感激。
【问题讨论】:
-
只是表示可以将i的减速移动到if语句的范围内
-
“作用域”一词是指变量的声明位置并且可以有效使用。正如其他人所说,您可以在“if”语句中移动变量“i”的声明,以便它仅在“if”块内有效,但在之后无效。通常认为将变量的范围仅设置为必要的大是好的。这有助于编译器了解如何优化程序,并帮助代码维护人员了解您打算如何使用该变量。