Understanding function in C++

A function in C++ is a self-contained block of code that performs a specific task and can be called from other parts of your program. Functions help to make your code modular and reusable, allowing you to break down a complex program into smaller, more manageable parts.


Here is a simple example of a function in C++:

#include <iostream>

using namespace std;

// Function declaration
int addNumbers(int a, int b);

int main() {
    int x = 5, y = 10, sum;
    sum = addNumbers(x, y); // Function call
    cout << "The sum of " << x << " and " << y << " is " << sum << endl;
    return 0;
}

// Function definition
int addNumbers(int a, int b) {
    int result = a + b;
    return result;
}

 

In this example, the addNumbers function takes two integer arguments, a and b, and returns their sum as the result. The function is declared in the program before it is called in the main function, where it is used to calculate the sum of x and y. When the function is called, the values of x and y are passed as arguments, and the result of the function is stored in the variable sum. The result is then displayed on the screen using the cout statement.

 

'C++' 카테고리의 다른 글

Compiling C++ Code on a Mac using the Terminal and GCC  (0) 2023.02.10
Key Features of C++14  (0) 2023.02.10
Lambda Functions in C++  (0) 2023.02.10
Function Pointers in C++  (0) 2023.02.10
Overview of C++11 and C++14 Features  (0) 2023.02.10

+ Recent posts