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,805
  • 22
  • 31
Belgi
  • 13,822
  • 22
  • 53
  • 66

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,754
  • 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
  • 67,570
  • 9
  • 102
  • 136
1

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

Alok Save
  • 196,531
  • 48
  • 417
  • 525
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
  • 15,237
  • 21
  • 68
  • 97