Search code examples
c++scopeglobal-variableslocal-variables

How local variable can change the value of global variable in cpp


Here, how can the operation n / 10 which is inside the inner loop, while(n>0), can change the value of n which is inside the same while loop. How the operation of local variable which is inside the inner while loop can change the value of upper level scope variable which is outside the while loop.

code I've written


Solution

  • how can the operation n / 10 which is inside the inner loop, while(n>0), can change the value of n which is inside the same while loop.

    For the same reason that digit_sum = digit_sum + last_digit; can change the value of digit_sum, even though it is declared outside of the loop, same as n.

    How the operation of local variable which is inside the inner while loop can change the value of upper level scope variable which is outside the while loop.

    Why shouldn't it be able to? n (and digit_sum) is in scope inside the loop. A variable's lifetime is the duration of the scope that it is declared in, but inner scopes also have access to it.