Welcome back, aspiring coder! Today, we're diving into a fundamental aspect of C++ programming - Function Calling. This lesson will help you understand how to define, call, and use functions in your C++ programs, making your code more modular, organized, and reusable.
Functions are self-contained pieces of code that perform a specific task. In C++, functions help in organizing your code by breaking it down into smaller, manageable units.
To define a function, we use the void keyword (for functions that don't return a value) followed by the function name, parameters (if any), and a function body enclosed in curly braces {}.
// Function definition
void greet() {
std::cout << "Hello, World!";
}š Note: The std::cout is a standard C++ library used for outputting text to the console.
To call a function, we simply write the function name followed by parentheses ().
// Function call
greet();Now, when you run this program, "Hello, World!" will be printed to the console.
Functions can accept data through parameters. Parameters are placeholders in the function definition for the values that will be passed during the function call.
// Function definition with a parameter
void greet(std::string name) {
std::cout << "Hello, " << name << "!";
}Here, std::string name is a parameter that accepts a string value. To pass a value to this function during the call, we write the actual value inside the parentheses.
// Function call with an argument
greet("John");Now, when you run this program, "Hello, John!" will be printed to the console.
Some functions may need to return a value. To do this, we use the return keyword followed by the value we want to return.
// Function definition that returns an integer
int add(int a, int b) {
int sum = a + b;
return sum;
}In this example, the add function adds two integers and returns the result. To use this function, we can call it and store the returned value in a variable.
int result = add(5, 3);
std::cout << "The sum is: " << result << std::endl;Now, when you run this program, "The sum is: 8" will be printed to the console.
How do we call a function in C++?
Stay tuned for the next lesson, where we'll explore more advanced concepts related to C++ functions! š