WeAreRight
WeAreRight

Reputation: 905

Is my understanding of declaration and definition correct?

As per my understanding when you say ;

int var;          // it is a declaration because no value stored in var

But when you do ;

int var = 90;     // it is a definition because var got its value

Reason to ask this question is that I am following book and internet for programming. But, I see everywhere different meaning of definition and declaration. Please clarify , If you know better ?

Some people are saying that both are definitions , if that's the case why program below gives " redeclaration error " instead of "redifination error" in gcc.

int main(){
  int var = 100;
  int var;

  return 0;
}

Error while compiling :

enter image description here

Upvotes: 2

Views: 147

Answers (3)

Peter
Peter

Reputation: 36637

No, your understanding of declarations and definitions is incorrect.

The line

int var;

is a declaration. It may ALSO be a definition depending on context (since all definitions are declarations). For example, in;

int var;
int main()
{

}

the declaration of var is a tentative definition of a variable var that has external linkage. In the context above, it is actually a definition. However, if we modify the code to be;

int var = 42;
int var;

int main()
{

}

then int var = 42 is a definition with initialiser (of 42) and the following tentative definition int var becomes a declaration but not a definition. This is also true if the two lines int var and int var = 42 are swapped.

Even better, the meaning changes if int var is placed inside a function. For example;

int main()
{
    int var;
}

In this context, int var is a definition of a variable, var, of automatic storage duration. Placing a second definition of var in the same scope is illegal.

int main()
{
    int var;          /* definition */
    int var = 42;     /*  second definition - illegal */
}

Upvotes: 0

M.M
M.M

Reputation: 141648

Inside a function, int var; and int var = 90; are both definitions. You get a compilation error for having two definitions of var in the same scope. Note that they are also both declarations (all definitions are declarations).

The same syntax has different meaning outside of a function, which might be why you got confused.

Upvotes: 0

venky513
venky513

Reputation: 321

Weather it is declaring or defining that all depends upon where you are using it . weather it is a global variable for same program or an extern variable of other program . case 1

int var; 
main ()

The line int var; both declares and defines the variable; it effectively says, "create a variable named var, of type int. Also, the storage for the variable is that it is a global variable defined in the object file associated with this source file .

case 2

extern int var;
main()

but here it is declaring the variable but not defining it . so it all depends on where you are using this

Upvotes: 1

Related Questions