1. What is a Function?
A function is a self-contained block of code that performs a specific task. Think of it as a "mini-program" within your main program.
So far, you've been using one big function: main(). As
programs get more complex, you can't put all your code inside main(). You need
to break it down into smaller, manageable, and reusable pieces. Those pieces
are functions.
Analogy: A Recipe Book
·
Your main() function
is like the main recipe for "Host a Dinner Party."
· This main recipe has steps like:
1.
"Make the appetizer" (Call the makeAppetizer() function)
2.
"Make the main course" (Call the makeMainCourse() function)
3.
"Make the dessert" (Call the makeDessert() function)
·
The actual instructions for "how to make the main
course" are written on a different page (the makeMainCourse() function
definition). You can use this recipe again (call the function) any time you
want, without rewriting it.
2. Why Use Functions?
· Reusability (DRY): DRY stands for "Don't Repeat Yourself." If you need to do the same task 10 times (e.g., print a fancy welcome message), you write a function once and "call" it 10 times.
·
Readability / Organization: A main() function
that just contains 5 function calls is much easier to read and understand than
a main() function with 500 lines of
code. It shows the logical flow of your program.
·
Maintainability / Debugging: If
there's a bug in how the "main course" is made, you know to go
straight to the makeMainCourse() function
to fix it. You don't have to hunt through 500 lines of code.
3. The Three Parts of Using a Function
To use a function, you must do three things:
A. Function Declaration (or "Prototype")
This is an announcement to the C compiler, usually at the top of your .c file (before main). It tells
the compiler, "Hey, a function with this name, these inputs, and this output
type exists. Trust me. You'll find the details later."
Syntax: return_type function_name(parameter_list);
// Prototype for a function that adds two integers
// - It takes two 'int' parameters
// - It returns an 'int' value
int addNumbers(int num1, int num2);
B. Function Call
This is where you "run" or "execute" the
function. You do this from main() or from another function. You
provide the actual values (called arguments)
for the function's parameters.
Syntax: variable = function_name(argument1, argument2);
// Inside the main function
int sum = addNumbers(10, 5); // '10' and '5' are the arguments
printf("The sum is: %d\n", sum); // Will print "The sum is: 15"
C. Function Definition
This is the actual code for the function. It's the
"recipe" itself. It's typically written after the main() function.
The header must match the prototype exactly (or be compatible).
Syntax:
return_type function_name(parameter_list) {
// Body of the function:
// ... statements that do the work ...
return value; // The 'value' must match the 'return_type'
}Example Definition:
// This is the function definition for addNumbers
int addNumbers(int num1, int num2) {
int result = num1 + num2;
return result; // Send this value back to the caller
}Parameters vs. Arguments
·
Parameters: The
variables in the function's declaration/definition (e.g., num1, num2). They are
placeholders for the data.
·
Arguments: The
actual values passed to the function when it is called (e.g., 10, 5).
4. The `void` Keyword
void is a
special keyword that means "nothing." It's used in two places with
functions:
·
As a Return Type: If
your function doesn't send any value back (e.g., it just prints something), its
return type is void.
·
As a Parameter: If
your function takes no inputs, you can put void in
the parentheses.
5. Using Built-in Libraries
You've been using library functions all along! When you write #include <stdio.h>, you are
telling the compiler to include the declarations
(prototypes) for all the standard input/output functions.
·
printf() is a
function.
·
scanf() is a
function.
·
strlen() (from <string.h>) is a
function.
·
sqrt() (from <math.h>) is a
function.
The #include file gives you the
prototypes. The actual *definitions* are in a pre-compiled library that gets
linked automatically when you create your executable.
6. Example Program (Putting It All Together)
This program demonstrates four types of functions:
1. No arguments, No return value
2. With arguments, No return value
3. No arguments, With return value
4.
With arguments, With return value (the add function)
/* * Example 1: Full Function Demonstration * Shows prototypes, main, and function definitions.*/
#include <stdio.h> // For printf, scanf
// --- 1. Function Prototypes ---
// Type 1: Takes nothing, returns nothing
void printWelcomeMessage(void);
// Type 2: Takes an int, returns nothing
void printNumber(int num);
// Type 3: Takes nothing, returns an int
int getUserNumber(void);
// Type 4: Takes two ints, returns an int
int add(int a, int b);
// --- 2. Main Function ---
int main() {
// Call Type 1 function
printWelcomeMessage();
// Call Type 3 function
int num1 = getUserNumber();
int num2 = getUserNumber();
// Call Type 4 function
int sum = add(num1, num2);
// Call Type 2 function
printf("The sum is: ");
printNumber(sum);
return 0;
} // --- 3. Function Definitions ---
/* * Type 1: No arguments, No return value * Just performs an action.*/
void printWelcomeMessage(void) {
printf("*** Welcome to the Function Calculator ***\n");
} /* * Type 2: With arguments, No return value * Takes a value and performs an action with it.*/
void printNumber(int num) {
printf("%d\n", num);
} /* * Type 3: No arguments, With return value * Gets data from the user and returns it.*/
int getUserNumber(void) {
int input;
printf("Enter a number: ");
scanf("%d", &input);
return input;
} /* * Type 4: With arguments, With return value * Takes data, processes it, and returns the result.*/
int add(int a, int b) {
return a + b;
}