C Declaration and Definition

๐Ÿ“˜ C Declaration and Definition – Variables and Functions Explained

In C programming, declaration and definition are two fundamental concepts that are often misunderstood. Letโ€™s simplify them:

๐Ÿ”น Declaration

A declaration tells the compiler about the name and type of a variable or function, but it does not allocate memory (for variables) or contain actual code (for functions).

๐Ÿ”น Definition

A definition not only declares but also allocates memory (for variables) or provides the implementation (for functions).

๐Ÿ“ Example 1: Variable Declaration vs Definition

Here, the declaration happens first, then the definition with initialization.

// Declaration
extern int num;

// Definition
int num = 10;
  

Try It Now

๐Ÿ“ Example 2: Function Declaration and Definition

We declare the function at the top and define it later in the program.

#include <stdio.h>

// Function declaration
void sayHello();

int main() {
    sayHello(); // Function call
    return 0;
}

// Function definition
void sayHello() {
    printf("Hello from the function!\n");
}
  

Try It Now

๐Ÿง  Important Notes

  • extern is used to declare a variable without defining it.
  • A declaration can appear multiple times, but a definition must appear only once.
  • Function prototypes are declarations.

๐ŸŽฏ Summary

  • Declaration: Announces the name and type.
  • Definition: Actually creates the object or implements the function.

๐Ÿ’ก Tip Time!

Use declarations to organize code across files and definitions to actually get things done. Try declaring variables or functions in a header file and defining them in a source file.