Defining & Declaring Functions
Anatomy of a function
return_type name(parameter_list) {
body
return value;
}
double add_vat(double amount) {
return amount * 1.13;
}
- Return type: the type of value sent back (
void= nothing) - Parameters: inputs (each with a type)
- Arguments: the actual values passed when calling:
add_vat(1500)
Declaration vs definition
- Declaration (prototype): tells the compiler the function exists
double add_vat(double amount); - Definition: the actual body
- A function must be declared before it's called. Either define it above
main, or declare it above and define it below. - In bigger programs, declarations go in header files (
.h), definitions in.cppfiles (Unit 8.8 / 17).
void functions
void print_line(int width) {
std::cout << std::string(width, '-') << '\n';
}
return; can exit early.
Return rules
- A non-void function must return a value on every path (compiler warns otherwise; missing it is undefined behaviour)
returnends the function immediately
Why functions?
- Reuse: write once, call many times
- Readability:
calculate_emi()explains itself - Testing: test small pieces separately
- DRY: Don't Repeat Yourself
Good function design
- Do one thing well
- Clear verb names:
calculate_total,is_valid_email,print_report - Few parameters (≤ 4 is a good guide)
- Short enough to fit on a screen
[[nodiscard]] (C++17)
Warns if a caller ignores the return value: [[nodiscard]] bool save();
Example
#include <iostream>
#include <string>
// Declarations (prototypes)
double add_vat(double amount);
bool is_valid_amount(double amount);
void print_receipt(const std::string& item, double amount);
[[nodiscard]] double emi(double principal, double yearly_rate, int months);
int main() {
print_receipt("Internet", 1500);
print_receipt("Phone bill", 800);
print_receipt("Refund", -50);
double monthly = emi(500000, 12, 24);
std::cout << "EMI for Rs. 500000 at 12% for 24 months: Rs. " << static_cast<long>(monthly) << '\n';
return 0;
}
// Definitions
double add_vat(double amount) {
return amount * 1.13;
}
bool is_valid_amount(double amount) {
return amount > 0;
}
void print_receipt(const std::string& item, double amount) {
if (!is_valid_amount(amount)) {
std::cout << item << ": invalid amount\n";
return; // early exit from a void function
}
std::cout << item << ": Rs. " << amount << " + VAT = Rs. " << add_vat(amount) << '\n';
}
double emi(double principal, double yearly_rate, int months) {
double r = yearly_rate / 12 / 100;
double factor = 1;
for (int i = 0; i < months; ++i) factor *= (1 + r);
return principal * r * factor / (factor - 1);
}
/* Output:
Internet: Rs. 1500 + VAT = Rs. 1695
Phone bill: Rs. 800 + VAT = Rs. 904
Refund: invalid amount
EMI for Rs. 500000 at 12% for 24 months: Rs. 23536
*/