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 ...
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 (!nonzerovalueis 0; !0 is 1) */
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 constexpr : statement(s) case constexpr : 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.
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.
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.
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.