#+TITLE: Task 1: Const and reference types
#+AUTHOR: JirR02

/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.

   #+begin_src cpp
int foo(int i) {
    return ++i;
}
   #+end_src

2.

   #+begin_src cpp
int foo(const int i) {
    return ++i;
}
   #+end_src

3.

   #+begin_src cpp
int foo(int& i) {
    return ++i;
}
   #+end_src

4.
   
   #+begin_src cpp
int& foo(int i) {
    return ++i;
}
   #+end_src

5.

   #+begin_src cpp
const int& foo(int& i) {
    return ++i;
}
   #+end_src

For each function, answer the following questions:

    a) 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):

    b) 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).

    c) 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

#+begin_src md
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.
#+end_src

-----

Made by JirR02 in Switzerland 🇨🇭
