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;
}
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
a
” is not true. First, we should be precise: A variable is an object (a region of storage) and an identifier (a name for it). An identifier declared inside a block has block scope. The identifier is not visible outside the block, but the object may exist when execution is outside the block, as when a subroutine is called, so execution goes somewhere else but the block is not finished executing. It is not necessary to explain all details for an elementary question, but the statements that are written should be correct ones.
Commented
Oct 29, 2018 at 15:53
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;}
You cannot access the variable outside the nearest pair of opening and closing curly braces else it will give compile time error