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;
}
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;
}
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;}
The scope of a local variable is limited to the block between {}.
In other words: outside the block containing
int a=3;ais not visible.Hint: google c scope variables