I am a learner and new to C language. While I was creating a function which will give power of two numbers using for loop I encounter that using int declaration before loop
In your second code snippet, the int r = r * x;
declares a new variable called r
that exists only for the duration of each iteration of the for
loop. Further, this declaration hides (or shadows) the earlier variable of the same name from the scope of that loop - so any changes made to r
in the loop do not affect the 'original' r
variable.
Enabling compiler warnings will generally reveal such problems. For example, for your second code snippet, the clang-cl compiler gives this:
warning : declaration shadows a local variable [-Wshadow]