My Compiler(gcc) is showing the warning
warning: declaration of ‘index’ shadows a global declaration
Please help me understand why this warning comes.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s when you do something like:
What it’s warning about is that the
indexinsidemain()is actually hiding the global one you’ve declared beforemain().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.
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:
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.