Jun 10, 2016

C Programming #65: Difference between declaration and definition

C Programming #65: Difference between declaration and definition

Even the experienced C programmer gets confused between declaration and definition. This article tries to explain it explicitly; so that it is cemented permanently.


To understand the difference between them lets first know the English meaning of both.

declare: (verb)say something in a solemn and emphatic manner.
define: (verb)state or describe exactly the nature, scope, or meaning of.

We declare to compiler prototype of function, variable ahead to find the exact definition later. e.g

#include <stdio.h>
extern int x; // Declaration
int main() 
{
   printf("Value of x is %d\n", x);
}
int x = 10;   // Definition
Value of x is 10

Declaration doesn't allocate the memory of variable x, neither does it initialize. It just tells compiler that x is variable of type int, whose definition is expected. Definition here is after main, it could have been even in different file also. Same concept applies of other primitive data-type float, char and double; also same could be applied to variable declaration and definition of user-type enum, typedef, struct and union. Following C program explains all.

#include <stdio.h>

typedef unsigned int roll_num_t; // Declaration of type roll_num_t
enum gender_t{MALE, FEMALE, OTHER}; // Declaration of type gender_t

typedef struct student_tag { // Declaration of struct student_tag
   roll_num_t r;  // Declaration of member variable r
   enum gender_t g; // Declaration of member variable g
}student_t; // Declaration of typedef student_t 

int main()
{
   student_t s; // Definition of variable s of type student_t
   s.r = 10;
   s.g = MALE;

   printf("Student roll is %d, Gender is %d\n", s.r, s.g);

   return 0;
}
Student roll is 10, Gender is 0

In case of function prototype of function is Declaration, Function body is the function definition. Taking a old example again

#include <stdio.h>
int factorial(int); // Declaration of function factorial
int main() 
{
   int fact, n = 4;

   fact = factorial(n);

   printf("Factorial of n is %d\n", fact);

   return 0;
}
int factorial(int x) // Definition of function factorial
{
   int temp_fact;
   if(x == 1) {
      temp_fact = 1;
   } else {
      temp_fact = x * factorial(x - 1);
   }
   return temp_fact;
}
Factorial of n is 24

Also note that we could declare any number of times but only defined once. If in declaration of variable if initialization is done, it is considered as definition. Hope this clears declaration and definition concepts.

No comments :

Post a Comment