Introduction to C and the Development Workflow
In questa pagina 8
Course goals (from the introduction deck)
- Write correct and efficient algorithms in C with loops, conditionals and basic algorithms.
- Understand the link between C and its execution environment: compilation, assembly, linking (see Compilation, Linking and ExecutionHow a C source file becomes a running program: editing, preprocessing, compiling, linking, plus interpreters versus compilers and static versus dynamic linking.Compilation, Linking and Execution →).
- Formalize specifications with pre- and post-conditions.
- Advanced C: data structures, pointers, memory management, sockets.
- Design a whole project with readable, modular, maintainable code; know the main similarities and differences with C++.
- Exam: written lab part (50%, produce software and answer questions) + individual project discussed orally (50%). Correctness, organization, efficiency and style are evaluated.
Computer architecture in brief
- Everything in a computer (data and programs) is a sequence of 0s and 1s (binary, base 2). A program must be in memory to run.
- Writing programs directly in binary is impractical, so tools translate a higher-level description into machine code.
- Von Neumann architecture
- RAM: sequence of bytes (1 byte = 8 bits), each with an address from 0 to N-1. Readable and writable.
- CPU: executes machine-language programs by repeating the cycle access (fetch), decode, execute.
- Secondary memory (permanent, survives power-off) and input/output devices.
- Memory hierarchy: registers (fastest, smallest, inside the CPU), cache L1/L2/L3, RAM, disk (HDD/SSD: biggest, slowest).
- CPU = control unit + ALU (arithmetic and logic operations) + registers; modern CPUs have several cores.
- Layers: hardware machine (circuits doing AND, OR, NOT) -> operating system -> compilers and applications. High-level languages describe operations more simply than machine language, and compilers translate them.
- Machine language gives: transfers RAM <-> CPU registers, arithmetic on registers, compare and jump, end-of-program. Programs are built from three constructs: assignments (compute and store), tests (conditional continuation), loops (repeat until a condition holds).
Data are bits plus an interpretation
- Information = data + interpretation: since everything is bits, you must always know the coding used to read or write a value.
- Positive binary:
101011= 1 + 2 + 8 + 32 = 43 (each bit weighs a power of 2). - n bits give 2^n combinations; the largest unsigned value is 2^n - 1. A result beyond the maximum is an overflow.
- Signed integers: leftmost bit is the sign (0 positive, 1 negative); negatives are in two's complement: add 2^n and write the result in standard form. Example n = 5: -7 = 32 - 7 = 25 =
11001. sizeof(int)gives the bytes of an int (4 or 8 depending on architecture);<limits.h>hasINT_MAX,INT_MIN, ...- The slide asks: with a 1-byte int, INT_MAX = 127, so what is INT_MAX + 1? By the two's complement rule above, 128 wraps to the pattern
10000000, that is -128. - C does not check overflow on additions: it is the programmer's job.
- Reals use floating point (IEEE 754: single precision 32 bit =
float, double 64 bit =double). Because precision is finite, comparing two equivalent real expressions with==can give false (intermediate rounding). Details of types in Primitive Data Types and ExpressionsC data types (basic, derived, enum, struct and union, void, bool), arithmetic, comparison, logical and bitwise operators, type conversions and the rules for evaluating expressions.Primitive Data Types and Expressions →.
Algorithms and specification
- Algorithm: ordered, finite set of elementary, unambiguous instructions to solve a problem. Three items (problem, instructions, solution) and two actors (who writes the instructions, who executes them).
- A problem decomposes into sub-problems; here problems/sub-problems are called functions (see Functions, Variables and ScopeHow to declare variables, define and call functions with prototypes and return values, pass arguments by value or through pointers, and use function pointers.Functions, Variables and Scope →).
- Steps to create an algorithm: decide starting point, find the ending point, list the steps from start to finish, decide how to accomplish each step, review.
- Formalizing the problem: describe inputs and outputs unambiguously.
- Precondition (PRE): what is assumed about the input (for which inputs a solution is guaranteed).
- Postcondition (POST): an assertion (true/false formula) saying what the code computes.
- Example: square root of x: PRE
x>=0, POST return y such thatx=y*y.
- Ideate the algorithm first, in a natural language, with freedom on elementary operations. Example: sort a list: while the unordered list is not empty, select the minimum of the unordered list and move it to the end of the sorted list (10, 7, 14, 3, 18, 1 -> 1, 3, 7, ...).
- Then implement it: know the language's basic instructions and express the solution with them. Doing the two steps separately keeps the difficulty under control.
- Correctness: after implementing, give evidence the program reaches the postcondition (unit tests, correctness tests); if wrong, analyze it with the debugger.
- Beyond correctness, programs are compared on: efficiency (time and space), organization (write well-made code once and reuse it), style (understandable to colleagues and to yourself months later).
Programming languages
- Low-level (machine language): architecture-dependent, instructions very basic.
- High-level: new instructions implemented over machine language and translated automatically by a compiler. If the architecture changes, only the translator must be provided (and programs retranslated).
- Desired characteristics: simple translator (few primitive instructions) and powerful language (you can build new "instructions", the functions, collected in libraries: knowing them saves time).
- Examples: C, C++, Java, Python.
- C: developed in 1970 by Ken Thompson and Dennis Ritchie when memory was in the order of KB and efficiency was the goal; close to low-level languages; specification published in 1978; standardized as ANSI C. It balances two conflicting goals: more checks against user errors versus efficiency ("do not trust the programmer" versus staying fast). C was written to develop Unix; used for systems-level and embedded software.
- C++: mid 1980s, Bjarne Stroustrup (AT&T Bell Labs); extension of C, first with object-oriented features then generic programming; can reuse C code.
- Interpreter vs compiler is in Compilation, Linking and ExecutionHow a C source file becomes a running program: editing, preprocessing, compiling, linking, plus interpreters versus compilers and static versus dynamic linking.Compilation, Linking and Execution →.
First program
c
#include <stdio.h>
int main () {
/* our first program that
prints the string "Hello world!" */
printf("Hello world!\n"); // \n represents a newline
}- A C program is made of functions (statements specifying the computation) and variables (values used in the computation).
mainis special: every program starts executing at the beginning ofmain; every C program must have it.#include <stdio.h>tells the compiler to include information about the standard I/O library (needed forprintf).- Arguments are values the caller gives to a function, in parentheses after its name;
main()here expects none (empty list). - Statements of a function are enclosed in braces
{ }; statements end with;; strings go between" ". \nis a single character. Escape sequences:\ttab,\bbackspace,\"double quote,\\backslash. An unknown escape like\cgives a warning (unknown escape sequence).- Comments: text between
/*and*/is ignored by the compiler and may appear wherever a blank, tab or newline may;//runs to the end of the line. They must help the reader understand quickly: not trivial (3+2; //add 3 and 2is bad), flag unusual algorithms, and say how every program/function is invoked. - Slide exercises: run the program, remove parts to see the error messages, try
\cin the string; print your name; print first and last name on two lines.
The same in C++
cpp
#include <iostream>
int main () {
std::cout << "Hello world!\n"; // \n represents a newline
}coutis an object from theiostreamlibrary;std::is its namespace prefix (std= standard).- Three variants produce the identical executable:
std::cout;using std::cout;thencout;using namespace std;(blanket directive, discouraged for complex projects). - General structure of our C/C++ programs:
#includefor I/O (<stdio.h>/<iostream>) plus other needed headers, and the requiredmainfunction whose body holds the statements.
Typical beginner errors (from the slides)
;at the end of a preprocessor directive: warning about unexpected tokens after the directive.- Missing
{afterint main()or missing closing}: error about unmatched{. \cin a string: unknown escape sequence.- Missing
#include:printfnot defined / namespacestdhas nocout.
Versione ripasso
- Von Neumann machine: RAM (bytes with addresses 0 to N-1, readable and writable), CPU (cycle: fetch, decode, execute), secondary memory, I/O devices. Memory hierarchy: registers, cache L1/L2/L3, RAM, disk.
- A program must be in memory to run. Machine language only moves data RAM <-> registers, computes on registers, compares and jumps. Every program is built from three constructs: assignments, tests, loops.
- Information = data + interpretation: always know the coding of a value.
- Unsigned, n bits: 2^n combinations, maximum 2^n - 1; beyond it there is overflow. Signed: leftmost bit is the sign, negatives in two's complement (add 2^n: n = 5, -7 = 32 - 7 = 25 =
11001). - Example from the slides: with a 1-byte int,
INT_MAXis 127 andINT_MAX + 1wraps to10000000= -128. C does not check overflow: that is the programmer's job.sizeof(int)and<limits.h>give the limits. - Reals: IEEE 754,
float32 bit,double64 bit. Rounding means two equivalent real expressions can differ, so==can give false (Primitive Data Types and ExpressionsC data types (basic, derived, enum, struct and union, void, bool), arithmetic, comparison, logical and bitwise operators, type conversions and the rules for evaluating expressions.Primitive Data Types and Expressions →). - Algorithm: ordered, finite set of elementary, unambiguous instructions. Formalize with PRE (what holds on the input) and POST (a true/false assertion on the output). Example: root of x, PRE
x >= 0, POST returns y withx = y*y. - Workflow: ideate the algorithm in natural language first, then implement it with the language's basic instructions. Give evidence of correctness (tests), debug if it fails.
- Compare programs on correctness first, then efficiency (time and space), organization (reusable functions) and style (readable months later).
- Low-level languages are machine dependent; high-level ones are translated by a compiler, so only the translator changes when the architecture changes. Functions are collected in libraries.
- C: born in 1970 (Thompson and Ritchie) to write Unix, close to the machine, efficient, standardized as ANSI C. C++: mid 1980s, Stroustrup, extension of C with objects and generic programming.
- Minimal program:
#include <stdio.h>,int main() { ... }(every program starts inmain), statements end with;, strings in" ",\nis one character.
c
#include <stdio.h>
int main() {
printf("Hello world!\n"); // prints a newline at the end
}- C++ equivalent:
#include <iostream>,std::cout << "...\n";.using namespace std;is convenient but discouraged in big projects. - Typical errors:
;after a preprocessor directive (warning), missing{or}(unmatched brace error), unknown escape\c(warning), missing#include(printfnot defined, nostd::cout). - Next: Compilation, Linking and ExecutionHow a C source file becomes a running program: editing, preprocessing, compiling, linking, plus interpreters versus compilers and static versus dynamic linking.Compilation, Linking and Execution →, Primitive Data Types and ExpressionsC data types (basic, derived, enum, struct and union, void, bool), arithmetic, comparison, logical and bitwise operators, type conversions and the rules for evaluating expressions.Primitive Data Types and Expressions →, Control StructuresBasic syntax rules and the control structures of C: if/else, switch, the ternary operator, goto, symbolic constants and the while, for and do-while loops with break and continue.Control Structures →, Functions, Variables and ScopeHow to declare variables, define and call functions with prototypes and return values, pass arguments by value or through pointers, and use function pointers.Functions, Variables and Scope →, Command-Line Arguments and StructsHow main receives command-line arguments (argc, argv), converting them with atoi and strtol, parsing options with getopt, and grouping data with struct, typedef and union.Command-Line Arguments and Structs →.