P. 1
How Are Variables Scoped in C

How Are Variables Scoped in C

|Views: 1|Likes:
Published by Vijay Gp
cxxcv
cxxcv

More info:

Published by: Vijay Gp on Mar 31, 2013
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as DOC, PDF, TXT or read online from Scribd
See more
See less

03/31/2013

pdf

text

original

How are variables scoped in C – Static or Dynamic? May 17, 2010 In C, variables are always statically (or lexically) scoped i.e.

, binding of a variable can be determined by program text and is independent of the run-time function call stack. For example, output for the below program is 0, i.e., the value returned by f() is not dependent on who is calling it. f() always returns the value of global variable x. int x = 0; int f() { return x; } int g() { int x = 1; return f(); } int main() { printf("%d", g()); printf("\n"); getchar(); } ====================================== What is return type of getchar(), fgetc() and getc() ? February 25, 2010 In C, return type of getchar(), fgetc() and getc() is int (not char). So it is recommended to assign the returned values of these functions to an integer type variable. char ch; /* May cause problems */ while ((ch = getchar()) != EOF) { putchar(ch); } Here is a version that uses integer to compare the value of getchar(). int in; while ((in = getchar()) != EOF) { putchar(in); } ======================================================= ============================= Scope rules in C

y++.c // When this file is linked with file1. y = %d\n". functions of this file can access a extern int a. x. } To restrict access to current file only. { // y is declared again. Blocks may be nested in C (a block may contain other blocks inside it). x. y). } // Changes the outer block variable x to 11 // Changes this block's variable y to 41 printf("x = %d. { // The outer block contains declaration of x and y. then the visibility of the outer block variable ends at the pint of declaration by inner block. int main(void) { a = 2. global variables can be marked as static.c int a. . so outer block y is not accessible // in this block int y = 40.c. // This statement accesses only outer block's variables printf("x = %d. What if the inner block itself has one variable with the same name? If an inner block declares a variable with the same name as the variable declared by the outer block. all identifiers are lexically (or statically) scoped. In C. y). int myfun() { a = 2. A variable declared in a block is accessible in the block and all inner blocks of that block. // filename: file1. } // filename: file2. but not accessible outside the block.December 30. y = 20. } } return 0. Global Scope: Can be accessed anywhere in a program. y = %d\n". y = %d\n". so // following statement is valid and prints 10 and 20 printf("x = %d. int main() { { int x = 10. Block Scope: A Block is a set of statements enclosed within left and right braces ({ and } respectively). x. 2011 Scope of an identifier is the part of the program where the identifier may directly be accessible. y). C scope rules can be covered under following two categories. x++.

Can variables of block be accessed in another subsequent block?* No. y = 20 x = 11. ================================================== // Error: x is not accessible here . y = %d. x. } return 0. x. } { printf("%d". z).} Output: x = 10. or you want to share more information about the topic discussed above. y = 2. printf(" x = %d. printf(" x = %d. z = 3. y. z = %d \n". int main() { { int x = 10. { int z = 100. x). printf(" x = %d. } } return 0. predict the output of following program. z). y = %f. float y = 20. a variabled declared in a block can only be accessed inside the block and all inner blocks of this block. { int x = 10. For example. y = %f. Parameters and other local variables of a function follow the same block scope rules. y = 20 What about functions and parameters passed to functions? A function itself is a block. z = %d \n". } Output: error: 'x' undeclared (first use in this function) As an exercise. } Please write comments if you find anything incorrect. z = %d \n". y = 41 x = 11. int main() { int x = 1. y. z). following program produces compiler error. y. x.

