CNDC Tutorial Plan
12 pages
English
Le téléchargement nécessite un accès à la bibliothèque YouScribe
Tout savoir sur nos offres
12 pages
English
Le téléchargement nécessite un accès à la bibliothèque YouScribe
Tout savoir sur nos offres

Description

1995, 2001 David Benn1A Tour of CIntroduction• Designed and implemented by Dennis Ritchie for the Unix operating system (DEC-PDP-11) in 1972.• Derived from BCPL (M. Richards, 1967) and B (K. Thompson, 1970). AmigaDOS usedformer.• The C Programming Language by K&R published in 1978.• Ported to a wide variety of platforms since then.• ANSI standardisation started in 1983; standard approved in 1989.• ANSI C standard recently embellished further.• ANSI C is not a strict subset of C++, but that's almost the case.• The C language includes no I/O functions. These are provided by libraries. Languageprovides abstractions of control and data.• There are three aspects to learning C: the language itself, the code libraries available forthe platform (e.g. the Standard C Library), and the C preprocessor.• C is used for a diverse range of programming:1. Operating systems (e.g. Unix, smart cards, etc);2. Device drivers;3. Compilers;4. Numerical computations (where once Fortran might have been used);5. Communications protocol stacks;6. Arbitrary applications.The C Language• C embodies features which are common to all imperative/procedural languages (eg.Pascal, Fortran, BASIC). 1 These are fairly generic C notes, originally serving as an introduction to C for a UnixNetwork Programming class I tutored several years ago. It has been updated a littlesince then, and since the talk I gave on 10 April 2001 to the SA PIC ...

Informations

Publié par
Nombre de lectures 79
Langue English

Extrait

1995, 2001
Introduction
1 A Tour of C
 Designed and implemented by Dennis Ritchie for the Unix operating system (DEC-PDP-11) in 1972.
David Benn
 Derived from BCPL (M. Richards, 1967) and B (K. Thompson, 1970). AmigaDOS used former.
 The C Programming Language by K&R published in 1978.
 Ported to a wide variety of platforms since then.
 ANSI standardisation started in 1983; standard approved in 1989.
 ANSI C standard recently embellished further.
 ANSI C is not a strict subset of C++, but that's almost the case.
 The C language includes no I/O functions. These are provided by libraries. Language provides abstractions of control and data.
 There are three aspects to learning C: the language itself, the code libraries available for the platform (e.g. the Standard C Library), and the C preprocessor.
 C is used for a diverse range of programming: 1.Operating systems (e.g. Unix, smart cards, etc); 2.Device drivers; 3.Compilers; 4.Numerical computations (where once Fortran might have been used); 5.Communications protocol stacks; 6.Arbitrary applications.
The C Language
 C embodies features which are common to all imperative/procedural languages (eg. Pascal, Fortran, BASIC).
1 These are fairly generic C notes, originally serving as an introduction to C for a Unix Network Programming class I tutored several years ago. It has been updated a little since then, and since the talk I gave on 10 April 2001 to the SA PIC User Group.
- 1 -
1995, 2001
 C is case sensitive.
2  ANSI C is a small language with 32 (lower case) reserved words.
 Often called a portable assembly language due to low-level nature. The claim of portability is dubious, e.g. due to data types, differences in libraries. Does provide independence from particular processor however.
Simple data types  char - single byte  int - typically reflects machine's natural word size (16 or 32 bits)  float - single-precision floating point  double - double-precision floating point  void - no parameters/value
David Benn
 Type qualifiers are: short, long, signed and unsigned; eg. short int (often 16 bits), long double (eg. 128 bits) and signed char (-128 to 127).  Storage qualifiers, e.g. register: automatic variable, in processor register if possible.
Constants  integer, floating-point, character and string (char array and special string literal syntax).
int 12345 123456789 0L 0xFFFF
/* L makes this a long integer */ /* hexadecimal FFFF is decimal 65535 */
floating-point 1.24 5.7e-3
character 'A' '\007' '\xa' '\n' '\t' '\'' '\\' '\0'
/* evaluates to (ASCII) 65 */ /* BELL - 1 to 3 digit octal */ /* hexadecimal A is ASCII 10: newline - 1 or 2 hex digits */ /* escape sequence - newline */ /* escape sequence - tab */ /* escape sequence - single quote */ /* escape sequence - backslash */ /* ASCII 0 - null character [different to'0'!!]*/
2 American National Standards Institute.
- 2 -
1995, 2001
string "hello world!" "" "\""
/* the empty string */ /* a string containing a double quote character */
All strings are actually null-terminated character arrays.
Defined constants (see alsoThe C Preprocessorbelow) #define BELL '\007' #define MAXLINE 100 #define HELLO "hello world!"
 Terms in an expression are promoted to the type of the most accurate term.  Character constants are treated as integers in arithmetic expressions,
