Home  >  Q&A  >  body text

C++循环的重复定义问题


第六行的int i = 0;在每轮循环均会执行,为什么能编译成功而不是提示重复定义?

天蓬老师天蓬老师2764 days ago520

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 14:40:55

    C++ variable scope problem

    #include <iostream>
    
    using namespace std;
    int main(int argc, char *argv[]) {
        int a = 3;
        int i = 3;
        {
            int i = 1;
        }
        cout << i << endl; // 3
    }

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 14:40:55

    Similar to the concept of global variables and local variables.

    A variable only works in the middle of "{}". Once the curly brackets are released, the variable will be automatically deleted.

    reply
    0
  • 黄舟

    黄舟2017-04-17 14:40:55

    The compiler is not that "dumb" and will know that you mean to use a variable that is initialized to 0 in the loop. The above a is different. The compiler can't figure out why you defined a twice. It is probably a wrong input, so an error will be reported.

    reply
    0
  • Cancelreply