Redefinition allowed in C but not in C++?

前端 未结 3 1940
一个人的身影
一个人的身影 2020-12-01 09:20

Why does this code work in C but not in C++?

int i = 5;
int i; // but if I write int i = 5; again I get error in C also

int main(){

  // using i
}
<         


        
3条回答
  •  有刺的猬
    2020-12-01 09:52

    Tha is called tentative definition. It's allowed only in C.

    A tentative definition is any external data declaration that has no storage class specifier and no initializer. A tentative definition becomes a full definition if the end of the translation unit is reached and no definition has appeared with an initializer for the identifier. In this situation, the compiler reserves uninitialized space for the object defined.

    The following statements show normal definitions and tentative definitions.

    int i1 = 10;         /* definition, external linkage */
    static int i2 = 20;  /* definition, internal linkage */
    extern int i3 = 30;  /* definition, external linkage */
    int i4;              /* tentative definition, external linkage */
    static int i5;       /* tentative definition, internal linkage */
    
    int i1;              /* valid tentative definition */
    int i2;              /* not legal, linkage disagreement with previous */
    int i3;              /* valid tentative definition */
    int i4;              /* valid tentative definition */
    int i5;              /* not legal, linkage disagreement with previous */
    

    C++ does not support the concept of a tentative definition: an external data declaration without a storage class specifier is always a definition.

    From here: Tentative Definitions

提交回复
热议问题