A function is a segment of code that executes only upon invocation.
It accepts input data, referred to as parameters.
Functions serve to execute specific tasks and are vital for code reuse: Define the logic once and employ it repeatedly.
Indeed, it appears you’re already familiar with the concept of a function. Throughout this tutorial, you’ve been utilizing functions consistently.
As an illustration, “main()” serves as a function responsible for executing code, while “printf()” functions to output or print text onto the screen.
int main() { printf(“Hello World!”); return 0; } |
To create, commonly referred to as declare, your own function, indicate the function name, followed by parentheses () and curly brackets {}.
void myFunction() { // code to be executed } |
Declared functions are not executed immediately. Instead, they are “stored for later use” and will be executed only when they are called.
To invoke a function, simply write the function’s name followed by two parentheses () and a semicolon ;
In the given example, myFunction() is employed to print a text (the action) upon its invocation.
Within the main function, invoke myFunction().
// Create a function void myFunction() { printf(“I just got executed!”); } int main() { // Outputs “I just got executed!” |
A function can be invoked multiple times.
void myFunction() { printf(“I just got executed!”); } int main() { // I just got executed! |