Functions in c++
Certainly! In C++, functions are blocks of code that perform a specific task and are designed to be reusable. Here's an overview of how functions are declared and defined in C++:
// Function declaration (prototype)
returnType functionName(parameterType1 parameter1, parameterType2 parameter2, ...);
// Example
int add(int a, int b);
Function Definition:
// Function definition
returnType functionName(parameterType1 parameter1, parameterType2 parameter2, ...) {
// Function body
// Statements to perform the task
// Return statement (if the function has a return type)
}
// Example
int add(int a, int b) {
return a + b;
}
Example of Using Functions:
#include <iostream>
// Function declaration
int add(int a, int b);
int main() {
// Function call
int result = add(3, 4);
// Output the result
std::cout << "Result: " << result << std::endl;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
add is a function that takes two integer parameters (a and b) and returns their sum. The function is declared at the top of the code to inform the compiler about its existence before it is used in main. The function is defined later in the code, providing the actual implementation of the task it performs. In main, the function is called with arguments 3 and 4, and the result is stored in the variable result. The result is then printed to the console.