Forum

Learn C++ Functions
 
Notifications
Clear all

Learn C++ Functions

1 Posts
1 Users
0 Reactions
10 Views
 josh
(@josh)
Member Admin
Joined: 2 months ago
Posts: 510
Topic starter  

In C++, functions are like reusable mini-programs that help you organize your code into logical chunks. They make your programs cleaner, easier to understand, and more efficient 🧠🔧


🧱 What Is a Function?

A function is a named block of code that performs a specific task. You define it once and call it whenever you need it.

void greet() {
    std::cout << "Hello there!";
}
  • void means the function doesn’t return a value.
  • greet is the function name.
  • The code inside {} runs when you call greet();

🔁 Calling a Function

int main() {
    greet();  // This calls the function
    return 0;
}

Functions don’t run until they’re called—like pressing “play” on a playlist.


🧪 Functions with Parameters

You can pass data into functions:

void greet(std::string name) {
    std::cout << "Hello, " << name << "!";
}

Call it like: greet("Alice");


🔙 Returning Values

Functions can return results:

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

Use it like:

int result = add(3, 5);
std::cout << result;  // Output: 8

🧠 Function Declaration vs Definition

You can declare a function before main() and define it later:

// Declaration
int square(int);

// main function
int main() {
    std::cout << square(4);
    return 0;
}

// Definition
int square(int x) {
    return x * x;
}

This helps organize your code better.


⚙️ Advanced Features

  • Default arguments: int add(int a, int b = 10);
  • Function overloading: Multiple functions with the same name but different parameters.
  • Inline functions: Hint to the compiler to insert code directly for speed.

 


   
Quote
Share: