Why the output is different when we add 'int' tag twice in a program when using 'for' loop?

前端 未结 4 843
滥情空心
滥情空心 2021-01-15 12:26

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

4条回答
  •  無奈伤痛
    2021-01-15 12:46

    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]

提交回复
热议问题