Hello All I have some confusion in Declaration and defination of variables.
Declaration means ===> where the variables are declared and no memory is allocated.

Defination means ===> where the variable is declared and defination is allocated.

For eg. if we write
(1)
int a;
printf("%d",a);
then it will print some garbage value.

(2)
int a=10;
printf("%d",a);
then it will print 10.

It looks like (1) is declaration (BUT IT IS NOT AS MEMORY IS ALLOCATED) of variables and (2) is declaration with defination.

Now where is the declaration in the above case?

Declaration means ===> where the variables are declared and no memory is allocated.

From the view of variables only, that's reasonable. An object declaration states the type and name of the object, but does not necessarily cause storage to be allocated for it. A declaration is more of a statement of intention. int foo; means "I'm calling this object foo and it will be used as a signed integer".

Defination means ===> where the variable is declared and defination is allocated.

A definition is a declaration that also allocates storage and potentially initializes said storage.

Now where is the declaration in the above case?

They're both definitions, which means they're both also declarations. I know it can get confusing because a definition can look exactly like a declaration with the only difference being that the compiler chose to allocate storage. Here's a fun example:

#include <stdio.h>

int foo; // Declaration or definition?
int foo; // Declaration or definition?
int foo; // Declaration or definition?

int main(void)
{
    foo = 12345;
    printf("%d\n", foo);

    return 0;
}

All three foo declarations look like declarations, but one of them is a definition.

These are all definitions. A declaration would be an extern, such as

#include <stdio.h>

/* Declaration of foo being an integer */
extern int foo;

/* Definition of bar as an integer. It is still a definition
 * even if it hasn't been initialized.
 */
int bar;

int main(void)
{
   bar = foo; /* initialize bar with value contained by external variable foo */
   printf("%d\n", bar);
   return 0;
}

Notice that I did NOT initialize the variable bar before entering main. Until you get into main(), there is no way to know if other external variables have been properly initialized as yet. Caveat programmer!

> These are all definitions.

Let's get legal. They are tentative definitions (6.9.2:2). All of them result in the behavior "exactly as if the translation unit contains a file scope declaration ... with an initializer equal to 0". That is, only one definition.

> All three foo declarations look like declarations, but one of them is a definition.

Funniest thing is, we don't know which one.

Edited 5 Years Ago by nezachem: n/a

This article has been dead for over six months. Start a new discussion instead.