¿Por qué la redefinición de una variable global estática da un error en tiempo de compilación cuando la redefinición de una variable global no?

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

Código 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;
}

Código 2

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

preguntado el 27 de agosto de 11 a las 16:08

tried it in gcc and did not get any errors. What compiler do you use? What is the error message? -

using visual studio 2005 -

Visual c++ WINDOW -

With the G++ (GNU C++) compiler, you get redefinition errors: xx.cpp:2: error: redefinition of ‘int i’ / xx.cpp:1: error: ‘int i’ previously declared here / xx.cpp:3: error: redefinition of ‘int i’ / xx.cpp:1: error: ‘int i’ previously declared here. Maybe you need to be compiling in C mode instead of C++ mode? -

1 Respuestas

Both should compile.

Ambos int i; y static int i; son definiciones provisionales 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, constituye un definición tentativa. 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.

Respondido 27 ago 11, 20:08

Looks like MSVC gets confused about tentative declarations after the external definition is seen (I hate that "external definition" terminology, because it's too easy to confuse with "external linkage" - and it's not the same). - Michael Burr

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.