为什么重新定义一个全局变量时不会重新定义静态全局变量给出一个编译时错误? [英] Why does redefining a static global variable give a compile-time error when redefining a global variable does not?

查看:241
本文介绍了为什么重新定义一个全局变量时不会重新定义静态全局变量给出一个编译时错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译code 1给出了一个错误我重新定义,但code 2显示没有类似的错误。为什么会这样呢?

code 1

 静态INT I; //声明变量i。
静态INT I = 25; //初始化变量。
静态INT I; //再次声明变量i。
诠释主(){
    返回0;
}

code 2

  INT I; //声明变量i。
INT I = 25; //初始化变量。
INT I; //再次声明变量i。
诠释主(){
    返回0;
}


解决方案

双方应编译。

两者 INT I; 静态INT I; 暂定定义的用C因为他们没有一个初始化,不是的extern 。你被允许多个暂定声明和至多一个非暂定定义为在翻译单元的任何物体,只要该定义不类型或联动冲突

ISO / IEC 9899:1999 6.9.2:


  

标识符的对象具有文件范围没有初始化,且无存储类说明或存储类说明符的声明静态,构成了的暂定定义的。如果翻译单元包含一个标识符的一个或多个试探性的定义,翻译单元包含该标识符的外部定义,则行为是完全一样的,如果翻译单元包含标识符的文件范围内声明,与复合类型的翻译单元的端部,具有一个初始化等于0


Compiling code 1 gives an error 'i redefined', but code 2 shows no similar error. Why is it so?

Code 1

static int i;        //Declaring the variable i.
static int i=25;     //Initializing the variable.
static int i;        //Again declaring the variable i.
int main(){       
    return 0;
}

Code 2

int i;        //Declaring the variable i.
int i=25;     //Initializing the variable.
int i;        //Again declaring the variable i.
int main(){       
    return 0;
}

解决方案

Both should compile.

Both int i; and static int i; are tentative definitions in C as they do not have an initializer and are not extern. You are allowed multiple tentative declarations and at most one non-tentative definition for any object in a translation unit so long as the definitions don't conflict in type or linkage.

ISO/IEC 9899:1999 6.9.2:

A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with a storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definitions for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initializer equal to 0.

这篇关于为什么重新定义一个全局变量时不会重新定义静态全局变量给出一个编译时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