C declaration Vs Definition



Some Examples of Declaration :

Declaration of Function :

Whenever we write function after the main function, compiler will through the error since it does not have any idea about the function at the time of calling function. If we provide prototype declaration of function then we compiler will not look for the definition.

int sum(int,int);

main()
{
int res = sum(10,20);
}

int sum(int n1,int n2)
{
return(n1+n2);
}

In the above example , first line is called as function declaration.

int sum(int,int);

Declaring Variable

Whenever we write declaration statement then memory will not be allocated for the variable. Variable declaration will randomly specify the memory location.

int ivar;
float fvar;

Variable Declaration Vs Definition Differentiation Parameters

A. Space Reservation :

  1. Whenever we declare a variable then space will not be reserved for the variable.
  2. Whenever we declare a variable then compiler will not look for other details such as definition of the variable.
  3. Declaration is handy way to write code in which actual memory is not allocated.
struct book  {
    int pages;
    float price;
    char *bname;
};

In the above declaration memory is not allocated. Whenever we define a variable then memory will be allocated for the variable.

struct book b1;

B. What it does ?

  1. Declaration will identify the data type of the identifier.
  2. Definition of the variable will assign some value to it.

C. Re-Declaration Vs Re-Definition

In Both the cases we will get compile error. Re-declaration and Re-definition is illegal in C programming language.

Re-Declaring the Variable in Same Scope :

main()
{
int num1;
int num1;
}

&

struct book  {
    int pages;
    float price;
    char *bname;
};

struct book  {
    int pages;
    float price;
    char *bname;
};

above statement will cause error.

Re-Defining the Variable :

int sum(int n1,int n2)
{
return(n1+n2);
}

int sum(int n1,int n2)
{
return(n1+n2);
}

above definition will cause compile error.

Difference between Declaration and Definition

NoDeclarationDefinition
1Space is Not ReservedIn Definition Space is Reserved
2Identifies Data TypeSome Initial Value is Assigned
3Re-Declaration is ErrorRe-Definition is Error

Some Re-commanded Reading List : Link 1 | Link 2 | Link 3