# C Handin 2

## Description

This hand in is based on C_Handin_1. This time we're adding better handling of bad input (e g `1 / 0`) and overflows.

## Problems

### Overflow

On the authors' copmuters (running GNU/Linux) the maximum value of an integer is 2147483647. So let's be a bit nasty and ask the calculator to add 1 to that nunmber: `./calc 2147483647 + 1`. Compare this to having a piece of paper with space for one digit only. The maximum value is 9, if we use the decimal system. What happens if you were asked to add 1 to the 9 and store it on the paper? It wouldn't work. Same thing with an int variable. Let's try it out:

```#./calc 2147483647 + 0
2147483647
#./calc 2147483647 + 1
-2147483648
```

Note that we couldn't add 1 to the max value.

### Division with 0

Let's try this `./calc 2147483647 / 0 `.

```# ./calc 2 / 0
Floating point exception (core dumped)
```

## Making our calculator more robust

### Overflow

It's a bit harder to make this code robust than just making sure that none of operators is the max value or min value or such. It's about making sure that the value of the calculated expression fits in an integer and provide some status back to the caller to indicate that status.

#### Strategy for fixing the overflow

1. Use the function `unsigned long int strtoul(const char *str, char **endptr, int base)` or `long int strtol(const char *nptr, char **endptr, int base);` to convert the String to an `unsigned long int`.
2. If the value is bigger than INT_MAX or smaller than INT_MIN than we have an error, otherwise cast the value to an int.

This will prove a bit hard, so if you want some help with converting a string to an int (hopefully safely), feel free to use the following code: strtoint.c, strtoint.h and some test code if you want for the two previous files strtoint-test.c. If you prove the code we provide is wrong/faulty/buggy SHOUT IT OUT during a lecture.

##### Calculating the value:
1. Store the resulting value after calculation in an `long int`.
2. If the value is bigger than INT_MAX or smaller than INT_MIN than we have an error, otherwise cast the value to an int.

### Division with 0

This is actually kind of easy. It's not just about forbidding `0` as the second operand because `1 + 0` is still valid. But writing code to detect if the operator is DIVISION or REMAINDER and the operand being 0.