← Previous | 🏠 Homepage | Next Chapter → |
- Functions in C
What’s a Function?
It’s like a mechanic — you just call him, and he knows what to do.
In C, we call a function using its name + ()
.
or
Think of a Restaurant!
You (the customer) place an order for masala dosa.
You don’t go into the kitchen, chop vegetables, cook or anything.
You just say:
"One masala dosa, please!"
Behind the scenes, the chef does all the work and brings you your dosa.
main() {
message(); // calling the function
}
message() {
printf("Smile!");
}
Key Points:
-
Every C program starts with
main()
. -
You can have many functions, but only one
main()
. -
Functions call each other; control jumps to the called function and returns after it finishes.
-
Functions can even call themselves (called recursion).
Passing Values
You can send data to functions using arguments.
sum = add(10, 20); // 10 and 20 are passed to add()
int add(int a, int b) {
return a + b; // sends result back
}
Actual arguments = from main()
Formal arguments = received by the called function
The return
Magic
return
sends back a result.return (a + b); // sends the sum back
You can return:
-
a number →
return (5);
-
nothing →
return;
(not recommended) -
no value at all → use
void
function
Notes:
-
Functions can’t be defined inside each other.
-
Changing a value in the function won’t change it in
main()
— only a copy is passed. -
Use functions to keep code clean and avoid repeating yourself.
Why Use Functions?
- Reuse code
-
Make programs easier to read and fix
-
Break big problems into small tasks
No comments:
Post a Comment