본문 바로가기
[Umich] COE Core/ENGR 101 (Matlab, C++)

[Notes] Ch.15 Functions in C++ (Runestone)

by Class of 26' Yuri Hong 2022. 11. 18.

I. Function Basics 

1. Basic structure of a function in C++

int square(int n){
Return n * n; 
}

The function square takes one int parameter (a variable you can use in your function code), and returns an int value. 

 

Ex) calling the function:

    int x = 3;                    

    int y = square(x);      

    cout << y << endl;    

Ex) what is wrong with the following function call? 

The statement is declaring a new variable n inside the function call. Instead, you want to pass an existing variable to the function. 

 

2. Application 

II. Function Details 

1. The details

When a function is called: 

(1) The values of the argument expressions are copied into the parameter variables. 

(2) The code for the function’s implementation is run. 

(3) As soon as a return statement is encountered, the function ends immediately. 

(4) The returned value is transferred back to the calling code, where it is used wherever the function call had appeared. 

 

2. Type Checking return statements 

3. C++ and MATLAB Differences

(1) C++ does not allow returning more than one value. 

MATLAB’s compound return syntax allowed this. 

(2) In C++, it is common to define several functions in the same file. 

In MATLAB, functions are often written in their own file. 

(3) In C++, a return statement determines the return value. 

In MATLAB, whatever values were stored in the specified return variables at the end of the function were sed as the return values. 

 

4. Arguments and Parameters

Functions may have many parameters, each with their own type. 

// prints a message and returns the sum of x and y 
int func(int x, string message, int y) { // function signature: the name, parameters, return type. 
   cout << message;
   return x+y;
}


int main () {
   int a = 3;
   int b = 4;
   int c = func(a, “hello”, b); // The ordering of arguments you pass in is used to determine what goes to which parameter. 

5. Motivation for functions 

(1) Functions make code easier to write / understand 

(2) Functions are great for separating out a set of steps that get repeated (iteration) 

(3) Even if it’s just one or two lines of code in the function, the abstraction can make your overall program much clearer. 

 

EXERCISE) Function for DNA Pattern Matching 

Write a function matchPattern. The function should take in three parameters: the DNA string, the pattern string to look for, and an integer for the length of the pattern. It should return a Boolean value: true if the pattern is found, and false if the pattern is not found. 

 

 

III. Void Functions 

1. Basic Structure

Some functions don’t return anything. They just do stuff. 

(1) This function takes in a number, and prints out a row of X’s, where the number of X’s printed is specified by the function parameter num. 

(2) The void keyword in the function signature indicates that there is no return value for this function. 

(3) Void functions will have some “side effect”, such as printing something out or changing the values of their parameters. 

 

EXERCISE) Printing Triangles 

 




IV. Functions and Scope 

1. Global Scope

(1) Variables declared outside of a function have global scope. 

(2) They can be used anywhere in the program. 

(3) In most cases, global variables are evil. 

(4) Because they can be used from anywhere. 

-- It’s hard to keep track of which parts of code use them. 

-- They allow seemingly separate parts of code to interfere with each other. 

 

2. Global Constants

(1) One non-evil use of global variables is for constants. 

(2) These are variables whose value will never change. 

-- In C++, use the const keyword to enforce this. 

 

3. Function block scope 

(1) The body of a function constitutes a block. 

(2) All local variables in the function have this block scope. 

(3) All parameters also have this block scope! 

 

4. Scope and Naming 

(1) Different scopes can have variables with the same name. 

(2) The complier considers these to be completely separate. 

 

 

5. Shadowing

(1) Working with nested scopes can be tricky. 

* BE CAREFUL about using declarations. Only declare a variable to create it – now whenever you use it. 

 

Correction: 

 

 

Ex) what is wrong with the following code? 

 

The variable y is not in scope in the square() function.

V. Declaring Functions 

1. Declaring Functions

(1) Just like variables, functions must be declared before use. 

(2) This leads to compile errors if functions are defined in the wrong order: 

Correction: 

 

2. Declaring functions: order matters!

(1) One solution: declare and define the functions before they’re used. 

 

3. Function Prototypes

(1) A function prototype: declares a function before it is actually defined.

 => It is written as the function signature followed by a; 

 

IV. Swapping Variable Values 

Correction: 

1. Parameter Passing 

(1) There are two mechanisms for parameter passing in C++;

=> Pass-by-value (This is default) 

// X and y are unchanged. -> a and b are given copies of the values of x and y 

  • X 와 y 그 자체를 가져가는게 아니라 x 와 y 값을 우선 swap(2,7) 로 대입하고 나서 void 로 데려감. 그럼 int a = 2, int b = 7 이 되는 것임. 값 수정이 안됨. 

=> Pass-by-reference (Specify with &) 

// x and y are swapped -> no copies! a refers to x, b refers to y 

  • X 와 y 그 자체를 데려가서 int a = x 와 int b = y 가 되게 하고 그 다음에 함수를 굴림. 그럼 값을 수정할 수 있게 됨. 

 

Ex) We are writing a function that calculates the area of the triangle. The function takes two parameters: the base of the triangle, and the height of the triangle. It returns the area of the triangle. 

A: We should use Pass-by-value. 

  • We don’t need to modify either the base or the height of the triangle. 

Ex) We are writing a function that adds interest to a bank account balance. The function takes one parameter, the bank account balance. Inside the function, the bank account balance is updated to include the interest. 

A: We should use Pass-by-reference. 

  • We need to modify the bank account balance. 

Ex) We are writing a function that updates the battery charge of an electric car while it’s being charged. The function takes one parameter: the current charge of the car. It returns void, but inside the function, it updates the current charge of the car. 

A: We should use Pass-by-reference.  

  • We need to modify the charge. 

IV. Summary  

(1) When defining a function, the function signature (the first line of the function) must include the name of the function, the types of the parameters, and the return type of the function. 

(2) To call a function, we pass it arguments. There are two ways to pass arguments to a function: pass-by-value (the default) and pass-by-reference (specified with &). 

-- In pass-by-value, functions are given copies of the argument values. 

--In pass-by-reference, the parameters refer directly to the arguments passed in. Changes to the parameters are visible outside the function. 

(3) The order of the arguments determines which argument goes with which parameter. After arguments are passed to a function, the function is run. As soon as a return statement is encountered, the function ends and transfers the return value back to the calling code. Only one value can be returned from a function. 

(4) void function don’t return anything, but they usually have some side effect, such as printing something out or changing the values of their parameters. 

(5) Variables declared outside of a function have global scope. You don’t usually want to use global scope, unless you are declaring a constant, a variable that never changes (specified with const). 

(6) A function parameter or a variable declared inside a function only has scope within that function. 

(7) You must declare a function before it is used. To do this, you can either declare and define a function before it’s used, or you can use a function prototype to declare a function ( and define it somewhere later). 

댓글