-4

What if we define a global variable int x; and inside the body of a function define another variable int x;.

Inside the function 'x' would always refer to the local variable 'x'. Now if the user must refer to the global variable x inside the very function how does one achieve that?

jwpfox
  • 5,124
  • 11
  • 45
  • 42

1 Answers1

2

Since your question is tagged "C", I'll answer about that language. Other languages may provide syntactic sugar or mechanisms to do what you want.

Defining a variable using the name of a variable existing in a greater scope is called shadowing: the inner definition shadows the outer one.

Below is an example:

int x = 42;

int main() {
    int x = 0; // Here, `x` shadows the global `x`.
    printf("%d\n", x); // Prints '0'
}

In C, there is no way to get the value of the shadowed variable.

On the style plan, shadowing is often considered a bad practice since it makes your code less legible and harder to refactor.

Richard-Degenne
  • 2,892
  • 2
  • 26
  • 43