Code-1: No warnings - No errors ... everything works fine
#include <stdio.h>
int main()
{
int r = 1;
printf("using %d\n", r);
for (int k = 1; k <= 2; k++)
{
int r = r * 2;
}
return 0;
}
Code-2: Wrong
#include <stdio.h>
int main()
{
int cnt = 1;
printf("using %d\n", cnt);
{
int cnt = cnt * 2;
}
return 0;
}
compiler response:
'cnt' is used uninitialized in this function [-Werror=uninitialized]
int cnt = cnt * 2;
So, I understand there is some difference between the loop
and block
in this case, but I am unable to figure out. Can anyone tell me how the scope of a variable
works here?