My Compiler(gcc) is showing the warning
warning: declaration of \'index\' shadows a global declaration
Please help me understand
It's when you do something like:
int index;
int main (void) {
int index;
....
return 0;
}
What it's warning about is that the index
inside main()
is actually hiding the global one you've declared before main()
.
It's warning you that you can't get at the global definition while the local one is "active". Now that's not necessarily a problem (hence why it's only a warning), it's perfectly valid C, but you need to be aware of the possible consequences.
As an aside, some C implementations (BSD-based) define an
index
function instring.h
which may also cause a problem. Use of this function is deprecated and it doesn't appear in the C standard (usestrchr
instead) but it may be the cause of problems if you're running on (for example) Mac OS or OpenBSD (or even Linux under some combination of#define
settings, I believe).
There are a couple of ways to get around this (if you need to).
The first is probably the preferred one: don't use globals. Yes, that's right, get rid of them. They're very rarely needed so don't make me come over and slap you around :-)
A second way I've seen is to ensure they're "packaged". Assuming that you actually need globals (by no means a certainty, see previous paragraph), create a structure that holds them, such as in the following:
myglobs.h:
struct sMyGlobs {
int index;
// all other globals.
};
extern struct sMyGlobs myGlobs;
myglobs.c:
#include "myglobs.h"
struct sMyGlobs myGlobs;
main.c:
#include <stdio.h>
#include "myglobs.h"
int main (void) {
myGlobs.index = 42;
return 0;
}
This has the advantage in that it's obvious that you're referring to a global and that they're never hidden, unless you do something like define your own local variable called myGlobs
.