Reference Sheet for CO120.3 Programming III

Summer 2017

Basic Types

Note: Try to keep functions under 40 lines long. Remember to include void in your parameter list for functions without parameters.

1. Don't use the char, short, int and long types. In order to increase portability and readability, use stdint.h. Included types are: uint8_t, uint16_t, uint32_t, uint64_t, int8_t, int16_t, int32_t, int64_t.

Variables Note: In general, you should initialise variables at point of denition. Example:

4.0}}.

double numbers[2][3] = {{1.0, 2.0, 3.0}, {2.0, 3.0,

A string can be represented as an array of type char, ending with `/0'. Example: uint8_t hello[] = "Hello!".

Enumerated Types Example: /** * @brief An enum type that represents flags for rendering. * * Each bit represents a different flag. Use bitwise and * to check if a flag is set. */ enum render_flag { /** The ambient flag (bit 0). */ AMBIENT = 1, /** The diffuse flag (bit 1). */ DIFFUSE = 2, /** The specular flag (bit 2). */ SPECULAR = 4, };

Flow of Control 1. Always use braces where it is possible to do so. 2. Leave a space and after the opening and closing parentheses for the condition, respectively. Note: You should usually break at the end of each case in a switch statement. Examples: if (condition) { statement; ... } else if (condition) { ... } else { ... }

Functions 1. Use underscore_separation for function names.

while (condition) { ... }

2. Don't put a space between the function name and parameter list. 3. Never leave the parameter list for a function empty.

for (initialiser; condition; increment / decrement) { ... }

4. Leave a single space between the closing parenthesis of the parameter list and the opening brace of the function body. 1

Pointers

switch (expression) { case constant1: ... break; case constant2: ... break; default: assert(false); }

1. When declaring a pointer, place the * adjacent to the variable name, not the type. 2. When passing by reference, pointers must be declared as const. Example: int *pointer, NOT int* pointer or int * pointer. Note: Use the const keyword wherever possible. Examples: int val = 5; // Value cannot be modified const int *ptr1 = &val; // Pointer cannot be modified int const *ptr2 = &val; // Neither value nor pointer can be modified const int const *ptr3 = &val;

Logical Expressions 1. Place constants before variables when using the equality operator. Note: Use parentheses to clarify precedence in complex expressions. Example: 3 == x, NOT x == 3.

Input Output Use printf to print to standard output. Sanitise using: - %c for character. - %d for signed integer. - %u for unsigned integer. - %o for octal. - %x for hexadecimal. - %f for oating point value. - %e for oating point value using scientic notation. - %s for string. - %p for pointer value. Use scanf to read from standard input. Beware of secuirity risks when inputting, say, a string. You can use fgets instead. Examples:

Think of * as an operator that takes an address and returns the value which it points to. & is an operator that takes a value and returns its address. We can also use function pointers to pass functions be reference. Example: /** * @brief A function which sums its two inputs. */ int sum(int a, int b) { return a + b; }

int i; int ret = scanf("%i", &i); assert(1 == ret); char buffer[100]; int size = sizeof(buffer); fgets(buffer, size, stdin);

/** * @brief A main function which does nothing. */ int main(void) { int (*sum_pointer)(int, int) = ∑

Bitwise Operations ˆ & for bitwise AND.

return EXIT_SUCCESS;

ˆ | for bitwise OR.

}

ˆ >> for RIGHT SHIFT.

Command Line Arguments main can have a type signature where it receives arguments from the command line:

ˆ << for LEFT SHIFT. ˆ ~ for bitwise NOT.

ˆ argc, the number of passed parameters.

ˆ  for bitwise XOR.

ˆ argv, an array of strings.

2

Makele Example:

The rst argument is the name of the le! Example:

# Set the flags for the C compiler CFLAGS = -Wall -pedantic -std=c99

/** * @brief A main function which prints its command line arguments. */ int main(int argc, char **argv) { for (int i = 0; i < argc; i++) { printf("argv[%i] = %s\n", i, argv[i]); } return EXIT_SUCCESS; }

# Build rule for final executable sum: add.o # Build rules for the .o files sum.o: add.h add.o: add.h # Rule to clean generated files clean: rm -f sum sum.o add.o

Memory Management

# Tell make that 'clean' is not a real file .PHONY: clean

1. main should only return EXIT_SUCCESS or EXIT_FAILURE.

More Variables

ˆ stlib.h's void *malloc(size_t size) allocates a region of memory of size bytes and returns a pointer to the allocated memory.

ˆ static (local): value is retained. ˆ static (top level): only seen within this le.

ˆ void free(void *ptr) frees a previously allocated memory region.

ˆ extern variables: dened in header, can be used in multiple les.

ˆ You need to check that these don't fail (not NULL).

ˆ Global variables: try to avoid them.

ˆ string.h's void *memset (void *s, int c, size_t n) sets teh n-byte region starting at s to c.

File Input

ˆ void *memcpy(void *dest, const void *src, size_t n) copies n bytes from src to dst, returning dst.

ˆ Use FILE fopen(const char *path, const char *mode).

ˆ You can use the memcheck tool provided by valgrind to check for memory

ˆ Need to check le could be opened (not NULL).

ˆ Modes are r to read from start, w to write from start, a to append.

leaks.

ˆ Use int feof(FILE *stream) to check if end of le has been reached

(NULL).

Assertions assert.h provides assert(logical_expression).

ˆ Use int fclose(FILE *fp) to close le. ˆ Need to check it doesn't fail.

Headers

Reading a le:

1. All headers should be surrounded by include guards, #ifndef THIS_H, #define THIS_H.

ˆ int fscanf(FILE *stream, const char *format, ...).

Note: In general, every .c le should have an associated .h le.

ˆ char *fgets(char *s, int size, FILE *stream).

3

Constants Three approaches:

Writing to a le: ˆ int fprintf(FILE *stream, const char *format, ...).

1. Use a marco using #define.

ˆ int fputs(const char *s, FILE *stream).

2. Dene a global static const variable (not a true constant).

Binary data:

3. Use an unnamed enum.

Strings Use string.h to get:

ˆ Use the mode b. ˆ size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)

ˆ size_t strlen(const char *s).

ˆ size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)

ˆ int strncmp(const char *s1, const char *s2, size_t n).

ˆ char *strncat(char *dest, const char *src, size_t n).

ˆ char *strncpy(char *dest, const char *src, size_t n).

ˆ ptr is the address to read or write, nmemb is the number of elements, size

is the number of bytes for each element.

Tips for Lexis Tests Make sure you check for all errors and initialise variables

ˆ Need to check returned value is the number of elements.

immediately. In particular:

Error checking: You can also use int ferror(FILE *stream). Printing errors:

ˆ All functions with a pointer as an argument should check that the given

pointer is not NULL.

ˆ Any memory that you malloc must be checked not NULL and should be

initialised immediately to 0.

ˆ Use perror(char *msg) when printing non user dened errors. ˆ Otherwise, use fprintf(stderr, char *msg).

Structs Example: /** * @brief A struct that hold the co-ordinates of a 2D vertex. */ typedef struct { /** The x co-ordinate */ float x; /** The y co-ordinate */ float y; } vertex; ˆ Use . to refer to a struct component. ˆ Use -> to refer to a struct component from a pointer to a struct.

Use typedef to declare an alias for an existing type. Use a union where requirements to store components are mutually exclusive. 4

Reference Sheet for CO120.3 Programming III - GitHub

GBB. B d˜rief en enum type th—t represents fl—gs for renderingF. B. B i—™h ˜it represents — different fl—gF …se ˜itwise —nd. B to ™he™k if — fl—g is setF. BG enum render•fl—g {. GBB „he —m˜ient fl—g @˜it HAF BG ewfsix„ a ID. GBB „he diffuse fl—g @˜it IAF BG hspp…ƒi a PD. GBB „he spe™ul—r fl—g @˜it PAF BG.

69KB Sizes 0 Downloads 306 Views

Recommend Documents

Reference Sheet for CO120.2 Programming II - GitHub
Implementing Interfaces Use notation: @Override when a class method im- ... Style: usually a class extends an abstract class (with constructor and fields).

Oolite Reference Sheet - GitHub
will shut down, requiring a cool-down period before it ... 10 Fuel Scoop ... V2 & Creative Commons License: BY - NC - SA 3.0 Oolite Website: http:/www. ..... A discontinued fighter design finding a new life in the professional racing circuit.

Reference Sheet for CO140 Logic - GitHub
Free Variable Variable which is not bound (this includes variables which do not appear in A!). Sentence Formula with no free variables. ... domain of M, dom (M).

Reference Sheet for C112 Hardware - GitHub
Page 1 ... We might be able to make a considerable simplification by considering max- terms (0s) instead of minterms. • Don't cares (X) can ... Noise Margin. Fan out The number of inputs to which the output of a gate is connected. • Since 1. R.

Reference Sheet for CO130 Databases - GitHub
create table actor_cars ( .... Table. Relational Expression. Views. Tuple. Row. Attribute. Column. Domain .... end of free space, location and size of each record.

Reference Sheet for CO120.1 Programming I
Stops execution and displays error message. 9 Types and Common ... multiple times or to clean up code. ... You should spend time planning your answer (on ...

Reference Sheet for CO142.1 Discrete Mathematics I - GitHub
Products For arbitrary sets A and B: 1. Ordered ... Identity idA = {〈x, y〉 ∈ A2|x = y}. Composition .... Identity: The function idA : A → A is defined as idA (a) = a. 3.

Reference Sheet for CO141 Reasoning about Programs - GitHub
General Technique: For any P ⊆ Z and any m : Z: P (m) ∧ ∀k ≥ m. [P (k) → P (k + 1)] → ∀n ≥ m.P (n). 1.2 Strong Induction. P (0) ∧ ∀k : N. [∀j ∈ {0..k} .

Reference Sheet for CO142.2 Discrete Mathematics II - GitHub
Connected: there is a path joining any two nodes. .... and merge two components .... Merge sort can be parallelised by executing recursive calls in parallel. 2.

Location Reference Sheet for writers.pdf
There was a problem previewing this document. Retrying... Download. Connect more apps... Try one of the apps below to open or edit this item. Location ...

CSS3 Cheat Sheet - GitHub
Border Radius vendor prefix required for iOS

gitchangelog Cheat Sheet - GitHub
new: test: added a bunch of test around user usability of feature X. fix: typo in spelling my name in comment. !minor. By Delqvs cheatography.com/delqvs/. Published 14th August, 2017. Last updated 14th August, 2017. Page 1 of 1. Sponsored by ApolloPa

Programming TCP for responsiveness - GitHub
for data that couldn't be stored in TCP send buffer ... packet (wasting packets during slow start!) ⁃ overhead of TLS header & HTTP frame becomes bigger. 5 ...

Reference Manual - GitHub
for the simulation of the electron cloud buildup in particle accelerators. 1 Input files .... points of the longitudinal beam profile of sec- ondary beams.

NetBSD reference card - GitHub
To monitor various informations of your NetBSD box you ... ifconfig_if assigns an IP or other on that network in- ... pkg_admin fetch-pkg-vulnerabilities download.

Programming - GitHub
Jan 16, 2018 - The second you can only catch by thorough testing (see the HW). 5. Don't use magic numbers. 6. Use meaningful names. Don't do this: data("ChickWeight") out = lm(weight~Time+Chick+Diet, data=ChickWeight). 7. Comment things that aren't c

Machine Learning Cheat Sheet - GitHub
get lost in the middle way of the derivation process. This cheat sheet ... 3. 2.2. A brief review of probability theory . . . . 3. 2.2.1. Basic concepts . . . . . . . . . . . . . . 3 ...... pdf of standard normal π ... call it classifier) or a decis

LIKWID | quick reference - GitHub
likwid-memsweeper Sweep memory of NUMA domains and evict cache lines from the last level cache likwid-setFrequencies Control the CPU frequency and ...

J1a SwapForth Reference - GitHub
application. After installing the icestorm tools, you can .... The SwapForth shell is a Python program that runs on the host PC. It has a number of advantages over ...

GABotS Reference Manual - GitHub
Apr 9, 2002 - MainWindow (Main widget for the GABots app). 23. Random ..... Main class for simple Genetic Algorithm used in the program. ز ذظ .

RTOS Threading Cheat Sheet - GitHub
If the UART is enabled, it causes a data frame to start transmitting with the parameters indicated in the. UARTLCRH register. Data continues to be transmitted ...

R Markdown : : CHEAT SHEET - GitHub
Word, or RTF documents; html or pdf based slides ... stop render when errors occur (FALSE) (default = FALSE) .... colortheme. Beamer color theme to use. X css.

RN-171 Data Sheet - GitHub
Jan 27, 2012 - 171 is perfect for mobile wireless applications such as asset monitoring ... development of your application. ... sensor data to a web server.

Go Quick Reference Go Quick Reference Go Quick Reference - GitHub
Structure - Package package mylib func CallMeFromOutside. Format verbs. Simpler than Cās. MOAR TABLE package anothermain import (. "fmt". ) func main() {.