JirR02 bfc1a7a2b0 Exercise 6
Added Exercise 6
2025-04-01 10:45:29 +02:00
..
2025-04-01 10:45:29 +02:00

Task 1: Const and reference types

This task is a text based task. You do not need to write any program/C++ file: the answer should be written in main.md (and might include code fragments if questions ask for them).

Note: You can safely ignore any undefined behavior due to integer overflows.

Task

Consider the following functions:

  1. int foo(int i) {
     return ++i;
    }
  2. int foo(const int i) {
     return ++i;
    }
  3. int foo(int& i) {
     return ++i;
    }
  4. int& foo(int i) {
     return ++i;
    }
  5. const int& foo(int& i) {
     return ++i;
    }

For each function, answer the following questions:

  1. Does the function attempt to modify const variables? If so, give the reason why (max. 15 words).

If no, answer the following (otherwise put N/A):

  1. Variable scopes: are the output and side effects of the function well-defined, i.e., free of undefined behavior? If not, give the reason why (max. 15 words).
  2. If the answer in b) is yes, give the precise post condition for the corresponding function foo. In particular, indicate what side effects the function may have.

Solution

1.

```c++
int foo(int i) {
    return ++i;
}
```

a) Yes and no, if depends if the input is assigend to a constant or not but generally no.

b) Yes

c) `foo` returns the increment by 1 of `i`. The side effect of this function is, that the variable `i` is only accessible inside the function `foo`. To make `i` accessible, one has to use the function as follows: `int b = foo(i)`


2.
```c++
int foo(const int i) {
    return ++i;
}
```

a) Yes, since `i` is defined as a constant variable the function foo increments `i`.

b) N/A

c) N/A


3.

```c++
int foo(int& i) {
    return ++i;
}
```

a) Yes and no, it depends if the reference is assigned to a constant variable or not but generally no.

b) Yes

c) The variable `i` which is referenced to another variable outside of the function will be incremented. Since it's referenced the variable is not only accessible within the function.


4.

```c++
int& foo(int i) {
    return ++i;
}
```

a) Yes and no, if depends if the input is assigend to a constant or not but generally no.

b) Yes

c) Since the whole function is a referenced, the variable which is inputted into the function will not be incremented. Instead the variable `i` will only be in scope of the function `foo` so as in task two, to use the function one has to use it as follows: `int b = foo(i);`

5.

```c++
const int& foo(int& i) {
    return ++i;
}
```

a) Yes and no, if depends if the input is assigend to a constant or not but generally no.

b) Yes

c) This function will increment the input and return it as a constant.

Made by JirR02 in Switzerland 🇨🇭