Saturday, 10 August 2013

Scope Rules in C

Welcome to Wind Trainers :: Trainers, C, Tutorials, Programming, Java, VB.net, C++, ANSI, Learn C, Learn Programming
Forum | Contact

C Tutorials


| Scope Rules |


A scope in any programming is a region of the program where a defined variable can have its existence and beyond that variable can not be accessed. There are three places where variables can be declared in C programming language:

1. Inside a function or a block which is called local variables.
2. Outside of all functions which is called global variables.
3. In the definition of function parameters which is called formal parameters.

| Local Variables |

Variables that are declared inside a function or block are called local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own. Following is the example using local variables. Here all the variables a, b and c are local to main() function.

#include <stdio.h>
void main ()
{
/* local variable declaration */
int a, b;
int c;
a = 10;
b = 20;
c = a + b;
printf ("\nvalue of c = %d",c);
}

| Global Variables |

Global variables are defined outside of a function, usually on top of the program. The global variables will hold their value throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.

A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration. Following is the example using global and local variables:

#include <stdio.h>
/* global variable declaration */
int c;
void main ()
{
/* local variable declaration */
int a, b;
a = 10;
b = 20;
c = a + b;
printf ("\nvalue of c = %d",c);
}

| Formal Parameters |


A function parameters, formal parameters, are treated as local variables with-in that function and they will take preference over the global variables.

#include <stdio.h>
/* global variable declaration */
int a = 20;
int main ()
{
/* local variable declaration in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("\nValue of a in main() = %d", a);
c = sum( a, b);
printf ("\nValue of c in main() = %d", c);
return 0;
}
int sum(int a, int b)
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}

No comments:

Post a Comment