error in c: declaration shadows a variable in the global scope

一曲冷凌霜 提交于 2020-07-10 11:08:03

问题


When I try to compile the following code I get this error message:

error: declaration shadows a variable in the global scope:

void iterator(node* root)

I don't understand where exactly I'm hiding or shadowing the global variable I've declared before.

How can I fix this?

// typedef node
typedef struct node
{
    bool is_word;
    struct node* children[27];
}
node;

node* root = NULL;

void iterator(node* root)
{
    for(int i = 0; i < 27; i++)
    {
        if (root -> children[i] != NULL)
        {
        iterator(root -> children[i]);
        }
    }
    free(root);
    return;
}

回答1:


The compiler is sloppy in its error message; “global scope” is not something defined in the C standard. What it is trying to tell you is:

node* root = NULL;

declares root as an identifier at file scope (it is visible from its declaration through the end of the translation unit [the source file being compiled]), and:

void iterator(node *root)

declares root as an identifier at block scope (it is visible from its declaration through the end of the block that defines the function).

These declarations refer to two different objects. The first one is an object with static storage duration—it exists as long as your program is executing. The second one is a function parameter—it exists only while the function is executing, and there is a separate instance of it each time your function is called.

Inside the function, root refers only to the function parameter. The former declaration is hidden and cannot be referred to by its name by any code inside the function. (That is another bit of sloppiness in the compiler error message; the C standard uses “hide,” not “shadow.”)

There is nothing wrong with this in regard to the C standard—you are allowed to hide identifiers. However, in regard to humans, it can cause problems because a person may write root in one place intended it to refer to the root in another place, because they did not see or forgot about the second declaration. This is why a compiler may have an optional warning about this. It appears you are compiling with that warning enabled, and with an option to elevate warnings into errors.

To fix it, you should either use different names for the static object and the function parameter or should turn off the compiler warning for hiding identifiers, whichever you think suits your project.



来源:https://stackoverflow.com/questions/53238366/error-in-c-declaration-shadows-a-variable-in-the-global-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!