What is the scope of a 'while' and 'for' loop?

后端 未结 10 1660
有刺的猬
有刺的猬 2020-11-30 06:37

What is the scope of a while and for loop?

For example, if I declared an object within the loop, what is its behavior and why?

10条回答
  •  青春惊慌失措
    2020-11-30 07:09

    Check out this code

    #include < stdio.h >
    
    int i = 10;  
    int main() {  
    
    for(int i=0; i<3; i++) {  
        fprintf(stdout," for i = %d & upper i = %d\n",i,::i);
    
    }  
    
    while (i>3) {  
        int i = 30;  
        fprintf(stdout," while i = %d & upper i = %d\n",i,::i);  
        i++;  
        fprintf(stdout," while i = %d & upper i = %d\n",i,::i);  
    
    }  
    
    fprintf(stdout,"i = %d \n",i);  
    
    }
    

    In the code above, the global variable i is different from one which is controlling the for loop.

    It will print

    for i = 0 & upper i = 10
    for i = 1 & upper i = 10
    for i = 2 & upper i = 10
    

    when while loop is executed - the variable i defined inside while is having local scope, where as the variable under (i > 3) follows the global variable, and doesn't refer to local scope.

    Dipan.

提交回复
热议问题