There’s an extern present in the beginning which is hidden and the compiler treats it as below. (or declaration as a subset of definition). And as the extern extends the visibility to the whole program. So let me ask the question. char arg2). the order of arguments and the return type of the function. Though (almost) everyone knows the meaning of declaration and definition of a variable/function yet for the sake of completeness of this post. In case of function declaration. By default. But we notice the actual definition of the function only once (i. Now let us the take the second and final case i. int foo(int arg1. . their data types. when we write.e. how would you declare a C variable without defining it? Many of you would see it trivial but it’s important question to understand extern with C variables. It means even though we don’t use extern with the declaration/definition of C functions. (Remember the basic principle that you can’t have two locations of the same variable/function). Let us first take the easy case. apart from the role of declaration. Coming to the definition. From this explanation. So that’s all about extern with C functions. char arg2). we can notice that declaration of a function can be added in several C/H files or in a single C/H file several times. when we define a variable/function.e. an extern is present there in the beginning of the function definition. in one file only). I’ve explained the role of declaration/definition because it’s mandatory to understand them to understand the “extern” keyword. I feel that it more interesting and information than the previous case where extern is present by default with C functions. Therefore whenever we define a C function. So that’s all about declaration. the declaration and definition of a C function have “extern” prepended with them. the program knows what are the arguments to that functions. it should be obvious that a variable/function can be declared any number of times but it can be defined only once. So let me start with saying that extern keyword applies to C variables (data objects) and C functions. Use of extern with C functions. The answer goes as follows. it also allocates memory for that variable/function. I would like to clarify them. Now coming back to our main objective: Understanding “extern” keyword in C. Therefore.e. Declaration of a variable/function simply declares that the variable/function exists somewhere in the program but the memory is not allocated for them. the functions can be used (called) anywhere in any of the files of the whole program provided the declaration of the function is known. when a variable is declared. the program knows the data type of that variable. 2009 I’m sure that this post will be as interesting and informative to C virgins (i. it is present there. we can think of definition as a super set of declaration. And that is the type of the variable/function. Same is the case with the definition of a C function (Definition of a C function means writing the body of the function). Since the declaration can be done any number of times and definition can be done only once. extern int var. extern int foo(int arg1. For example. Probably that’s is the reason why it was named as extern. So that’s all about declaration and definition. use of extern with C variables.Understanding “extern” keyword in C July 19. C compiler knows that the definition of the function exists and it goes ahead to compile the program). beginners) as it will be to those who are well versed in C. (By knowing the declaration of the function. Therefore. Basically extern keyword extends the visibility of the C variables and C functions. But the declaration of a variable/function serves an important role.

Example 1: int var. Here var is declared only. Here var is defined (and declared implicitly) globally. (remember that declaration can be done any number of times) So far so good. we saw that an extern was present by default. Here the memory for var is also allocated. While defining a function. int main(void) { var = 10. Therefore. Here. int main(void) { return 0. And the program is trying to change the value to 10 of a variable that doesn’t exist at all. Now let us try to understand extern with examples. return 0. as the extern extends the visibility to the whole program. the var isn’t allocated any memory. (remember that definition is the super set of declaration). } Analysis: This program is compiled successfully. int var. when we declared/defined a C function. Essentially. an integer type variable called var has been declared (remember no definition i. } Analysis: This program throws error in compilation. an integer type variable called var has been declared as well as defined. Now here comes the surprise. return 0. by externing a variable we can use the variables anywhere in the program provided we know the declaration of them and the variable is defined somewhere. Also. Notice var is never used so no problems. But it is not the case with C variables.Here. . Example 3: extern int var. we put extern explicitly for C variables when we want to declare them without defining them. Now I agree that it is the most trivial question in programming and the answer is as follows. And we can do this declaration as many times as needed. If we put the presence of extern in variable as default then the memory for them will not be allocated ever. Because var is declared but not defined anywhere. int main(void) { var = 10. Example 2: extern int var. no memory allocation for var so far). they will be declared only. we can prepend it with extern without any issues.e. Now how would you define a variable. } Analysis: This program is compiled successfully.

Example 5: extern int var = 0. Declaration can be done any number of times but definition only once. 2010 In C. when an extern variable is declared with initialization. } Analysis: Supposing that somefile. it’s only declared not defined.h has the definition of var. then the memory for that variable will be allocated i. it is taken as definition of the variable as well. it is initialized to a NULL pointer. As an exception.h" extern int var. Therefore. it is initialized to (positive or unsigned) zero. This program will be compiled successfully. — if it is an aggregate. So that was a preliminary look at “extern” keyword in C. here comes another surprise from C standards. — if it is a union. 4.e. as per the C standard. And I would not disappoint you. They say that. I’m sure that you want to have some take away from the reading of this post. When extern is used with a variable. “extern” keyword is used to extend the visibility of variables/functions(). . In short. the first named member is initialized (recursively) according to these rules. The use of extern is not needed in function declaration/definition.Example 4: #include "somefile.. we can say 1. that variable will be considered as defined. — if it has arithmetic type. return 0. ======================================================= =============== What are the default values of static variables in C? November 10. Since functions are visible through out the program by default. if an object that has static storage duration is not initialized explicitly. 5. int main(void) { var = 10. Its use is redundant. 2. int main(void) { var = 10. return 0.if a variable is only declared and an initializer is also provided with that declaration. this program will compile successfully and work. then: — if it has pointer type. 3. every member is initialized (recursively) according to these rules. } Analysis: Guess this program will work? Well.

following program prints: Value of g = 0 Value of sg = 0 Value of s = 0 #include<stdio. or you want to share more information about the topic discussed above. printf("\nValue of s = %d". global static objects have static storage duration int main() { static int s. //g = 0. static objects have static storage duration printf("Value of g = %d". s). } Please write comments if you find anything incorrect. //gs = 0. gs). return 0.h> int g. global objects have static storage duration static int gs. getchar().For example. printf("\nValue of gs = %d". g). . //s = 0.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->