4

Does C have scope hiding?

For example, if I have a global variable:

int x = 3; 

can I 'declare' inside a function or main 'another' int x?

Brissles
  • 3,833
  • 23
  • 31
Belgi
  • 14,542
  • 22
  • 58
  • 68

4 Answers4

5

Yes, that's how C works. For example:

int x;

void my_function(int x){ // this is another x, not the same one
}

void my_function2(){
  int x; //this is also another x
  {
    int x; // this is yet another x
  }
}
int main(){
  char x[5]; // another x, with a different type
}
Adiel Mittmann
  • 1,764
  • 9
  • 12
  • What if in the main it was not int as well (different type), for example char array[5] x ? – Belgi Jan 19 '12 at 15:32
  • in such cases, the type doesn't matter. if you declare `x` as an `int` and then you shadow that declaration by saying that you have a new `x` of type `char[5]`, you will only see the latter `char x[5]`. – Adiel Mittmann Jan 19 '12 at 15:37
3

Yes but some compilers complain or can be told to complain. For gcc, use -Wshadow.

lhf
  • 70,581
  • 9
  • 108
  • 149
1

Yes Scope Hiding exists in C.
A variable in local scope will hide the same named variable in global scope.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

Yes. This is very much possible. Please go through this post for a detailed explanation on various scope in C

Community
  • 1
  • 1
Sangeeth Saravanaraj
  • 16,027
  • 21
  • 69
  • 98