ashna
ashna

Reputation: 7589

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?

Upvotes: 1

Views: 344

Answers (5)

IntelliChick
IntelliChick

Reputation: 626

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.

Upvotes: 0

R Samuel Klatchko
R Samuel Klatchko

Reputation: 76541

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.

Upvotes: 11

Praveen S
Praveen S

Reputation: 10393

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

Upvotes: 0

InsertNickHere
InsertNickHere

Reputation: 3666

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

Upvotes: 0

sharptooth
sharptooth

Reputation: 170499

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

Upvotes: 1

Related Questions