Commit 1a18af82 authored by Autopawn's avatar Autopawn

Updated types class, added primitive data types and pointers.

parent 956f7011
......@@ -41,10 +41,10 @@ typedef struct {
---
## El problema del acceso a los miembros
## El problema del acceso a los atributos
:arrow_forward: Notemos que hay miembros a los que es conveniente acceder directamente para lectura, como `len` y `sum`.
:arrow_forward: Sin embargo, una **modificación** directa de los miembros puede dejar nuestra estructura en un estado **inconsistente**.
:arrow_forward: Notemos que hay atributos a los que es conveniente acceder directamente para lectura, como `len` y `sum`.
:arrow_forward: Sin embargo, una **modificación** directa de los atributos puede dejar nuestra estructura en un estado **inconsistente**.
:soccer: Puede dar ejemplos de modifcaciones que resultan en estados inconsistentes:question:
......
figures/vectorsum_copy0.png

6.56 KB | W: | H:

figures/vectorsum_copy0.png

6.64 KB | W: | H:

figures/vectorsum_copy0.png
figures/vectorsum_copy0.png
figures/vectorsum_copy0.png
figures/vectorsum_copy0.png
  • 2-up
  • Swipe
  • Onion skin
......@@ -21,14 +21,339 @@ Programming Languages
# Types of types
:link: Ver diapositivas `P4-tipos.pdf` del profesor M. Araya.
:link: Ver diapositivas `5-tipos.pdf` del profesor M. Araya.
:arrow_right: A type is an **attribute** of the data which tells the compiler or interpreter how the programmer intends to use the data.
:arrow_right: What is important of the types:
* The set of **values** that they can represent.
* How the values are affected by the different operations (what do they **mean**).
* How much **memory** do they use.
---
## Ordinal types
:arrow_right: They can associated to a natural **number**:
* Integers
* Characters
* Booleans
:arrow_right: Some may be defined by the programmer
* **Enums**
* Ranges
---
:arrow_right: An `enum` in C:
```c
enum weekday {Mon=0,Tue=1,Wed=2,Thu=3,Fri=4,Sat=5,Sun=6};
enum weekday meeting_day;
```
:arrow_right: They are equivalent to an `int` but with named values.
:bulb: It is often used together with a `typedef`:
```
typedef enum weekday {Mon,Tue,Wed,Thu,Fri,Sat,Sun}; wday;
```
---
## Primitive data types
> A primitive data type is either a data type that is built into a programming language, or one that could be characterized as a basic structure for building more sophisticated data types.
:arrow_right: We have:
* Integers
* Characters
* Floating point (`float`, `double`, `long double`).
* Booleans
---
## Memory sizes
:arrow_right: In C we use the `sizeof` operator to know the number that a type uses:
```c
#include <stdio.h>
int main() {
printf("Size of char : %d\n",(int) sizeof(char));
printf("Size of int : %d\n",(int) sizeof(int));
printf("Size of short int : %d\n",(int) sizeof(short int));
printf("Size of long int : %d\n",(int) sizeof(long int));
printf("Size of float : %d\n",(int) sizeof(float));
printf("Size of double : %d\n",(int) sizeof(double));
printf("Size of long long int : %d\n",(int) sizeof(long long int));
printf("Size of char* : %d\n",(int) sizeof(char *));
printf("Size of long long int* : %d\n",(int) sizeof(long long int *));
return 0;
}
```
---
```plain
Size of char : 1
Size of int : 4
Size of short int : 2
Size of long int : 8
Size of float : 4
Size of double : 8
Size of long long int : 8
Size of char* : 8
Size of long long int* : 8
```
:bulb: Note that these may vary between architectures.
---
## Pointers
:arrow_right: Values that represent a direction in memory where a value of another type is stored.
:arrow_right: They can have the special value `NULL`, indicating that they are not pointing to a value (yet).
---
### Operations
:arrow_right: **reference**: we use `&` to get the position in memory of a given value:
```c
int a = 20;
int *ptr = &a;
//...
```
:arrow_right: **dereference** (or indirection): we use `*` to get the value in memory pointed by a pointer:
```c
//...
printf("%d\n",*ptr);
```
:arrow_right: **assignment**: we can assign a value on the position that the pointer is pointing to:
```c
*ptr = 30;
printf("%d\n",a);
```
---
:arrow_right: When adding an integer `n` to a pointer `type *a`, we get to the position $\texttt{a}+\texttt{sizeof(type)*n}$, this means:
$$
\texttt{a+n} = \texttt{\&a[n]}
$$
$$
\texttt{*(a+n)} = \texttt{a[n]}
$$
:arrow_right: We can have pointers of pointers without problem, for instance, to represent an array of pointers.
```c
int a = 20;
int b = 40;
int **ptrs = malloc(sizeof(int*)*3);
ptrs[0] = &a;
ptrs[1] = &b;
ptrs[2] = &a;
```
---
## Arrays
:arrow_right: Sequence of elements ubicated contiguously in memory.
:arrow_right: It is associated to a **size**, modern languages store it within the array but C **doens't**.
:arrow_right: They are identified with a **pointer** to the position of the **first** element.
:star: In some languages a check in runtime if an index is within the range of the array.
:star: Some languages provide multidimensional arrays.
---
## Strings
:arrow_right: In C the strings are represented like arrays of `char`.
:arrow_right: The length of the array is not stored, instead, the string is considered over once a special character `'\0'` appears.
![center](figures/string_representation_c.jpg)
---
## Structs
:arrow_right: User defined type for variables that can hold several data items of the same kind.
```c
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;
```
:arrow_right: Attribute `b` from a value of the struct `a` can be accessed with the `a.b` operator.
:arrow_right: The `a->b` operator is equivalent to `(*a).b`, so can be used when `a` is a pointer to the struct.
---
## Unions
:arrow_right: They store different types in the same memory.
```c
union direccion{
char dominio[20];
int ip[4];
};
```
![center](figures/union_ip.png)
---
### Some links
[:link: `string.h`](http://www.cplusplus.com/reference/cstring/)
* A header with functions to manipulate C strings.
[:link: `limits.h`](http://www.cplusplus.com/reference/climits/)
* In C we can get the maximum and minimum values that a the types can have using `#include <limits.h>`.
[:link: Primitive types in C++](https://www.tutorialspoint.com/cplusplus/cpp_data_types.htm).
* The types for C are the same with the exception that C doesn't habe `boolean`.
---
## Problems with pointers
:arrow_right: Working with pointers without care can result in:
* **Memory leak**
* **Invalid access**
* **Double free**
:skull_and_crossbones: All are runtime errors:bangbang:
---
![w:600px](./humor/fear_segfault.jpeg)
:bulb: We can use [valgrind](https://www.cprogramming.com/debugging/valgrind.html) to debug our programs.
---
### Memory leak
:arrow_right: When we asked for memory but then we lose all references to it and we can't release it.
```c
#include <stdlib.h>
int main(){
int *vals = malloc(sizeof(int)*3);
// ...
vals = malloc(sizeof(int)*3);
// ...
return 0;
}
```
![](figures/memory_leak.png)
:bulb: It also includes when we forget to release memory that we no longer use and exhaust the available system memory.
---
![w:600px center](humor/awesome_stack.png)
---
### Invalid access
:arrow_right: When we try to access memory that was not allocated.
```c
#include <stdlib.h>
#include <stdio.h>
int main(){
int *vals = malloc(sizeof(int)*3);
vals[0] = 10;
vals[1] = 20;
vals[2] = 30;
printf("value = %d\n",vals[3]); // invalid read
vals[3] = 40; // invalid write
}
```
![w:700px](figures/invalid_access.png)
---
:arrow_right: A NULL dereferentiation is also an invalid memory access:bangbang:
```c
#include <stdlib.h>
#include <stdio.h>
int main(){
int *value = NULL;
printf("value: %d\n",*value); // invalid read
return 0;
}
```
---
### Double free
:arrow_right: When we realease a block of memory that was already released.
```c
#include <stdlib.h>
int main(){
int *vals = malloc(sizeof(int)*3);
// ...
free(vals);
// ...
free(vals);
return 0;
}
```
![center w:400px](figures/double_free.png)
---
## The problem of NULL pointers
:arrow_right: Allowing pointers to be `NULL` means that any function that works with pointers should consider this case.
:arrow_right: Some people call it the [worst mistake of computer science](https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/).
:rabbit: Modern languages like Rust, and C#, and Haskell use the typesystem to make explicit when a value can have this **special case**.
<!-- Haskell is not that old -->
---
![center w:600px](humor/conan_null_pointer.jpg)
---
# Argument passing
:arrow_right: Passing information from calling function to the called function.
:arrow_right: It consists on passing information from a calling function to a called function.
---
......@@ -207,6 +532,16 @@ void fun(const bigstruct *x){
:arrow_right: It's particularly useful to avoid copying a big struct.
---
# :soccer: Activity
:arrow_forward: Let's do [Activity 1](ac01_vectorsum.md):bangbang:
![center](humor/two_states.jpg)
---
# Void pointers
......@@ -316,7 +651,7 @@ amet dolor ipsum lorem sit
:warning: This is not an absolute [definition](http://wiki.c2.com/?WeakAndStrongTyping):
> All languages can be placed somewhere in the 2D "typing" space whose axes are strong <-> weak and static <-> dynamic.
> E.g. types in SmalltalkLanguage are very strong, completely dynamic; types in PHP are quite weak, completely dynamic; types in LISP are completely strong, completely dynamic; types in C are quite weak, completely static; and so on...
> E.g. types in Smalltalk are very strong, completely dynamic; types in PHP are quite weak, completely dynamic; types in LISP are completely strong, completely dynamic; types in C are quite weak, completely static; and so on...
---
......@@ -407,7 +742,7 @@ public:
---
:arrow_right: If a method is used, `T` has to have it implemented.
:arrow_right: If a method is used, `T` has to have it implemented :duck:
```c++
template<class T>
void barkThreeTimes(const T& input)
......
......@@ -228,4 +228,10 @@ y:3
z:3
true
z:4
```
\ No newline at end of file
```
---
# Sobreescritura de operadores
:warning: Work in progress :warning:
\ No newline at end of file
......@@ -34,6 +34,10 @@ Lenguajes de Programación
---
![](humor/always_you_three.jpg)
---
## `Exception`
:arrow_right: Cuando se produce un error, se **interrumpe** el flujo normal de ejecución del código.
......
......@@ -13,7 +13,7 @@ Lenguajes de Programación
# ![center h:250px](figures/blocks.png)
## 17 - Más sobre Tipos
## 17 - Más sobre tipos en Haskell
###### Francisco Casas Barrientos
......
---
marp: true
size: 4:3
number: true
paginate: true
theme: default
style: |
img[alt~="center"]{display:block;margin: 0 auto;}
---
Lenguajes de Programación
===
:warning: WORK IN PROGRESS :warning:
[:egg:](https://www.youtube.com/watch?v=LJvEIjRBSDA)
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment