cvariable-declarationcurly-bracesprintf-debugging

Variable declaration inside curly braces


Why does the following code produce an error? I don't understand why the curly braces are making a difference.

#include<stdio.h>

int main(void)
{
    {
        int a=3;
    }

    {
        printf("%d", a); 
    }

    return 0;
}

Solution

  • The scope of a local variable is limited to the block between {}.

    In other words: outside the block containing int a=3; a is not visible.

    #include<stdio.h>
    int main()
    {
        {
          int a=3;
          // a is visible here
          printf("1: %d", a);  
        }
    
        // here a is not visible
        printf("2: %d", a);  
    
        {
         // here a is not visible either
          printf("3: %d", a); 
        }
    
        return 0;
    }
    

    Hint: google c scope variables