Table of Contents
A function is a named block of code that performs a specific operation. Functions allow a program to divide a larger task into smaller, reusable units and avoid repeating the same code.
A function can be called from different locations within a program. Depending on its definition, a function can accept input through parameters and return a value to the caller.
Source Code #
#include <iostream>
void greet()
{
std::cout << "Hello from the function.\n";
}
int main()
{
greet();
return 0;
}
Output #
Hello from the function.
Explanation #
void greet()defines a function namedgreet.voidspecifies that the function does not return a value.- The statements enclosed within
{}form the function body. std::coutinside the function displays the message when the function is executed.greet();calls the function frommain().- When the function is called, program execution transfers to the function body.
- After the function finishes executing, control returns to the statement following the function call.
- A function can be called multiple times from different locations in a program.
return 0;terminates the program successfully.