Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Ansi Memory allocation closures

Tags:

c

scope

I have this stuff:

compiled with gcc a.c -o a

// a.c
int main() {
    int a;   
    if (1) { 
        int b;
    }
    b = 2;
}   

In console I will have the follow error:

a.c:7:4: error: ‘b’ undeclared (first use in this function)
a.c:7:4: note: each undeclared identifier is reported only once for each function it appears in

All variables in C Ansi declared inside conditions will be closured to that scope?

like image 869
Ragen Dazs Avatar asked Feb 23 '26 00:02

Ragen Dazs


2 Answers

Certainly it has to throw an error.

The { and } braces are used to define a block which gives the block a new scope. And hence all the things defined or created inside a scope cannot be accessed outside that scope.

But you can access the members of the outer scope in a block if that block encloses some other blocks.

i.e

int main()
{
 int a;
 {
   int b;
    {
      int c;
      b = c;  // `b` is accessible in this innermost scope.
      a = c;  // `a` is also accessible.
    }
   // b = c;  `c` is not accessible in this scope as it is not visible to the 2nd block
   b = a;  // `a` is visible in this scope because the outermost block encloses the 2nd block.
 }
// a = b; outermost block doesn't know about the definition of `b`. 
// a = c; obviously it is not accessible.
return 0;
}

And, since {} are used in if's ,for,while,do-while and switch constructs they define a new scope for each of them when used.

This is one good mechanism in which you can limit the visibility of data members in C where the definition/declaration of variables is only allowed at the start of a block before any executable statement is encountered.

like image 92
Uchia Itachi Avatar answered Feb 25 '26 18:02

Uchia Itachi


b is local to the scope of that conditional. In order to use it, you will need to declare it before the loop. The most logical place would be right with a at the top of the function.

like image 37
phyrrus9 Avatar answered Feb 25 '26 19:02

phyrrus9