Reputation: 41
#include<stdio.h>
int x;
int main()
{
int x;
return 0;
}
Why am I not getting an error, even though I am re-declaring the variable x
with the same name?
Upvotes: 0
Views: 82
Reputation: 5221
It is allowed although not advised to define variables with the same names provided that they are not in the same scope. Inside the main()
function, the x
in the local scope has more precedence than x
in the global scope.
But it is confusing and error prone to define variables with the same names. With a compiler like gcc
, you can activate some options to track them. For example, the "-Wshadow" will warn you that x
in main()
shadows the global variable with the same name:
$ gcc try.c -Wshadow
try.c: In function ‘main’:
try.c:5:5: warning: declaration of ‘x’ shadows a global declaration [-Wshadow]
int x;
^
try.c:2:5: note: shadowed declaration is here
int x;
^
Upvotes: 3
Reputation: 173
To expand on what Some programmer dude said in the comment,
A scope is a region of the program and broadly speaking there are three places, where variables can be declared −
Inside a function or a block which is called local variables,
In the definition of function parameters which is called formal parameters.
Outside of all functions which is called global variables.
The int x above your main is a global variable which can be used by any function inside your program.
The int x inside your main is a local variable and can only be used logically inside your main.
Check out this link for more info. https://www.tutorialspoint.com/cplusplus/cpp_variable_scope.htm
Upvotes: 4