Variables Scope in C Language

In the C programming language, variables have different scopes that determine their visibility and lifetime within a program. Understanding variable scope is essential for writing efficient and organized code. In this tutorial, we'll explore the various types of variable scope in C, including local, global, static, automatic, and external variables.

Local Variables

Local variables are declared within a block or function and have a limited scope, accessible only within the block or function where they are defined. They are typically used for temporary storage and are destroyed when the block or function execution completes. Here's an example:

Output:

Global Variables

Global variables are declared outside of any function and have a global scope, making them accessible from any part of the program. They retain their values throughout the program's execution and are useful for storing data that needs to be shared across multiple functions. Here's an example:

Output:

Static Variables

Static variables have a local scope like local variables but maintain their values across function calls. They are declared with the static keyword and are useful when you need to preserve data between function invocations. Here's an example:

Output:

Automatic Variables

Automatic variables, also known as local variables, are the default type of variables in C. They are created and destroyed automatically as the program flows through the block or function where they are defined. Here's an example:

Output:

External Variables

External variables are declared in one source file and can be accessed by other source files in the same program. They have global scope but need to be declared using the extern keyword in other source files to avoid duplicate definitions. Here's an example:

Output:

Understanding the different variable scopes in C is crucial for writing modular and maintainable code. By choosing the appropriate type of variable and scope, you can control the accessibility and lifetime of variables in your programs, improving code organization and efficiency.