这段简单的代码行中的变量定义在哪里?

时间:2014-08-24 11:30:07

标签: c

我对此有点困惑:

#include <stdio.h>
#define MAXLINE 1000
int x;
int main()
{
    int x;

    getch();
    return 0;
}

此代码中的变量定义在哪里?我假设它将是外部变量。在这种情况下,函数中的变量不应该有一个extern修饰符吗?

如果外部变量低于主要功能怎么办?

2 个答案:

答案 0 :(得分:3)

示例1:

int x; // declares and defines global variable

int main()
{
   int x; // declares and defines *new* local variable, which hides (shadows) the global variable **in this scope**
}

示例2:

int main()
{
   extern int x; // declares variable that will refer to variable defined *somewhere*
}

int x;

示例3:

int x; // declares and defines global variable

int main()
{
   extern int x; // redundant, declares variable that will refer to variable defined *somewhere*, but it is already visible in this scope
}

答案 1 :(得分:2)

extern并不意味着在当前范围之外,它意味着具有外部链接的对象。自动变量永远不会有外部链接,因此main中的声明int x可能会引用它。因此,它隐藏了全局int x,也就是说,带有auto存储类的变量x隐藏了全局x。您需要了解有关storage classes in C的更多信息 阅读后参考以下程序:

#include <stdio.h>
int i = 6;
int main()
{
    int i = 4;
    printf("%d\n", i); /* prints 4 */
    {
        extern int i; /* this i is now "current". */
        printf("%d\n", i); /* prints 6 */
        {
            int *x = &i; /* Save the address of the "old" i,
                          * before making a new one. */
            int i = 32; /* one more i. Becomes the "current" i.*/
            printf("%d\n", i); /* prints 32 */
            printf("%d\n", *x); /* prints 6 - "old" i through a pointer.*/
        }
        /* The "previous" i goes out of scope.
         * That extern one is "current" again. */
        printf("%d\n", i); /* prints 6 again */
    }
    /* That extern i goes out of scope.
     * The only remaining i is now "current". */
    printf("%d\n", i); /* prints 4 again */
    return 0;
}