Unix/Linux
Basic Commands
The commands you will use the most will probably be the ones that orientate you in a system.
To figure out where you are, use the command pwd. This will tell you the path from root to where you are now. If you own or have admin privileges on a server you will probably start at the root. If not, you often start at the level where you have been given access.
An absolute path starts from the root directory and is given in full.
A relative path starts from your current directory and uses certain operators to change where you’re currently looking.
pwd command gives us our absolute path.
Basic Commands
Once you know where you are, it’s good to see what’s there. Use ls command to see all the files in the directory.
Ls option flags:
-a
–List ALL things – do not ignore entries that start with a ‘.’
-l
–List things in a long format showing properties, timestamps, etc
Combine them ls –al or ls –a –l
Basic Commands
When you know where you are and what’s around you, you can move around with the cd command.
–cd
changes the path to that specific thing
-cd
Looks for that directory in your current directory so you dont have to type the full path. You can also do multiple at a time if you know where they are:
cd CSE220/Homework … This will look for CSE220 in your current directory then look for Homework directory inside CSE220.
–cd ..
change path the to parent
–cd ~
change path to the user’s home directory
Other Useful Commands
–mkdir CSE220
Create a new directory named CSE220 in the current directory
–mv
This command moves a file from one location to another and gives you the opportunity to rename it
mv test.txt ~/CSE220/Assn1/V2/test.t (File now named test.t)
–cp
Copy File: This pretty much works the same way mv does
-rm
Remove a file or many, doesnt work on directories without extra option flags: *, removes everything that is not a directory. *-r,removes everything
–help will generally get you info on any command
Other Useful Commands pt 2
3 types of File permissions: R=read,W=write,X = execute
Chmod changes file permissions. It can add or take them away
– chmod
To view files, use the “cat” command. This just dumps all text in a file to the console
-cat
Piping is a command that works like an operator: left hand side computes and gets used as the arguments for the right hand side
-ls –l | less :this command takes the long version of ls and pipes it into the less command which lets us scroll through the list 1 page a time.
–grep
grep searches a file for a pattern match and return the line it exists in
A Little On Shell Scripting
By convention shell script files end with .sh.
Really all you have to do is create a file, then make it executable with chmod +x
File should begin with: “#!/bin/bash”, this is to make sure the script is ran with the bash shell.
Commands in the script will be executed in order.
Example:
If/Else statements
Begin with “if”, followed by conditional inside of [ ], make sure to leave a space after the first bracket and before the last bracket.
After conditional we use “then”, followed by what you want to do.
Then we can use “else” for an else condition or “elif” followed by a conditional for an else if.
Use “fi” to end the if statement.
If/Else Example
Math
Doing Math
The shell can only do INTEGER math!!
Math is performed via a parentheses notation, brackets or let:
$((
Functions
Use the function keyword and {} to define the body
Parameter passing is via position and not explicitly done through syntax like other languages
Parameters are stored in $# order based on position
The local keyword makes a variable local to a function: local result=0
Return is more for throwing error codes and just marks the end of a function. Try storing needed values in parameters or capturing the output in a variable: RESULT=$(myFunction).
Function Example
Loops
Basic loop syntax:
while [ condition ];
do
Commands
done
NOTE****
condition does not become false
When value of conditional == 0.
If i did while [ $COUNTER ]:
This would be an infinite loop.
Evaluating a Language
Reliability How well does it perform to specification?
Readability How easily can the language be read and understood?
Writability How easily can someone write in the language
Reusability How easily can code be reused and shared?
Efficiency How fast is the code and the compiler?
Simplicity/orthogonality ∙ ∙ ∙ ∙
Control structures ∙ ∙ ∙ ∙
Data types & structures ∙ ∙ ∙ ∙
Syntax design ∙ ∙ ∙
Support for abstraction ∙ ∙ ∙
Expressivity ∙ ∙
Strong/weak type checking ∙
Exception handling ∙
Restricted aliasing/pointer ∙
Efficiency Readability Writability Reliability
Reusability
Characteristics
Performance metrics
Evaluating a Language
Orthogonality
Combinational Many to Many Relationship
Sort One to Many Relationship
Number If one instance exists, any number can exist
Combinational Orthogonality – I have commands S1 and S2; If S1_a combines with S2_a, then S1 combines with all S2 commands
-Creating a variable, combines idea of variable creation and data types
Sort Orthogonality – I have commands S1 and S2; If S1_a combines with S2_a, then S1_a combines with all S2 commands
-If I can create a variable of a type that implies I should also be able to initialize it, make a constant and make an array
Number Orthogonality – When I have the ability to use a command somewhere, that implies I can use zero or more of that command in the same place
-Classes are an example, like those seen in Java in CSE205
‹#›
Programming Paradigms
Imperative/Procedural fully specified/controlled manipulation of named data in a step-wise fashion
Object-Oriented Encapsulation of state of the program in objects, which can be accessed only through operations defined on them. Also includes: Inheritance and Polymorphism
Functional/Applicative Higher level abstraction, simpler semantics, closer to math functions and referential transparency
Logic/Declarative set of facts about objects, rules about objects, and defining and questioning relations between objects. Get rid of programming altogether
Service-Oriented Programming Runs as a service, listening for connections and fulfilling requests (designed around networks)
Expression of Programs
Lexical Basic building blocks
Is the stuff its built of right?
For the purposes of this class we bundle this error with Syntactic for the most part so know it but do not expect it to be the correct answer.
Syntactic How lexical units are assembled.
Is the statement valid (BNF)?
Is it built correctly?
IF YOUR CODE DOES NOT COMPILE, YOU HAVE A SYNTAX ERROR
Contextual The structure of the semantics, the building blocks of the code.
Do data types do what you need them to? Did your code compile and run, but not give you a correct output?
Is it built from the right stuff?
EX) used integers when you need float/double, using Kilometres instead of Miles.
Semantic The overall meaning… is the logic correct? Did you code compile then bug during runtime?
Is the code doing what I want it to?
Syntactic Analyses: Syntax Graph
A language can also be defined by a syntax graph
if (condition) statements ;
else statements ;
if (a < 0) return -a;
if (a < 0) return -a; else return a;
switch (expr) { case value: statements ;
default: statements;
}
switch (ch) {
case '+': x = a + b; break;
case '-': x = a - b; break;
case '*': x = a * b; break;
case '÷': x = a / b; x = round(x); break;
default: printf("invalid operator"); break;
}
Does a while-loop’s syntax graph have a loop?
Very Simple Programming Language (VSPL)
Example: Define a Very Simple Programming Language (VSPL)
< expr > ::= < variable>
| (
Functions
Forward Declaration: return type Name(parameter types)
Example: float distance(double, double, int, int)\
Lets C/C++ know the functions exist
Macros: #define (a>b)?a:b – a++ – (a++>b)?a++:b
The programmer decides if to optimize the program;
The programmer is responsible for the correctness;
Macro is a forced in-lining and the programmer can predict the performance.
Side effects with using post/pre-increments
In-lining: inline
The compiler decides if to optimize the code;
The compiler is responsible for the correctness;
Programmer does not know if the optimization is done and cannot predict the performance.
Functions:
Uses a stack frame and memory to execute some value.
It does not replace code
Data – Key Concepts
Type: what values and operations are allowed. This also tells us the size of the object which is important for addressing.
Location: where data are stored in memory
Address: an integer associated to a location
Reference/pointer: a name associate with the variable that holds an address of a location
Variable name: a name associated with a location
Value: what stored in a memory location
Scope: (lifetime) and visibility
Data Types – 32bit
pointer (32bit) 4bytes
pointer (64bit) 8bytes
Should be “signed long long int”, not “signed long int”
Pointers
What is a pointer? A variable consisting of:
The starting point of the address of the variable it is pointing to.
A Type, the same type as the object it is pointing to. This lets the pointer know where the object ends in memory.
An address for itself – the pointers own location in memory
A name – an easy way to reference the variable, for humans only.
What are the two pointer-specific operations?
& is a referencing function that returns the address value of the variable it precedes, allows us to set what a pointer is pointing at
* represents the name of the memory location of the address it precedes, allows access to the data stored where the pointer is pointing
EXAMPLE:
int num = 7;
int* intPtr = # //now intPtr is pointing at x
(*intPtr)++; //here we are returning the object intPtr points to, then incrementing
cout << *(intPtr) << " " << num; //outputs 8 8
//because they are pointing to the //same variable
Arrays and Strings
Arrays are sequential blocks of memory that can store more than one of the same data type
In C, a string is an array of characters where the last index is ALWAYS the null char ‘\0’
Can be reference and manipulated similar to Java
Note: C does not prevent going out of bounds, so the programmer must be careful when getting and setting data
char name[10];
char name[] = {‘M’, ‘i’, ‘k’, ‘e’}; Size 4
char name[] = “Mike”; Size 5 – invisible ‘\0’ character because it’s a string
The Magic of Arrays
Because arrays are sequential blocks of the same type of memory, [] are actually just “syntactic sugar” for manipulating data in arrays
char name[2];
char* p = name;
*p = ‘H’;
p++;
*p = ‘i’;
//Sets name[] = “Hi”;
Dynamic Allocation
Allows for the creation of arrays with length undetermined at runtime
NOT the same as variable length arrays, the size still can’t be changed once created
Must be released after use, otherwise it becomes a memory leak
C:
int* myArray = (int*)malloc(length*sizeof(int));
//in C you do not need the (int*) in-front of malloc but if you want //it to compile in a C++ program you need to.
free myArray;
C++
int* myArray = new int[length];
delete[] myArray;
Multidimensional Allocation
Remember when you build a multi dimensional array you need a pointer level for each dimension and you are building arrays of arrays
Effectively, each layer other than the base is just pointers pointing to the sublayer
C
int** my2D = (int**)malloc([Y_DIM]*sizeof(int*));
for(int i = 0; i < Y_DIM; i++)
my2D[i] = (int*)malloc([X_DIM]*sizeof(int))
C++
int** my2D = new int*[Y_DIM];
for(int i = 0; i < Y_DIM; i++)
my2D[i] = new int[X_DIM];
Multidimensional Deletion
Deletion follow a similar patter to creation, but has a bigger risk of memory leaks due to each sub-array needing to be deleted
C
for(int i = 0; i < Y_DIM; i++)
free(my2D[i]);
free(my2D);
C++
for(int i = 0; i < Y_DIM; i++)
delete[] my2D[i];
delete[] my2D;
The issue with sizeOf
Great for normal arrays, not so great for dynamically created arrays
int* myArray = new int[10]; //40 bytes of ints right?
cout << sizeof(myArray) << endl; // output ... 4 ...
To C, the program asked for the size of a pointer, not an array
THE HEAP
Dynamically allocated memory is located on the heap
C isn’t nice like Java is, garbage collection doesn’t occur unless your program ends
Memory on the heap must be freed else memory leaks(waste) occur
Function Parameters
Know your parameter passing differences
Reference – passes the memory (C++ only)
int doStuff(int &val);
int doStuff(const int &val); //constant trades mutability for safety
Pointer – passes a pointer to the memory
void doStuff(int* val);
Value – passes a copy
void doStuff(int val);
* Notice that passing by pointer is really just passing a pointer by value
‹#›
Function Parameters
Pass by value when a function does not want to modify the parameter and the value is easy to copy (simple data types and certain things like strings)
Pass by constant pointer when
the value is expensive to copy
the function DOES NOT want to modify the value pointed to
NULL is valid and expected and handled
Pass by pointer when
the value is expensive to copy
the function WANTS to modify the value pointed to
NULL is valid and expected and handled
Pass by constant reference when (C++ only)
the value is expensive to copy
the function DOES NOT want to modify the value
NULL is not valid
Value might not be addressed
Pass by reference when (C++ only)
the value is expensive to copy
the function DOES want to modify the value
NULL is not valid
‹#›