What if you could write a piece of code once and use it everywhere without repeating yourself?
Why Function declaration and definition in C++? - Purpose & Use Cases
Imagine you are writing a long C++ program where you need to perform the same task multiple times, like calculating the area of different shapes. Without functions, you would have to write the same code again and again in every place you need it.
Copying and pasting code everywhere makes your program long, hard to read, and easy to break. If you find a mistake, you must fix it in every copy, which wastes time and causes errors.
Function declaration and definition let you write the code for a task once and give it a name. You can then call this name whenever you want to run that code. This keeps your program clean, easy to understand, and simple to fix.
int main() {
int length = 5, width = 10;
int area = length * width; // repeated code
// ... many times
}int calculateArea(int length, int width); // declaration
int main() {
int area = calculateArea(5, 10); // call function
}
int calculateArea(int length, int width) { // definition
return length * width;
}Functions let you organize your code into reusable blocks, making programs easier to build, read, and fix.
Think of a coffee machine: you press a button (call a function) to get coffee without knowing how the machine works inside. Functions in code work the same way.
Writing code once and reusing it saves time and effort.
Function declaration tells the program about the function's name and inputs.
Function definition contains the actual code to run when called.