Topic 30 of 83
Return Values
Overview
Functions can send data back to the caller using the `return` statement. The return type (e.g., int, void, double) must be declared in the signature.
Syntax
cpp
// Returns an integer
int getSquare(int x) {
return x * x;
}
// Returns nothing
void logMessage(string msg) {
cout << "LOG: " << msg;
// return; is optional in void functions
}Common Pitfalls
- Forgetting to return a value in a non-void function (Undefined Behavior).
- Returning a pointer or reference to a local variable that gets destroyed when the function ends.
Interview Tips
- In modern C++, you can use `auto` as a return type, and the compiler will deduce it based on the `return` statement.
Real-World Example
Using a returned value in a calculation.
example
cpp
#include <iostream>
using namespace std;
double calculateTax(double amount) {
return amount * 0.08;
}
int main() {
double price = 100.0;
double total = price + calculateTax(price);
cout << "Total cost: $" << total << endl;
return 0;
}