C programming - Variable scope

Variable scope in C programming refers to the part of a program where a variable can be accessed. In other words, it defines the visibility and accessibility of a variable within a program.

There are two types of variable scope in C programming:

  1. Global scope: Variables declared outside of any function have global scope. These variables can be accessed from any part of the program, including inside functions. Global variables are visible to all the functions in a program.

Here is an example of a global variable:

refer to‮editfigi:‬a.com
int num = 10; // global variable
  1. Local scope: Variables declared inside a function have local scope. These variables can only be accessed from within the function in which they are declared. Local variables are not visible to other functions in a program.

Here is an example of a local variable:

void myFunction() {
  int num = 5; // local variable
  printf("The value of num is %d", num);
}

In this example, we declared a local variable named num inside the myFunction function. This variable is only accessible within the function, and its value cannot be accessed or modified from outside the function.

It is important to note that if a local variable has the same name as a global variable, the local variable takes precedence within the function. That means the local variable will be used instead of the global variable within the function.

Here is an example:

int num = 10; // global variable

void myFunction() {
  int num = 5; // local variable with the same name as the global variable
  printf("The value of num is %d", num); // prints the value of the local variable (5)
}

int main() {
  printf("The value of num is %d", num); // prints the value of the global variable (10)
  myFunction(); // calls the function and prints the value of the local variable (5)
  return 0;
}

In summary, variable scope in C programming defines the visibility and accessibility of a variable within a program. Global variables can be accessed from any part of the program, while local variables can only be accessed from within the function in which they are declared. If a local variable has the same name as a global variable, the local variable takes precedence within the function.