'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 1:[1]
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
Solution 2:[2]
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;}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | rici |
Solution 2 |