C++ Functions

Function declaration, definition, and overloading

Function Basics

int add(int a, int b) { # function with return type
    return a + b; # return value
}
void greet() { # void function (no return)
    cout << "Hello!"; # just output
}

Function Overloading

int sum(int a, int b) { # two parameters
    return a + b;
}
int sum(int a, int b, int c) { # three parameters
    return a + b + c;
}

Pass by Reference

void swap(int& a, int& b) { # pass by reference
    int temp = a;
    a = b; # modifies original
    b = temp; # modifies original
}

Default Parameters

int power(int base, int exp = 2) { # default value
    return pow(base, exp);
}
power(5); # uses default exp=2, returns 25
power(5, 3); # uses exp=3, returns 125