在循环内重新定义变量是否有效?

huangapple go评论66阅读模式
英文:

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&lt;=end)
    {
        int mid=start+(end-start)/2;
        if(a[mid]==c)
            return mid;
        else if(a[mid]&gt;c)
            end=mid-1;
        else
            start=mid+1;
    }
    if(start&gt;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 &lt;&lt; a &lt;&lt; &#39;\n&#39;; // 1

    int a = 2;

    if (true)
    {
        int a = 3;
        std::cout &lt;&lt; a &lt;&lt; &#39;\n&#39;; // 3
    }

    std::cout &lt;&lt; a &lt;&lt; &#39;\n&#39;; // 2
}

huangapple
  • 本文由 发表于 2023年2月7日 00:40:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75364150.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定