C++ Function Return Types

Function return types in C++ define the type of value a function returns after execution. Functions can return basic types, objects, or nothing (void). Choosing the correct return type ensures proper usage and prevents errors.

1. Returning int

A function can return an integer value using the int return type.

C++
Example: Function returning int
#include <iostream>
using namespace std;

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

int main() {
    int result = add(5, 3);
    cout << "Sum: " << result << endl;
    return 0;
}

2. Returning double

Functions can return floating-point values using double or float types.

C++
Example: Function returning double
#include <iostream>
using namespace std;

double divide(double a, double b) {
    return a / b;
}

int main() {
    double result = divide(10.0, 4.0);
    cout << "Result: " << result << endl;
    return 0;
}

3. Returning void

If a function does not return any value, use the void return type.

C++
Example: Void function
#include <iostream>
using namespace std;

void greet() {
    cout << "Hello, World!" << endl;
}

int main() {
    greet();
    return 0;
}

4. Common Mistakes

Returning a value from a void function or forgetting to return a value for a non-void function can cause compilation errors. Always match the return type with the function's behavior.

Conclusion

C++ function return types determine the type of value a function produces. Correct usage ensures proper function behavior, prevents errors, and improves code clarity.