Primitive Data Types

  • The most basic data types available in a programming language
  • Reflections of the hardware
    • are directly related to how the computer’s hardware processes and stores data
    • primitive data types are designed to map directly to the underlying hardware of a computer (i.e., allow programs to interact with the hardware in an efficient way)

Integer

  • An exact reflection of the hardware

  • Integer sizes: platform-independent

    • Java signed integer sizes: byte(1 bytes), short(2 bytes), int(4 bytes), long(8 bytes)
    • C/C++ signed integer sizes are not fixed
    • Python: arbitrary sizes

Floating Point

  • Mordelling real numbers, but just approximations
  • IEEE Floating-Point Standard 754
  • Languages support at least 2 floating-point types: float (32 bits), double (64 bits)

Complex

  • Some languages support a complex type (e.g., Python, C99)
    1
    2
    3
    4
    5
    print(1+4j) # (1+4j)
    print((1+4j)*(1+4j)) # (-15+8j)
    print(j) # not complex
    print(j*j) # not complex
    print(1j*1j) # (-1+0j)

Decimal

  • For business applications which involve money (e.g., COBOL~ essential, C#, Python)
  • It stores a fixed number of decimal digits in binary coded decimal
  • Advantages:
    1. Accuracy
  • Disadvantages:
    1. Limited range
    2. Memory waste

Boolean

  • true, false

  • C99 and C++ allow numeric expressions to be used as Boolean, but Java and C# do not because of the reliability

    1
    2
    3
    4
    5
    6
    int main(){
    int j = 0;
    if(j = 1){
    std::cout << "GG" << std::endl;
    }
    }
  • Advantages:

    1. Readability
    2. Reliability

Character

  • Stored as numeric codings (ASCII standard and Unicode not standard)
  • Noted: Python does not have Character type (it is a string of one length)

Character String Types

  • A sequences of characters

  • Typical Operations:

    1. Assignment and copying
    2. Comparasion (ascending/descending)
    3. Concatenation
    4. Substring reference
    5. Pattern matching
  • String Types in Languages:

    1. C and C++

      • Not primitive, use char arrays and a library of functions provides operation
    2. Java and C#

      • Not primitive, use the String class
    3. Fortran and Python

      • Primitive type with assignment and serveral operations
    4. Perl and JavaScript

      • Provide built-in pattern matching (regular expression)
  • String Length Options:

    • Static length in Python, Java String class

      • It only need a compile-time descriptor for the length
    • Limited dynamic length in C and C++ char arrays (\0 indicates the end of string)

      • It may need a run-time descriptor for the length and maximum length
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        int main(){
        char s1[3] = {'a', 'b', 'c'};
        std::cout << s1 << std::endl; // dangerous
        char s2[4] = {'a', 'b', 'c', '\0'};
        std::cout << s2 << std::endl; // safe
        char s3[] = "abc";
        std::cout << s3 << std::endl; // safe

        // Limited dynamic length
        char s4[20] = "hahahaha";
        std::cout << s4 << std::endl; // hahahaha
        s4[8] = '!';
        std::cout << s4 << std::endl; // hahahaha!
        }
    • Unlimited dynamic length in Perl

      • It must need a run-time descriptor for the length and maximum length
        1. Linked-list
        2. Adjacent storage cells

Ordinal Types

  • It represents values that have a natural ordering among them
  • It is the range of possible discrete values can be easily associated with the set of integers
  • Primitive Ordinal Types:
    • int
    • char
    • boolean

Enumeration Types

  • It allows programmers to define a set of named constants as a type
  • Examples:

    1
    2
    3
    4
    5
    6
    7
    8
    enum Day {MON, TUE, WED, THU, FRI, SAT, SUN};

    int main(){
    Day d = MON;
    if(d == MON){
    std::cout << "Monday" << std::endl; // Monday
    }
    }
  • Issues:

    1. Are enumeration values coerced to other types (int)?

      1
      2
      3
      4
      5
      6
      7
      enum Day {MON, TUE, WED, THU, FRI, SAT, SUN};

      int main(){
      Day d = SUN;
      // does the addition make sence? coerced to integer type
      std::cout << d + 1 << std::endl;
      }
    2. Any other type coerced to an enumeration type?

      1
      2
      3
      4
      5
      6
      7
      enum Day {MON, TUE, WED, THU, FRI, SAT, SUN};

      int main(){
      Day d = SUN;
      // can we assign integer to Day? coerced to enumeration type
      d = 123;
      }
  • Evaluation:

    1. Aid to readability

      • No need to code the Day, Color as a number
    2. Aid to reliability

      • No enumeration variable can be assigned a value outside its defined range, so make it as compilation error
      • No invalid operations
      • No invalid coercion (Java, C# does not coerced to integer type)

Array

  • Indexing
    • It is a mapping from indices to elements
      • array_name (index_value_list) → one or more elements
  • Index Types
    1. Typically integers only
    2. Usually starts with 0
      • R starts with 1
    3. Range checking
      • In Java, C#, Python
      • Not in C, C++
    4. Some languages allow negative indices
      • Python: reverse
  • Initialization

    • Character strings in C and C++

      1
      char name[] = "Doge";
    • Array of strings in C and C++

      1
      char* animals [] = {"Dog", "Cat", "Pig"};
    • String object in Java

      1
      String[] animals = {"Dog", "Cat", "Pig"};
    • Python - list comprehension

      1
      a_list = [x**2 for i in range(8) if x%2 == 0]
  • Array Operations
    • Python supports lots of operations, access for details.

Array Types

  1. Heterogeneous Array

    • the elements in an array need not be of the same type
      1
      2
      3
      4
      let myArray = ["Hello", 42, true,
      {name: "John", age: 30},
      function() {console.log("Hello from a function!")}
      ];
      1
      2
      3
      4
      my_list = ["hello", 42, True,
      {"name": "John", "age": 30},
      lambda: print("Hello from a lambda!")
      ]
  2. Rectangular array:

    • the arrays with multiple dimensions and each dimension has the same number of elements
      1
      int rectangular_array[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
      1
      int[][] rectangularArray = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
  3. Jagged array:

    • the arrays with multiple dimensions but each dimension can have a different number of elements
      1
      jagged_array = [[1, 2], [3, 4, 5], [6, 7, 8, 9]]
      1
      vector<vector<int>> jagged_array = {{1, 2}, {3, 4, 5}, {6, 7, 8, 9}};

Array Binding

  1. Static:

    • the size of array is fixed at compiler-time
    • the array is allocated a fixed memory location at compiler-time
    • Advantage: time efficiency (finish binding at compiler-time)
    • Disadvantage: inflexibility (cannot change the size at runtime)
  2. Fixed stack-dynamic:

    • the size of array is determined at runtime
    • the array is allocated on the stack (the memory for the array is freed when the function is returned)
    • Advantage: space efficiency (the memory for the array is allocated on the stack)
    • Disadvantage: inflexibility (cannot change the size at runtime)
  3. Fixed heap-dynamic:

    • the size of array is dynamically bound (but fixed onece the allocation is done) malloc
    • the array is allocated on the heap at runtime
    • Advantage: flexibility (the array is allocated on the heap)
    • Disadvantage: inflexibility (cannot change the size at runtime)
  4. Heap-dynamic:

    • the size of array is dynamically bound
    • the array is allocated on the heap at runtime
    • Advantage: highest flexibility (the size of array can be changed in runtime)
    • Disadvantage: low efficiency

Implementation of Array

  • Access function for single-dimensioned arrays:

    • Here are total 3 calculation operations
  • Access multi-dimensional arrays:

    • Access function:

      • $\text{lbr}$: lower-bound row index
      • $\text{lbc}$: lower-bound column index
      • $\text{ubr}$: upper-bound row index
      • $\text{ubc}$: upper-bound column index
    1. Row major (Most languages):

    2. Column major (Fortran):

Associative Arrays

  • In Python:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    # Dictionary
    doge = {"name": "Kabosu", "gender": "Female", "age": 16}

    # Access
    doge["name"] # Kabosu

    # Subscripting
    doge["age"] = doge["age"] + 1

    # Remove elemen
    del doge["age"]
  • In Perl:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    # Hash begins with %
    %temps = ("Mon" => 27, "Tue" => 29, "Wed" => 25);

    # Access
    $temps{"Wed"}; # 25

    # Subscripting
    $temps{"Wed"} = $temps{"Wed"} + 1;

    # Remove elemen
    delete $temps{"Tue"};

Tuples

  • a data type similar to a heterogeneous array, but it is immutable 不可改變的
    1
    2
    3
    4
    5
    6
    7
    # Declaration and Assignment
    t = (3.1415, "XD", 678)

    t[0] = 3 # error! it is immutable

    # Creating the new tuple
    t = t + (2,) # (3.1415, "XD", 678, 2)
  • it is used in Python, F# to allow functions to return multiple values
    1
    2
    3
    4
    5
    6
    7
    def f(a,b):
    c = a + 1
    d = b * 2
    return(c,d)

    c, d = f(4, 6)
    print(c, d) # 5, 12
  • Return multiple values in C++

    • the following code can be executed but have a potential error

      1
      2
      3
      4
      5
      6
      7
      8
      9
      int* f2(int a, int b){
      int result[2];
      return result;
      }

      int main() {
      int* result = f2(1,2);
      std::cout << result[0] << result[1] << std::endl;
      }
      • When the array is returned, it would be decated to a pointer, but the result array is allocated on the stack, so the array is already destoried when the function is returned and the pointer returned by the function points to invalid memory.
    • Solution: using the dynamic heap variables

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      int* f2(int a, int b){
      int* result = new int[2];
      return result;
      }

      int main() {
      int* result = f2(1,2);
      std::cout << result[0] << result[1] << std::endl;
      delete[] result; // remember to delete the pointer
      }
    • Solution: using std::pair class

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      #include <utility>

      std::pair<int, int> f3(int a, int b){
      pair<int, int> result(a * 3, a + b);
      return result;
      }

      int main() {
      std::pair<int, int> result = f3(3, 4);
      std::cout << result.first << result.second << std::endl; // 9 7
      }

Records

  • a data structure that is used to store a collection of related values
  • the individual elements are identified by names

  • In languages that support OOP, data classes or record classes serve as records

    1
    2
    3
    4
    5
    public record Person(String name, int age) {}

    Person john = new Person("John", 30);

    System.out.println(john.name() + " " + john.age); // John 30
  • In C, C++, C#, records are supported with struct data type
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    #include <string>
    using std::string;

    struct Nice{
    int i;
    float f;
    string s;
    };

    int main(){
    Nice n{1, 1.2, "haha"};
    std::cout << n.i << " " << n.f << " " << n.s << std::endl; // 1 1.2 haha
    }

Implement of Records

Unions

  • user-defined data type in programming that allows storing multiple data types in the same memory location
  • uses the same memory location for all its members, which means that modifying one member can affect the other members

  • Examples:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    union VariantNumber{
    int i;
    float f;
    double d;
    };

    int main(){
    union VariantNumber num;
    num.i = 9;
    std::cout << num.i << std::endl; // 9
    num.f = 3.14;
    std::cout << num.f << std::endl; // 3.14

    std::cout << num.i << std::endl; // unexpected value
    }
  • Evaluation of Unions:

    1. Free unions are unsafe (do not allow type checking)
    2. Java and C# do not support because of the safety issues

Heap Management

Pointer

  • it stores the memory address of another variable or object in the program
  • it provides a power of indirect addressing and a possibility of heap memory management
  • Lifetime
    • a pointer is declared as a local variable within a function, then it is stored on the stack and destoried when the function is returned
    • a heap-dynamic variable is declared at runtime and remains valid until it is deallocated through delete
  • Pointer arithmetic
    • the process of performing arithmetic operations on pointers
      1
      2
      3
      4
      5
      6
      7
      8
      char* c = new char[5];
      std::cout << (void*)(c) << std::endl; // 0x1c39eb0
      std::cout << (void*)(c + 1) << std::endl; // 0x1c39eb1 (+1)

      int* p = new int[5]{1, 2, 3, 4, 5};
      std::cout << (p) << std::endl; // 0x1c39ed0
      std::cout << (p + 1) << std::endl; // 0x1c39ed4 (+4)
      std::cout << *(p + 1) << std::endl; // 2
  • Problems

    1. dangling pointers

      • a pointer points to a heap-dynamic variable that has been deallocated others
        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        class Dog{
        public:
        char* name;
        Dog(){ name = new char[5]{"doge"}; }
        // solution: override the copy construction
        ~Dog(){ delete [] name; }
        };

        int main(){
        Dog* a = new Dog;
        Dog* b = new Dog(*a); // it is a shallow copy of a
        delete a;
        std::cout << b->name << std::endl; // the name has already been deallocated
        return 0;
        }
    2. lost heap-dynamic variable

      • an allocated heap-dynamic variable that is no longer accessible (it would lead to memory leak)
        1
        2
        3
        int* p = new int;
        p = new int; // create a new int and force p points to it
        delete p; // cannot delete the new int that declared on the top
  • Solutions for dangling pointers

    1. Tombstone

      • adding an extra heap cell (a pointer) to the heap-dynamic variable

      1. the actual pointer variable points only at the tombstone (a middleware among the variable and pointers)
      2. when a heap-dynamic variable is deallocated, the tombstone remains but points to null
    2. Locks-and-keys

      • the pointer values are represents as (key, address) and the heap-dynamic variables are represents as (key, values)
      1. when a heap-dynamic variable is allocated and assigned to a pointer, a unique value is created and assigned to both pointer’s and variable’s key
      2. when we use the pointer to access the corresponding variable, it would compare the key value first to check whether the access is legal or not
      3. when the heap-dynamic variable is deallocated, the lock value is cleared to an illegal lock value to make sure it won’t be access

References

  • reference type variable is similar to pointer but it only refers to an object in memory instead of an address
    1
    2
    3
    4
    5
    String a = "haha";
    String b = a;
    String c = "hehe";
    b = c; // it would not change the value of a
    System.out.println(a); // haha
    1
    2
    3
    4
    5
    int a = 1;
    int& b = a;
    int c = 2;
    b = c; // it does change the value of a
    std::cout << a << std::endl; // 2

Implicit Heap Management

  • Reference Counter
    • maintain a reference counter in every cell, which stores the number of pointers currently pointing at the cell
    • when a pointer is disconnect from the cell, the counter is decreased by one and check for the zero value
    • if the counter value is 0 which means no pointers are pointing to it, then it would deallocate the memory