Functions in C++
Functions are central in C++. We’ll learn about functions with a few different examples.
#include <iostream>
// Here's a function that takes two ints and returns
// their sum as an int.
int plus(int a, int b) {
// C++ requires an explicit `return` for non-void functions;
// falling off the end of a non-void function is undefined
// behavior and modern compilers will warn or reject it.
return a + b;
}
// In C++, you need to declare the type for each parameter,
// even if they are of the same type.
int plusPlus(int a, int b, int c) {
return a + b + c;
}
int main() {
// Call a function just as you'd expect, with
// name(args).
int res = plus(1, 2);
std::cout << "1+2 = " << res << std::endl;
res = plusPlus(1, 2, 3);
std::cout << "1+2+3 = " << res << std::endl;
return 0;
}To compile and run this C++ program:
$ g++ functions.cpp -o functions
$ ./functions
1+2 = 3
1+2+3 = 6There are several other features to C++ functions. One is function overloading, which allows multiple functions with the same name but different parameter lists. Another is default arguments, which allow you to specify default values for function parameters.
C++ functions are similar to those in other languages, but with some key differences:
- Function declarations (prototypes) are often used in header files, with the implementation in separate source files.
- C++ supports function overloading, allowing multiple functions with the same name but different parameter lists.
- Default arguments can be specified for function parameters.
- C++ supports inline functions for performance optimization.
- Function templates allow for generic programming.
These features make C++ functions powerful and flexible, allowing for efficient and reusable code.
Comments powered by Disqus