开发者

c variables scope

if a variable is defined in a block is it present in the block only or throughout the program? for开发者_如何学编程 example

main()
{
    int j=5;
    {
        int i=10
        printf("%d",i);
    }
    printf("%d , %d ",i,j);
}

is it valid

main()
{
    int j=5, *k;
    {
        int i=10
        printf("%d",i);
    }
     k=&i
    printf("%d , %d ",*k,j);
}

as variable remains in memory from the point of its declaration to the point wen function exits?


A non-global variable's scope is limited to the block it's defined in. Furthermore, for an automatic variable, once the block ends the variable's lifetime is over.

Consider this silly example:

void doit()
{
    int *ps;
    int *pa;

    {
        static int s = 1;
        int a = 2;

        ps = &s;
        pa = &a;
    }

    // cannot access a or s here because they are out of scope
    // *ps is okay because s is static so it's lifetime is not over
    // *pa is not okay because a's lifetime ends at the end of the block
}

Your second printf line will not compile because i is not in scope.


It's only accessible within the block, so in your example the second printf() is illegal and will not compile.


Yes its scope is then limited to the block where it is located.


The scope of i is limited within the block where it is declared. In your case it is

{ 
    int i=10 
    printf("%d",i); 
} 

Hence i is not accessible outside this scope


This question also relates to your question about local scope or an auto variable. Scope can be defined as the module within which this variable is defined.

And a module may be a function or a file.

So you can declare an auto variable in a file - which would mean it can be accessed by every function in that file, or put another way - its scope is defined to be the file in this case.

If you declare the same variable as auto, but within a function, it would mean that it can only be accessed within that function - or its scope is defined to be the function in this case.

Think of auto as 'local' within a module (where module may be a function or a file).

In the example above, you have defined the scope by adding the braces, and therefore the scope of variable i is localised to within the braces, which is why you have limited access outside the braces.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