Mechatronics - Lecture Notes

C Language Notes

Notes: This guide is written for those who are familiar with another programming language such as FORTRAN. The main source of my lectures for C language is Beginning with C by Ron House (1994, ITP). It is to be used as a hands-on guide for the Mechatronics class.


  • Due to the complexity of computer systems, programs should be well-structured for ease of understanding. One useful structuring method is arrangement in hierarchies.
  • When dealing with a hierarchical system, try where possible to deal with just one level of the hierarchy at any one time.
  • In C, functions provide a basic tool for implementing hierarchies.
  • Every C program contains a 'master function' called main, which:
    • is the first function to start executing in a program
    • is the function that causes all required processing to occur
    • may call other functions to perform required subtasks.
  • We can pass information into a function for its use by using arguments.
  • C provides a large library of standard functions; as these have already been written for us, we do not need to know how they operate in order to use them.
    • We must use # include to make the compiler read the appropriate header file(s).
  • printf is one such standard function that allows us to send output to the user's screen.
    • The first argument to printf is a string to be printed.
  • Functions can
    • be called as often as required
    • call other functions
    • contain as many statements as required
    • call themselves, directly or indirectly (recursion).
  • The statements in function are executed when (and only when) the function is called.
  • A void functions's purpose is to carry out the instructions in its function body (inside the braces).
  • void function definition:
    void function_name (void)
    {
           /* statements to be executed when function is called */
    }
  • void function declaration:
    void function_name (void) ;
  • Each function should serve a single, well-defined purpose.
  • Functions should have clear, explanatory names. void functions should usually be given verbs as names.
  • Program layout:
    • C gives the programmer a lot of freedom in program layout, but we must not split a word or join two words.
    • We should follow layout rules to make the program easier for humans to read.
    • # include (and other # directives to be discussed later) must not be split over lines.
    • Comments, delimited by / * and * / , let us include information for human readers, and do not alter the meaning of the program.
  • Preconditions are statements of the conditions under which a given piece of code will work correctly; postconditions say what will be done by the code if the preconditions are met.
  • Certain words (keywords) have a special meaning to the C compiler, and cannot be used for other purposes such as function names.

           

  • Data is information represented according to well-defined rules.
  • C has many data types for storing integer values.
    • Characters are stored as integer codes (usually ASCII).
    • The char type is used to store an integer code for any character.
    • The int type can store values form -32,767 to 32,767 inclusive. Some compilers let us store larger numbers than this.
    • The long data type is like int, but allows a larger range of values.
  • String literals consist of readable text in double quotes.
    • The same type of quotation mark both opens and closes a literal.
    • The opening and closing quote must be on the same line.
    • Each character is stored in one computer memory byte.
    • Special characters are represented with escape sequences, such as:
    • \n newline
    • \" the quote character itself
    • \\ the backslash itself
    • \0 the nul character.
    • A string is terminated by a nul character.
  • Variables are names places in memory where a data value of the appropriate type may be stored.
    • Variables must be declared before they are used.
    • A variable can only store one value at a time.
    • A variable may be given a value using the assignment operator, =.
  • Local variables:
    • are declared inside a function, and can only be used inside the function
    • should be used wherever feasible.
  • Global variables:
    • are declared outside functions
    • may be accessed by any function
    • should only be used for data needed by more than one function.
  • An array is a place in memory which can story many values.
    • A char array may be used to store a string.
  • printf can output data using format sequences in the format string.
    • Some format sequences are: %s (for strings), %c (for character codes), %d (for integers), %ld (for long integers), or %f, %e and %g (for floats and doubles).
    • For each format sequence, a suitable argument to be output must be supplied following the format string.
    • Format sequences can have length specifications to control formatting of output:
    • The width is the minimum number of characters to print, for all format types
    • For %s formats, the precision, written after a period, is the maximum number of characters to print.
    • For %d, the precision is the minimum number of digits to print.
    • For %f and %e, the precision is the number of places after the decimal point; for %g is is the total number of digits.
    • %% is used in the format string only, to print the % character.
  • Calculations may be performed by writing expressions.
    • Operators include +, -, *, / and, for integers only, %.
    • Shortcut assignment operators: ++, --, +=, -+, *=, /+, %=.
    • Function results may also be used in expressions.
    • A range of mathematical functions are provided in the standard library.
  • Variable names are identifiers, which may include letters, underscores and digits, but may not commence with a digit. Upper and lower case letters are considered to be different.

           

  • A loop is a section of a program which is repeated zero or more times.
  • The main loop types are pretest and posttest:
    • pretest loops perform the loop test before executing the loop body
    • posttest loops perform the loop test after executing the loop body.
  • C statements for creating loops include while, for, and do...while.
    • while is a pretest loop
    • for is a convenient form of while
    • do...while is a posttest loop.
    • Unless the loop body must execute at least once, avoid the do...while loop.
  • Loop tests consist of logical assertions which may be true or false.
  • In all three C looping statements, a true test result causes the loop to execute again, whereas a false result causes the loop to cease.
  • One way to write a test is with comparison operators: <, <=, >, >=, = =, !=.
  • A common way to program a loop is to set a variable to an initial value, and increment it until the test indicates it has reached the final value.
  • Pretending to be a computer and executing a program by hand is called tracing the program.
  • To add a list of values, set a totalling variable to 0 first, and add one value to it each time round a loop.
  • To multiply a list of values, set a totalling variable to 1 first, and multiply one value into it each time round a loop.
  • The preprocessor transforms the text of a program before it is compiled by the C compiler proper. All lines starting with # are directives to the preprocessor.
  • The #define directive tells the preprocessor to substitute a constant (or some other piece of text) for a macro name wherever it occurs, except inside string literals.
  • A multiple assignment allows a value to be stored in two or more variables.
  • Care needs to be taken when using floating point variables as loop counters, as slight inaccuracies may cause the loop to malfunction.
  • Loop correctness can be checked using a bound function, a postcondition, and an invariant.
  • The five-point checklist:
    1. Is there an integer bound function which must be positive if the loop continues?
    2. Is it guaranteed to decrease each time through the loop?
    3. Is the invariant true on first entry to the loop?
    4. Will any one iteration of the loop re-establish the truth of the invariant?
    5. Will the truth of the invariant, and the fact that the loop stopped, establish the truth of the postcondition?
  • Try to write postconditions, bound functions, and (if you can) invariants, even if you do not perform the full loop checking.
    • Write the postcondition and invariant before you write the loop.
    • Incorporate them in the program as comments.