Flicks Gorger
Flicks Gorger

Reputation: 305

Declaration and Definition issue

I know this question has been asked many times,but I don't find any relevant answer. According to C

int x;       //definition

extern int x; //declaration

int  func(void); //declaration
int func(void)  //definition
{

}

My first question is if int x is definition,then why compiler shows an redeclaration error

header files
int main()
{
     int x,x;      //for this it shows redeclaration error
}

And my second question is if I am defining the var x,twice it doesn't show any error

header files
int x;
int x;
int main()
{

}

I am using window 7 and DevCpp 5.6.2

Edited :

header files
int y;
int main()
{
  int x;
}

x and y are definition here?

Upvotes: 1

Views: 69

Answers (3)

ouah
ouah

Reputation: 145919

A declaration of a variable of at file scope without an initializer (and without storage class specifier) is a tentative definition:

int i;

It is valid to have multiple tentative definitions of the same variable in the same source file:

int i;
int i;

the behavior specified by C is as if there is a declaration at the top of the source file and at the end of the source file there is a int i = 0;.

At block scope there is no tentative definition and declaring the same variable multiple times in the same block is invalid.

Upvotes: 4

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

Your first code, gets redeclaration error, because, in your case, x is having no linkage (local variable) and as per C11, chapter 6.7,

If an identifier has no linkage, there shall be no more than one declaration of the identifier (in a declarator or type specifier) with the same scope and in the same name space,....

Your second code, compiles because the redeclaration is allowed, as both the statements reside in the global scope having external linkage.

Ref:

If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

Upvotes: 1

nerez
nerez

Reputation: 447

Regarding the first question: int x is both declaration and definition, whereas extern int x is only declaration. This is why you get a redeclaration error.

Upvotes: 1

Related Questions