C++ Function Calling šŸŽÆ

beginner
20 min

C++ Function Calling šŸŽÆ

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.

What are Functions in C++? šŸ“

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.

Defining a Function in C++ šŸ’”

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 {}.

cpp
// Function definition void greet() { std::cout << "Hello, World!"; }

šŸ“ Note: The std::cout is a standard C++ library used for outputting text to the console.

Calling a Function in C++ šŸ’”

To call a function, we simply write the function name followed by parentheses ().

cpp
// Function call greet();

Now, when you run this program, "Hello, World!" will be printed to the console.

Parameters and Arguments šŸ“

Functions can accept data through parameters. Parameters are placeholders in the function definition for the values that will be passed during the function call.

cpp
// 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.

cpp
// Function call with an argument greet("John");

Now, when you run this program, "Hello, John!" will be printed to the console.

Returning a Value from a Function šŸ’”

Some functions may need to return a value. To do this, we use the return keyword followed by the value we want to return.

cpp
// 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.

cpp
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.

Quiz Time šŸŽÆ

Quick Quiz
Question 1 of 1

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! šŸš€