In C++, functions can have various types depending on their return value and arguments. Here are the main function type in C++:
Functions with a void return type: These functions do not return any value. They are typically used for performing operations that do not need to return a value to the caller.
void sayHello() {
std::cout << "Hello!"<< std::endl;
}
int add(int a, int b) {
return a + b;
}
Functions with no arguments: These functions do not take any arguments. For example:
void printMessage() {
std::cout << "This is a message." << std::endl;
}
Functions with one or more arguments: These functions take one or more arguments of specified types. For example:
void printName(std::string name) {
std::cout << "Your name is:" << name << std::endl;
}
Note that functions can also be declared as const or static, among other modifiers. const functions promise not to modify the state of the object, while static functions are not tied to a specific instance of a class.
int* createIntArray(int size) {
return new int[size];
}
In this example, the function createIntArray takes an integer argument size and returns a pointer to a dynamically allocated array of integers.
int& getLargest(int* arr, int size) {
int largest = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}
return largest;
}
In this example, the function getLargest takes an array of integers arr and its size size as arguments, and returns a reference to the largest element in the array.
Note that the return type of a function must match the type of the value that the function returns.
Learners TV is a website that is designed to educate users and provide instructional material on particular subjects and topics.