What exactly is the difference between blocks and loops?

Viewed 92

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?

1 Answers

They both have exactly the same problem i.e. r and cnt are self-initialized in respective programs.

This is potentially undefined because of use of uninitialized variables (which has indeterminate value) if they happen to have trap representation.

gcc happens to detect it one case and doesn't in the other case. gcc has -Wuninitialized -Winit-self options but it still doesn't detect the first case even with these options. Regardless, the issue remains (and the same) in both.

Related