In C++, a function is a block of code designed to perform a specific task. Functions allow you to break your program into smaller, modular, and reusable pieces. Instead of writing the same code multiple times, you write it once in a function and call it whenever needed!
To use a function, you first need to declare and define it, and then you can call (or invoke) it from main() or another function.
returnType functionName() {
// Code to be executed
}
returnType: The data type of the value the function returns (e.g., int, double). Use void if the function doesn't return anything.functionName: The name of the function (e.g., myFunction). It should describe what the function does.(): Parentheses may contain parameters (inputs to the function).#include <iostream> using namespace std;// Create a function void sayHello() { cout << "Hello, World!" << endl; }
int main() { // Call the function sayHello(); sayHello(); // You can call it multiple times! return 0; }
In professional C++ programming, a function consists of two parts:
It is a best practice to declare functions above main() and define them below main().
#include <iostream> using namespace std;// Function Declaration void printMessage();
int main() { printMessage(); // Function Call return 0; }
// Function Definition void printMessage() { cout << "Learning C++ is fun!" << endl; }
Which keyword is used as the return type for a function that does not return a value?