Data Types
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
Javasigned integer sizes:byte(1 bytes),short(2 bytes),int(4 bytes),long(8 bytes)C/C++signed integer sizes are not fixedPython: 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
5print(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:
- Accuracy
- Disadvantages:
- Limited range
- Memory waste
Boolean
true,falseC99andC++allow numeric expressions to be used as Boolean, butJavaandC#do not because of the reliability1
2
3
4
5
6int main(){
int j = 0;
if(j = 1){
std::cout << "GG" << std::endl;
}
}Advantages:
- Readability
- Reliability
Character
- Stored as numeric codings (ASCII standard and Unicode not standard)
- Noted:
Pythondoes not have Character type (it is a string of one length)
Character String Types
A sequences of characters
Typical Operations:
- Assignment and copying
- Comparasion (ascending/descending)
- Concatenation
- Substring reference
- Pattern matching
String Types in Languages:
CandC++- Not primitive, use char arrays and a library of functions provides operation
JavaandC#- Not primitive, use the String class
FortranandPython- Primitive type with assignment and serveral operations
PerlandJavaScript- Provide built-in pattern matching (regular expression)
String Length Options:
Static length in
Python,JavaString class- It only need a compile-time descriptor for the length
Limited dynamic length in
CandC++char arrays (\0indicates 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
14int 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!
}
- It may need a run-time descriptor for the length and maximum length
Unlimited dynamic length in
Perl- It must need a run-time descriptor for the length and maximum length
- Linked-list
- Adjacent storage cells
- It must need a run-time descriptor for the length and maximum length
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:
intcharboolean
Enumeration Types
- It allows programmers to define a set of named constants as a type
Examples:
1
2
3
4
5
6
7
8enum Day {MON, TUE, WED, THU, FRI, SAT, SUN};
int main(){
Day d = MON;
if(d == MON){
std::cout << "Monday" << std::endl; // Monday
}
}Issues:
Are enumeration values coerced to other types (
int)?1
2
3
4
5
6
7enum 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;
}Any other type coerced to an enumeration type?
1
2
3
4
5
6
7enum 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:
Aid to readability
- No need to code the Day, Color as a number
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
- It is a mapping from indices to elements
- Index Types
- Typically integers only
- Usually starts with 0
Rstarts with 1
- Range checking
- In
Java,C#,Python - Not in
C,C++
- In
- Some languages allow negative indices
Python: reverse
Initialization
Character strings in
CandC++1
char name[] = "Doge";
Array of strings in
CandC++1
char* animals [] = {"Dog", "Cat", "Pig"};
String object in
Java1
String[] animals = {"Dog", "Cat", "Pig"};
Python- list comprehension1
a_list = [x**2 for i in range(8) if x%2 == 0]
- Array Operations
Pythonsupports lots of operations, access for details.
Array Types
Heterogeneous Array
- the elements in an array need not be of the same type
1
2
3
4let myArray = ["Hello", 42, true,
{name: "John", age: 30},
function() {console.log("Hello from a function!")}
];1
2
3
4my_list = ["hello", 42, True,
{"name": "John", "age": 30},
lambda: print("Hello from a lambda!")
]
- the elements in an array need not be of the same type
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}};
- the arrays with multiple dimensions and each dimension has the same number of elements
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}};
- the arrays with multiple dimensions but each dimension can have a different number of elements
Array Binding
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)
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)
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)
- the size of array is dynamically bound (but fixed onece the allocation is done)
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
Row major (Most languages):
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 values1
2
3
4
5
6
7def 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
9int* 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
resultarray 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.
- When the array is returned, it would be decated to a pointer, but the
Solution: using the dynamic heap variables
1
2
3
4
5
6
7
8
9
10int* 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::pairclass1
2
3
4
5
6
7
8
9
10
11
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
5public 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 withstructdata type1
2
3
4
5
6
7
8
9
10
11
12
13
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
15union 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:
- Free unions are unsafe (do not allow type checking)
JavaandC#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
8char* 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
- the process of performing arithmetic operations on pointers
Problems
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
15class 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;
}
- a pointer points to a heap-dynamic variable that has been deallocated others
lost heap-dynamic variable
- an allocated heap-dynamic variable that is no longer accessible (it would lead to memory leak)
1
2
3int* 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
- an allocated heap-dynamic variable that is no longer accessible (it would lead to memory leak)
Solutions for dangling pointers
Tombstone
adding an extra heap cell (a pointer) to the heap-dynamic variable

- the actual pointer variable points only at the tombstone (a middleware among the variable and pointers)
- when a heap-dynamic variable is deallocated, the tombstone remains but points to null
Locks-and-keys
- the pointer values are represents as (key, address) and the heap-dynamic variables are represents as (key, values)

- 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
- 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
- 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
- the pointer values are represents as (key, address) and the heap-dynamic variables are represents as (key, values)
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
5String a = "haha";
String b = a;
String c = "hehe";
b = c; // it would not change the value of a
System.out.println(a); // haha1
2
3
4
5int 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


