Lecture 03: Functions

Jan 17, 2024  β”‚  Last updated Jan 14, 2024 by Charlotte Curtis

HTML Slides html β”‚ PDF Slides PDF

Where we left off

#include <iostream>
using namespace std;
#define PI 3.14159

int main() {
  double r;
  cout << "Enter the radius: ";
  cin >> r;
  cout << "The area is " << PI * r * r << endl;
  return 0;
}

Today’s topics

Textbook Sections 4.1-4.5

Program execution

Predefined functions

Remember how you needed to access Python functions with . syntax, such as random.randint? C++ is similar, using :: instead of ., and the using namespace std statement lets you skip the std:: part.

<cmath> functions

FunctionDescription
fabs(x)Absolute value of x
pow(x, y)x to the power of y
sqrt(x)Square root of x
ceil(x)Smallest integer greater than or equal to x
floor(x)Largest integer less than or equal to x
round(x)Nearest integer to x
sin(x)Sine of x (and other trig functions)

emoji Review: Calling functions 1/2

Given a function pow(int x, int y) that returns $x^y$, what output do you think the following code will produce? Assume the code is part of a complete program.

  1. No output
  2. 8
  3. 9
  4. 27
  5. Error
int x = 2;
int y = 3;
cout << pow(y, x) << endl;

emoji Review: Calling functions 2/2

Given a function pow(int x, int y) that returns $x^y$, what output do you think the following code will produce? Assume the code is part of a complete program.

  1. No output
  2. 8
  3. 9
  4. 27
  5. Error
int x = 2;
int y = 3;
pow(x, y);
cout << pow << endl;

Main takeaway: function calls

General form is similar to Python:

return_val = function_name(argument1, argument2, ...);

Example: formatted output

print(f"Total: ${bill:.2f}")
cout.precision(2);
cout << fixed;
cout << "Total: $" << bill << endl;

Formatting output: field width

print(f"Total:    ${bill:8.2f}")
print(f"With GST: ${bill*1.05:8.2f}")
#include <iomanip>
cout.precision(2);
cout << fixed;
cout << "Total: $" << setw(8) 
     << bill << endl;
cout << "With GST: $" << setw(8) 
     << bill*1.05 << endl;

Remember abstraction?

Declaring functions

Defining functions

def func_name(args) -> return_type:
    # function body
    return return_val
return_type func_name(args) {
    // function body
    return return_val;
}

void functions

What if you don’t want to return anything?

def say_hello() -> None:
    print("Hello!")
void say_hello() {
    cout << "Hello!" << endl;
}

Caution: Python’s return types are just a suggestion, while in C++ they are strictly enforced.

Complete program example with functions

#include <iostream>
#include <cmath>
using namespace std;

double hypoteneuse(double a, double b); // function declaration

int main() {
  double a, b;
  cout << "Enter the two side lengths of a right angle triangle: ";
  cin >> a >> b;
  cout << "The hypotenuse length is " << hypoteneuse(a, b) << endl;
  return 0
}

double hypoteneuse(double a, double b) { // function definition
    return sqrt(a*a + b*b);
}

A brief preview of Separate Compilation

Separate Compilation

make

Compiling in multiple steps is a tedious process, so we automate it with a makefile

# This is "Makefile". Notice that comments begin with "#"
program: defs.o main.o
    g++ main.o defs.o –o program
main.o: main.cpp
    g++ -c main.cpp
defs.o: defs.cpp
    g++ -c defs.cpp

Tangent: Curly brace convention

Refresher: Variable scope

As in Python, variables defined in a function (including parameters) are only accessible within that function:

int main() {
    int x = 5;
    int y = some_func();
    return 0;
}

int some_func() {
    return x * 2; // Error: x is not defined
}

We’ll talk more about scope next lecture

Coming up next

Textbook 4.5, 5.1-5.2



Previous: Lecture 02: C++ Basics Continued
Next: Lecture 04: Pass by reference