eg.
'B'  'A'
gives an integer result of 1.
Variables  Identifiers are alphanumeric. The first character must be a letter or an underscore.  At least the first 31 characters of a variable name are significant.  Traditionally, variables are in lower case while named constants are uppercase.  Reserved words may not be used as variable names.
eg.
int x; float n = 1.25; char tab = '\t';
David Benn
 Assignment operations return a result; eg. x=y=1 is evaluated fromright to leftso we get y=1 which returns the value 1 which is in turn assigned to x.
Operators  C provides a rich set of operators. Commonly used ones are shown below:
Arithmetic +,,*,/,%,,++
eg.
++x y++ a % b
/* must think about context of use */
- 3 -
1995, 2001
Assignment =,+=,=,*=,/=,%=
eg.
x = 12 y += 2
Relational ==,!=,>,<,>=,<=
eg.
x = (7 == 2)
Logical &&,|| !
/* assign 12 to x */ /* assign y+2 to y */
/* assign 0 (FALSE) to x */
David Benn
/* short circuit AND,OR operators */ /* logical NOT (!nonzerovalueis 0; !0 is 1) */
(seeifstatement)
Bitwise ~,>>,<<,&,|,^ /* not,rightshift,leftshift,and,or,xor */
Miscellaneous sizeof, (type), (),?:
eg.
int x,n; x = sizeof(int) /* store size of int data type */ sin((double)n) /* cast n then passes to sin() */ return (x > y) ? x : y /* MAX */
 See Kernighan & Ritchie re: precedence and associativity of C operators.
Control constructs  C supportssingle-linestatements (expression followed by a semi-colon) andcompound statements (block of single-line statements delineated by { and }).  Both are used with C control constructs.
if-else
if (expression) statement1 [else statement2]
eg. if (y > MAXLINE)
- 4 -
1995, 2001
switch
y = 1; else ++y;
switch(expression) { case constexpr : statement(s) case constexpr : statement(s) default : statement(s) }
eg.
while
switch(choice) { case 1 :
}
case 2 : case 3 :
3 puts("one"); break;
puts("two or three"); break;
default : puts("last"); break;
while (expression) statement
eg. x = 1; while (x < 10) x += 2;
y=1; while (y < 10) { printf("%d %d\n",y,y*y); ++y; }
do-while
do statement 3 puts, printf, scanfare examples of standard C library functions in a desktop computer environment.
- 5 -
David Benn
1995, 2001
while (expression);
eg.
char ch; do { scanf("%c",ch); printf("You entered %c\n",ch); } while (ch != 'q');
is equivalent to the following Pascal code:
for
var ch : char; repeat  read(ch); writeln('You entered ',ch); until ch = 'q';
for (expr1;expr2;expr3) statement
which is equivalent to:
expr1; while (expr2) { statement expr3 }
eg.
for (i=0;i<=10;i++) . . .
is equivalent to:
i=0; while (i<=10) { . . . i++; }
David Benn
 C'sforloop is much more flexible than that of many other languages such as BASIC or Pascal.
eg.
1.
int i;
- 6 -
1995, 2001
2.
3.
for (i=1;i<=10;i++) printf("%d\n",i,i*i);
for(;;) printf("Hello world!\n");
char ch; for (ch = getchar();ch != ' ';ch = getchar());
David Benn
An application of this kind of loop might be to read characters until the end-of-line is reached, as in the following complete C program:
#include <stdio.h>
#define MAX 80
void main(void) { int i; char ch; char word[MAX];
 for (ch = getchar(), i=0;  ch != '\n' && i < MAX;  ch = getchar(), i++)  {  word[i] = ch;  }
 /* Terminate and possibly truncate. */  word[(i == MAX) ? i1: i] = '\0';  printf("You entered: %s\n",word); }
