英文:
Is redefinition of a variable valid inside loops?
问题
在以下的binarySearch程序中,mid变量在循环中被初始化,只有当条件start<=end为真时才会执行。
我是编程新手,我学到在C中重新定义变量是无效的。但我遇到了binarySearch程序,其中循环将在start<=end为真时执行,并且会一遍又一遍地初始化一个名为mid的int变量,直到条件为真,因此将发生重新定义。我想知道*“循环内的重新定义是否有效?”*或者我是否漏掉了什么。
英文:
I have encountered the following binarySearch program
int binarySearch(int a[],int b, int c)
{
int start=0,end=b-1;
while(start<=end)
{
int mid=start+(end-start)/2;
if(a[mid]==c)
return mid;
else if(a[mid]>c)
end=mid-1;
else
start=mid+1;
}
if(start>end)
return -1;
}
in which mid variable is initialized in the loop which will be executed if the condition start<=end becomes true.
I am new to programming and i have learnt that redefinition of variable is not valid in C. But i have encountered binarySearch program in which loop will be executed when start<=end will be true and will be initializing an int variable named mid again and again till the condition will be true and thus redefinition will take place. I want to know "are redefinition valid inside loops?" or something else i am missing.
答案1
得分: 4
一个变量本身是一个编译时的概念,它是源代码中的一个标签,一个指向在运行时将存在的实际对象的名称。
由于int mid
在您的代码中只出现一次,所以没有重新定义。即使它被多次拼写,如果这些变量在不同的地方,那么这是合法的(这些变量将会相互遮盖):
int a = 1;
int main()
{
std::cout << a << '\n'; // 1
int a = 2;
if (true)
{
int a = 3;
std::cout << a << '\n'; // 3
}
std::cout << a << '\n'; // 2
}
英文:
A variable itself is a compile-time concept, it's a label in the source code, a name which refers to an actual object that will exist at runtime.
Since int mid
is only spelled once in your code, there's no redefinition. Even if it was spelled multiple times, if the variables are in different places, it can be legal (the variables will shadow one another):
int a = 1;
int main()
{
std::cout << a << '\n'; // 1
int a = 2;
if (true)
{
int a = 3;
std::cout << a << '\n'; // 3
}
std::cout << a << '\n'; // 2
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论