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.