1.5. Introduction to Functions

[ fromfile: cppintro.xml id: intro-functions ]

Example 1.3. src/early-examples/fac2.cpp


#include <iostream> 

long factorial(long n) {
    long ans = 1;
    for (long i = 2; i <= n; ++i) {
        ans = ans * i;
        if (ans < 0) {
            return -1;
        }
    }
    return ans;
}

int main() {
    using namespace std;
    cout << "Please enter n: " << flush;
    long n;        1
    cin >> n;      2 

    if (n >= 0) { 
        long nfact = factorial(n);
        if (nfact < 0) {
            cerr << "overflow error: " 
                 << n << " is too big." << endl;
        }
        else {
            cout << "factorial(" << n << ") = "
                 << nfact << endl;
        }
    }
    else {
        cerr << "Undefined:  "
             << "factorial of a negative number: " << n << endl;
    }
    return 0;
}

1

long int

2

read from stdin, try to convert to long


int toCelsius(int fahrenheitValue);
QString toString();
double grossPay(double hourlyWage, double hoursWorked);

Function Overloading

Example 1.4. src/functions/overload-not.cpp

#include <iostream>
using namespace std;

void foo(int n) {
  cout << n << " is a nice number." << endl;
}


int main() {
   cout << "before call: " << 5 << endl;
   foo(5);
   cout << "before call: " << 6.7 << endl;
   foo(6.7);
   cout << "before call: " << true << endl;
   foo(true);
}

  src/functions> g++ overload-not.cpp
  src/functions> ./a.out
  before call: 5
  5 is a nice number.
  before call: 6.7
  6 is a nice number.
  before call: 1
  1 is a nice number.
  src/functions>
  

Example 1.5. src/functions/overload.cpp

#include <iostream>
using namespace std;

void foo(int n) {
  cout << n << " is a nice int." << endl;
}

void foo(double x) {
  cout << x << " is a nice double." << endl;
}

void foo(bool b) {
   cout << "Always be " << (b?"true":"false") << " to your bool." << endl;
}

int main() {
  foo(5);
  foo(6.7);
  foo(true);
}

  src/functions> g++ overload.cpp
  src/functions> ./a.out
  5 is a nice int.
  6.7 is a nice double.
  Always be true to your bool.
  src/functions>
  


[4] A constructor must not have a return type and may have an empty body. A destructor must not have a return type, must have an empty parameter list, and may have an empty body.

[5] The ternary conditional operator, testExpr ? valueIfTrue : valueIfFalse provides a terse way to insert a simple choice into an expression. If testExpr has a nonzero value (e.g., true) the value immediately to the right of the question mark (?) is returned. If testExpr has value 0 (e.g., false) the value to the right of the colon (:) is returned.