The aboveforloop is equivalent to the followingwhileloop:
ch = getchar(); i=0; while (ch != '\n' && i < MAX) { word[i] = ch; ch = getchar(); i++; }
 This brings us to the next topic: C functions. Beyond this, the above small program uses C preprocessor commands (#includeand#define) and library functions. See below re: these topics.
- 7 -
1995, 2001
David Benn
Functions  Functions and procedures are one and the same in C.  A function call ending in a semi-colon is a statement (like a Pascal procedure) and the function's return value is ignored.  All parameters are passed byvalue.  Pointers are used to turn value parameters into pass-by-reference parameters (see Pointerssection).  Functions may not be nested in C.  Return values default to int.  Even when there are no parameters, "()" follows the function name.
eg.
double foo(double n) { return sqrt(n); }
void main(void) { double x; x = foo(6.25); }
 Functions often have accompanying "prototypes" in C which help to enforce correct function parameter types and return values, especially when calling external functions, ie. functions defined in other source code/compiled modules (return type defaults to int).
 In general, where strongly typed languages such as Pascalforbidcertain data type combinations, C often just gives awarning. C allows you totype-casteasily (eg. int x; int y = 3.46; x = (int)y).
eg.
double foo(double);
Scope  Variables can be declared in any statement block to which their scope is then limited.  Global variables are available to other modules unless declared to bestatic.  Variables and functions in other modules can be referenced usingexterndeclarations.
Pointers  A pointer is a variable which holds an address.  Any data object can be "pointed to" in C: eg. variable, function.  Commonly used in C to implement pass-by-reference function parameters. C++ provides references and Pascal provides implicit pass-by-reference (variable)
- 8 -
1995, 2001
David Benn
parameters. Pointers have a much more central role than in Pascal. In the latter, pointers are used almost exclusively for implementing data structures.
eg.
void foo(int *x,int *y) { int temp;
}
temp = *x; *x = *y; *y = temp;
void main(void) { int a,b;
}
a = 1; b = 2;
printf("%d %d\n",a,b); foo(&a,&b); printf("%d %d\n",a,b);
 Arrays are always passed by reference since their address is passed by value (see also below).  It is possible in C to find the address of a function. This constitutes a function pointer.
Compound data types  C supports arrays, structures and unions.
Arrays
char str[40]; char str[] = "Hello World!"; char *str = "Hello World!";
/* includes '\0' */
 Note:&str[0] == str(to pass the name of an array to a function is to pass its address)
int stuff[2][3]
Structures
struct point
/* multidimension array */
- 9 -
1995, 2001
{
};
int x; int y;
struct point myPoint; /* variable declaration */ typedef struct point POINT; /* type definition */ POINT thePoint; /* variable declaration */
Here’s some code for a linked list:
struct node { int n; struct node *next; }; typedef struct node node_t;
David Benn
void main(void) {  node_t *p;  node_t *head = (node_t *)malloc(sizeof(node_t));  node_t *curr = head;  curr>n = 1234;  curr>next = (node_t *)malloc(sizeof(node_t));  curr = curr>next;  curr>n = 5678;  curr>next = NULL;
 for (p=head; p != NULL; p=p>next) {  printf("%d\n", p>n);  } }
Structures are the basis for classes in Stroustrup's C with Classes, and subsequent C++.
Unions are structs with N members only one of which is active for a given variable since all occupy the same space.
- 10 -
1995, 2001
The C Preprocessor
 Carries out text inclusions and replacement, constant-expression arithmetic, parameterised macro expansion and conditional compilation.
#include <includefile> /* looks in include */ #include "pathuses explicit path */" /*
eg.
#include <stdio.h>
includes function prototypes, constants etc for standard I/O.
#define SIZE 100 #define NULL '\0' #define MIN(a,b) ((a) < (b) ? (a) : (b))
char my_string[SIZE+1];
#ifdef MYSYMBOL . . #endif
#pragma
Libraries
/* compiler specific, e.g. pack a struct */
David Benn
Libraries exist for specific platforms, e.g. glue code for invoking Amiga shared library routines, or LCD library code for PIC. In BASIC dialects you find specific intrinsic functions and commands. In C, the same functionality can be in library code invoked as C functions in a uniform way.
In a PC or Unix environment, the Standard C Library is available.
The Standard C Library  The C language allows functions in external modules to be called. The Standard C Library consists of functions in pre-compiled modules, usually written in a mixture of C and assembler for the target machine.  Defines commonly used functions, including I/O (on a Unix system, see/usr/include for header files and/usr/libfor actual binary library files).  The -lcompiler switch must sometimes be used, eg. when you want to link math code.  Functions in theStandard C Libraryare machine independent.  See separate handout, Plauger, Appendix B of Kernighan & Ritchie.
- 11 -
  • Univers Univers
  • Ebooks Ebooks
  • Livres audio Livres audio
  • Presse Presse
  • Podcasts Podcasts
  • BD BD
  • Documents Documents