C++ Functions

What Are Functions in C++?

Functions in C++ are blocks of reusable code designed to perform specific tasks. Instead of writing the same code multiple times, we can write a function once and use it whenever needed. This makes our code cleaner, easier to manage, and more efficient!

🎯 Why Use Functions?

  • Reusability: Define once, use multiple times.
  • Modularity: Break down programs into logical sections.
  • Clean Code: Makes the program easier to read and debug.

📌 Function Syntax

The basic syntax of a function in C++ looks like this:

return_type function_name(parameters) {
    // code to execute
}

Let’s look at a simple function that prints a message!

#include <iostream>
using namespace std;

void sayHello() {
    cout << "Hello from a function!" << endl;
}

int main() {
    sayHello();  // Calling the function
    return 0;
}
  

Try It Now

📦 Functions with Parameters and Return Values

You can pass values (parameters) to functions and even return a result. Let’s add two numbers using a function:

#include <iostream>
using namespace std;

int add(int a, int b) {
    return a + b;
}

int main() {
    int result = add(5, 3);
    cout << "Sum: " << result << endl;
    return 0;
}
  

Try It Now

🔧 Built-in Functions (Like sqrt())

C++ includes many built-in functions, such as mathematical functions from the <cmath> library.

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double num = 49.0;
    cout << "Square root: " << sqrt(num) << endl;
    return 0;
}
  

Try It Now

📚 Function Declaration vs Definition

Sometimes you declare a function before main() and define it later. This is useful when organizing large programs.

// Declaration
int multiply(int, int);

int main() {
    cout << multiply(2, 3);
    return 0;
}

// Definition
int multiply(int a, int b) {
    return a * b;
}

Try It Now

🧠 Scope of Functions and Variables

  • Local Scope: Variables declared inside a function only exist there.
  • Global Scope: Declared outside all functions—accessible anywhere.

✅ Summary

  • Use functions to make your code reusable and modular.
  • They can accept parameters and return values.
  • C++ also provides many built-in functions for common tasks.

Explore, experiment, and have fun coding with C++ functions!