1 / 139

52.223 Low Level Programming Lecturer: Duncan Smeed

52.223 Low Level Programming Lecturer: Duncan Smeed. Overview of the C Programming Language Part 1. Nature of C. The C programming language has acquired the reputation for being a mysterious and messy language that promotes bad programming habits.

arne
Download Presentation

52.223 Low Level Programming Lecturer: Duncan Smeed

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 52.223 Low Level ProgrammingLecturer: Duncan Smeed Overview of the C Programming Language Part 1

  2. Nature of C • The C programming language has acquired the reputation for being a mysterious and messy language that promotes bad programming habits. • Part of the problem is that C gives special meanings to many punctuation characters, such as asterisks, plus signs, braces and angle brackets. • Once a programmer has learnt the C language, these symbols look quite commonplace, but there is no denying that a typical C program can be intimidating to the uninitiated. Overview of the C Programming Language - Part 1

  3. Trust the programmer • The other, more serious, complaint levelled against C concern the relative dearth of rules. • Other programming languages have very strict rules to protect programmers from making accidental blunders. • The C language was designed by experienced programmers for experienced programmers. The compiler, therefore, assumes little about what the programmer does or does not intend to do. This can be summed up by the C tenet: "Trust the programmer" Overview of the C Programming Language - Part 1

  4. …Trust the programmer • C programmers have tremendous liberty to write unusual code. • In may instances, this freedom allows programmers to write useful programs that would be difficult to write in other languages. • However, the freedom can be, and is, abused by inexperienced programmers who delight in writing needlessly tricky code. • C is a powerful language, but it requires self-restraint and discipline. Overview of the C Programming Language - Part 1

  5. …Trust the programmer “...there is a huge difference between good and working programs. A good program not only works, but is easy to read and maintain. Despite what some people claim, it is very possible to write good programs in C. Unfortunately, many C programmers are content to write programs that merely work.” Excerpted from C: A Software Engineering Approach by Darnell and Margolis Overview of the C Programming Language - Part 1

  6. The Background of C • C was originally designed for and implemented on the Unix operating system on the DEC PDP-11, by Dennis Ritchie. • Unix, the C compiler, and virtually all Unix applications programs are written in C. • C is not tied to any particular hardware or system, however, and it is easy(!) to write programs that will run without change on any machine that supports C. Overview of the C Programming Language - Part 1

  7. …The Background of C • C is a general purpose programming language which features economy of expression, modern control flow and data structures, and a rich set of operators. • C is not a 'very high level' language, nor a 'big' one, and is not specialised to any particular area of application. • Its absence of restrictions and its generality make it more convenient and effective for many tasks than supposedly more powerful languages. Overview of the C Programming Language - Part 1

  8. …The Background of C • C has been closely associated with the Unix system. • It is, however, available on a large number of machines under a variety of operating systems; and • although it has been called a "systems programming language" because it is useful for writing operating systems, it has been used equally well to write numerical, text-processing, and database programs. Overview of the C Programming Language - Part 1

  9. …The Background of C • C is a relatively "low level" language which means that it deals with the same sort of objects that most computers do, namely characters, numbers and addresses. These may be combined and moved about with the usual arithmetic and logical operators implemented by actual machines. • C provides no operations to deal directly with composite objects such as character strings, sets, lists, or arrays considered as a whole. • C also provides no input-output facilities such as READ or WRITE. Such high-level mechanisms must be provided by explicitly called functions. Overview of the C Programming Language - Part 1

  10. …The Background of C • The absence of such features keep the language down to modest dimensions so that it can be described easily, and learned quickly. • A compiler for C can be simple and compact and are easily written with, typically, 80% of the code common to existing ones. This provides a high degree of language mobility. Overview of the C Programming Language - Part 1

  11. …The Background of C • Because the data types and control structures provided by C are supported directly by most existing computers, the run-time library required to implement self-contained programs is tiny. • Of course, each implementation provides a comprehensive, compatible, library of functions to carry out I/O, string handling, and storage allocation operations, but since they are called only explicitly, they can be avoided if required; they can also be written portably in C itself. Overview of the C Programming Language - Part 1

  12. …The Background of C • C programs tend to be efficient enough that there is no compulsion to write assembly language instead. • The most obvious example of this is Unix itself, the kernel of which is written almost entirely in C. • Of the 13000 lines of system code in early versions of Unix, only about 800 lines at the very lowest level were in assembler. • Since C is independent of any particular machine architecture it is possible, with a little care, to write "portable" programs that can be run without change on a variety of hardware. Overview of the C Programming Language - Part 1

  13. C as a Programming Language • Many of the most important ideas of C stem from the considerably older language BCPL. • Although it shares several characteristic features with BCPL, C is in no sense a dialect of it. BCPL was a "typeless" language: the only data type is the machine word, and access to other kinds of objects is by special operators or function calls. • In C, the fundamental data objects are characters, integers of several sizes, and floating point numbers. In addition there is a hierarchy of derived data types created with pointers, arrays, structures, unions and functions. Overview of the C Programming Language - Part 1

  14. C Flow-Control Constructions • C provides the fundamental flow-control constructions required for well-structured programs: • statement grouping; • decision making (if); • looping with the termination test at the top (while, for) or at the bottom (do); • and selecting one of a set of possible cases (switch). Overview of the C Programming Language - Part 1

  15. C Call By ‘Value’ & Call By ‘Reference’ • C provides pointers and the ability to do address arithmetic. • The arguments to functions are passed by copying the value (call by value) of the argument, and it is impossible to change the actual argument in the caller. • However, call be reference can be achieved by passing a pointer explicitly, and the function may change the object to which the pointer 'points'. • Array names are passed as the location (address) of the array origin, so array arguments are effectively call by reference. Overview of the C Programming Language - Part 1

  16. C Variables • Any function may be called recursively, and its local variables are typically "automatic" - created anew with each invocation. • Functions may be compiled separately. • Variables may be (a) internal to a function, (b) external but known only within a single source file, or (c) completely global. • Internal (local) variables may be placed in registers for efficiency, but the register declaration is only a hint to the compiler and cannot specify actual registers. Overview of the C Programming Language - Part 1

  17. Summary of C language structure • Notes • letter case is NOT ignored by the compiler. • a newline (carriage return) in the C source is equivalent to a space, it does not indicate the end of a statement except in the case of pre-processor directives. Overview of the C Programming Language - Part 1

  18. Strings and Character Constants • Strings are normally terminated by a null character, i.e. the value 0. • A string literal (constant) is specified between double quotes, e.g. "this is a string". The compiler appends the null byte to the end of a string literal. • A character literal is specified between single quotes, e.g. 'A'. No null is appended. Character literals are integers. Overview of the C Programming Language - Part 1

  19. Control Characters • Control characters are entered in literals following a backslash character (\), as follows: Overview of the C Programming Language - Part 1

  20. Integer and Floating Point Constants Integer Constants Floating Point Constants FP constants are always double precision. Examples: 1.23, 1., .23, 1.23e4, 1.23E4, 3e4 Overview of the C Programming Language - Part 1

  21. Comments • /* This is a comment */ • They may appear wherever a space or newline is allowed. • Comments are not allowed to nest (caveat: some compilers allow nesting). So: someVar = 1; /* some comment *//* someVar = 1; */ /* still legal *//* but this attempt to comment out ...someVar = 1; /* some comment */...is illegal in most compilers. */ Overview of the C Programming Language - Part 1

  22. Identifiers • An identifier is a sequence of letters and digits; the first character of which must be a letter. • The underscore, _ , counts as a letter. • UPPER and lower case letters are different. • To conform to the C standard, a compiler must treat at least the first 31 characters as significant in the names of functions and global variables (i.e. identifiers with external linkage), and at least the first 63 characters in all other identifiers. • External identifiers, which are used by various assemblers and linker/loaders, may be more restricted. Overview of the C Programming Language - Part 1

  23. Variable Types • The sizes of the following variable types are implementation dependent. Typical values (in bits) for ANSI C are given: Overview of the C Programming Language - Part 1

  24. Storage Classes • Definitions outside of a function are external definitions. There are two classes: • Within a function: Overview of the C Programming Language - Part 1

  25. Program Structure • A C program is a series of external definitions and pre-processor directives. • External definitions are storage definitions and function definitions. • The executable part of the program is made up of the functions, which may call each other, passing parameters as required. • There must be one function whose name is main. It is this function that is called when the program is run. Functions cannot be defined within functions. Overview of the C Programming Language - Part 1

  26. The First C Program #include <stdio.h> int main() { printf("Hello, world\n"); return (0); } Overview of the C Programming Language - Part 1

  27. Function Definition A function definition has three parts: • the function declaration • the parameter declarations • the function body - a compound statement /* Declare the function max that returns an int... */ int max(int a,int b,int c) /* ...with the parameters a, b, and c of type int */ { /* start of the compound statement */ int m; /* auto storage decl'n (local var.) */ m = (a>b) ? a : b; /* m = max of a,b */ return ((m>c) ? m : c); /* return max of m,c */ } /* end compound statement */ Overview of the C Programming Language - Part 1

  28. Compound Statement A compound statement may be used wherever a simple statement is permitted. It has two parts: • storage declarations and definitions (optional) • executable statements The compound statement is enclosed in braces {curly brackets such as these}. Overview of the C Programming Language - Part 1

  29. Simple Statement A simple statement has the form: label: statement; The label is optional - it's only use is the target of a goto ({over}use of which is to be strongly discouraged). A label takes the same form as an identifier. Overview of the C Programming Language - Part 1

  30. Pointers and Addresses An identifier may be declared as a pointer to a particular type of data. This is frequently used in string manipulation, using a pointer to type char, and in buffered files, using a pointer to type FILE. Example declarations: char *a; /* a declared to be a pointer to char */ int *b[5]; /* b declared as an array of 5 pointers to int */ Overview of the C Programming Language - Part 1

  31. Address Operator & • The address operator & yields the address of its operand. • If the operand x has the type T, then the expression &x has the type ‘pointer to T’. • The operand of the address operator must have an addressable location in memory. I.e. the operand must designate either a function or an object (i.e. an lvalue) that is not a bit-field, and has not been declared with the storage class register Overview of the C Programming Language - Part 1

  32. Pointer Variables A pointer variable contains the address of a storage element. The address of a variable can be put in a pointer: int x; /* defines an integer */ int *p; /* defines a pointer to int */ p = &x; /* place address of x in p */ x = *p; /* places the value pointed at by p in x */ Pointers can have integers added or subtracted, which moves them by that number of storage elements. E.g., adding 5 to a pointer to int moves it forward by 5 integer 'elements' - 20 bytes in the case where an int is 32-bits in size. A pointer can have the constant value 0 (null) assigned to it. It is then a null pointer and is guaranteed to be different to any pointer to an actual value. Overview of the C Programming Language - Part 1

  33. main() • Every executable program must contain a special function called main(), which is where program execution begins. For example, to invoke max(), you could write: int main() { int maximum; maximum = max(3,4,5); /* rest of main() ... */ } Overview of the C Programming Language - Part 1

  34. printf() • The printf() function is the most versatile runtime routine for display output. • This function can take any number of arguments, the first of which - the format string - is special as it specifies how many data arguments are to follow and how they are to be formatted. • The format string is enclosed in double quotes, and may contain text and format specifiers. Overview of the C Programming Language - Part 1

  35. printf()Format Specifier • A format specifier is a special character sequence that begins with a percent sign (%) and indicates how to write a single data item. For example: printf("The maximum of %d %d & %d is %d\n”,\ 3,4,5,max(3,4,5)); • The %d specifiers indicate that the data items are decimal integers. Other similar specifiers are: Overview of the C Programming Language - Part 1

  36. scanf() • The scanf() function is the mirror image of printf() - it reads data entered form standard input (i.e. the keyboard). The major difference is that scanf() must have the address of a data item passed as the argument. For example: scanf("%d %d %d",&num1,&num2,&num3); directs the system to read integer input and store the values in num1, num2 and num3. The ampersand (&) is a special character that yields the address of a variable. • The best way to learn how to use printf() and scanf() is to experiment with them and, of course, to read complete descriptions of them in the manual pages or from a text book. Overview of the C Programming Language - Part 1

  37. The Preprocessor • The preprocessor can be thought of as a separate program that runs before the compiler. • The preprocessor directives begin with a hash (#) sign, which must be the first character on the line. • Unlike C statements, a preprocessor directive ends with a newline, not a semicolon. Overview of the C Programming Language - Part 1

  38. #include • The #include directive causes the compiler to read source text from another files as well as the file it is currently compiling. This is useful when identical information is to be shared by more than one source file. It has two forms: #include <filename> #include "filename" • The <...> form causes the preprocessor to look in a special directory which contains all the system include files, such as header files for the runtime library - e.g. <stdio.h>. • The "..." form causes the preprocessor to look in the directory containing the source file and, if it can't find it there, it'll revert back to the special directory. Overview of the C Programming Language - Part 1

  39. #define • The #define directive associates a name with a constant (among other thing). For instance: #define MAX_PAGE_WIDTH 80#define LOOPS 100000000 • Naming constants has two important benefits. • Firstly, it enables the programmer to give a descriptive name to a nondescript constant thus making the program easier to read and understand (hopefully!). • Secondly, they make the program easier to change! Overview of the C Programming Language - Part 1

  40. References & Bibliography • C in a Nutshell<http://www.oreilly.com/catalog/cinanut/> • The C Book (online e-book)<http://publications.gbdirect.co.uk/c_book/> • Standard C<http://www-ccs.ucsd.edu/c/> • C: A Software Engineering Approach (print on demand?)<http://tinyurl.com/ay58v> Overview of the C Programming Language - Part 1

  41. 52.223 Low Level ProgrammingLecturer: Duncan Smeed Overview of the C Programming Language Part 2

  42. Scalar Data Types • The ability to divide data into different types is one of the most important features of modern programming languages. • The programmer can work with integers, characters, floating point numbers, etc., without having to be concerned with the underlying representations. • It is up to the compiler, therefore, to make sure that the computer handles bits and bytes in a way consistent with their data type. Overview of the C Programming Language - Part 2

  43. …Scalar Data Types The C language offers a small but useful set of data types: • Arithmetic types: Integers and floating-point entities. • Scalar types: arithmetic types plus pointers and enumerated types. Known as the scalar types because all of the values lie along a linear 'scale'. • Aggregate types: a combination of one or more scalar types including: • arrays, structures and unions • useful for organising logically-related variables into physically-adjacent groups. • Void type: neither scalar or aggregate. Overview of the C Programming Language - Part 2

  44. Hierarchy of C Data Types Overview of the C Programming Language - Part 2

  45. Standard Signed Integer Types Overview of the C Programming Language - Part 2

  46. Standard Unsigned Integer Types Overview of the C Programming Language - Part 2

  47. char • The type char is one of the standard integer types but can be signed or unsigned depending on the implementation. So, • char, signed char and unsigned char are formally three different types. Overview of the C Programming Language - Part 2

  48. Floating-point Types • The standard floating-point types for calculating with real numbers are as follows: • float Single precision • double Double precision • long double Extended precision Overview of the C Programming Language - Part 2

  49. Typedefs • Names for data types can be created with a typedef keyword. • Syntactically, a typedef is exactly like a variable declaration except that the declaration is preceded by the typedef keyword. • Semantically, the variable name becomes a synonym for the data type rather than a variable that is allocated memory. E.g.: typedef long int DOUBLE_WORD; • The following declarations are now identical: long int j; DOUBLE_WORD j; • By convention, typedef names are capitalised so that they are not confused with variable names. Overview of the C Programming Language - Part 2

  50. Uses of Typedefs • Typedefs are especially useful for abstracting global types that can be used throughout a program. • Another use for typedefs is to compensate for differences in C compilers: For example, some non-ANSI C compilers do not support the unsigned short type. Using typedefs, you can write the program so that it uses unsigned short if it's available, or unsigned int if not. • ANSI-conforming: typedef unsigned short USHORT; • non-ANSI: typedef unsigned int USHORT; Overview of the C Programming Language - Part 2

More Related