Variable declaration inside curly braces

1.7k Views Asked by At

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;
}
3

There are 3 best solutions below

2
Jabberwocky On BEST ANSWER

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

3
gigis95 On

Variables that are defined inside curly braces exist only while the program is running within the braces. When the program exits the '}' then like in your case these variables are destroyed and the memory that used to be occupied is returned to the system.

If you are in need of this implementation what you can alter it so that the definition will be outside of the curly braces. For example :

   c/c++

   #include <stdio.h>
   
   int main(){

    int a;

    {a = 3;}

    {printf("%d",a) ;}
    
    return 0;}
0
Aditya Raj On

You cannot access the variable outside the nearest pair of opening and closing curly braces else it will give compile time error