Upload
shana-gibbs
View
227
Download
1
Embed Size (px)
Citation preview
Introduction to C Programming
Summer 2014
COMP 2130 Intro Computer Systems
Computing ScienceThompson Rivers University
TRU-COMP2130 Data Representation 2
Course Contents
Introduction to computer systems: B&O 1 Data representations: B&O 2.1 – 2.4 Introduction to C programming: K&R 1 – 4 C: advanced topics: K&R 5.1 – 5.10, 6 – 7 Introduction to IA32 (Intel Architecture 32): B&O 3.1 – 3.8, 3.13 Compiling, linking, loading, and executing: B&O 7 (except 7.12) Dynamic memory management – Heap: B&O 9.9.1 – 9.9.2, 9.9.4 –
9.9.5, 9.11 Code optimization: B&O 5.1 – 5.6, 5.13 Memory hierarchy, locality, caching: B&O 5.12, 6.1 – 6.3, 6.4.1 –
6.4.2, 6.5, 6.6.2 – 6.6.3, 6.7 Virtual memory (if time permits): B&O 9.4 – 9.5
TRU-COMP2130 Data Representation 3
Unit Learning Objectives
Use cc (or gcc) to compile C programs. Write a C program with the common (very similar) syntaxes with
Java. Use printf() library function to print messages. Use define statements for constants. Use getchar() and putchar() for I/O. Use of integer values as Boolean values. Use a char array as a string. Use bit operators to manipulate bits in a given integer. Understand the scope of external identifiers. Distinguish signed integer types and unsigned integer types. Use register variables for indexing arrays. Use conditional inclusion statements with #if, #elif, … . …
TRU-COMP2130 Data Representation 4
1. Introduction
The C programming language was designed by Dennis Ritchie at Bell Laboratories in the early 1970s
Influenced by ALGOL 60 (1960), CPL (Cambridge, 1963), BCPL (Martin Richard, 1967), B (Ken Thompson, 1970)
Traditionally used for systems programming, though this may be changing in favor of C++
Traditional C: The C Programming Language, by Brian Kernighan and Dennis Ritchie,
2nd Edition, Prentice Hall (Referred to as K&R ) Programming in C – Byron S. Gottfried (Schaum’s Outline Series)
Introduction 5
Standard C
Standardized in 1989 by ANSI (American National Standards Institute) known as ANSI C
International standard (ISO) in 1990 which was adopted by ANSI and is known as C89
As part of the normal evolution process the standard was updated in 1995 (C95) and 1999 (C99)
C++ and C C++ extends C to include support for Object Oriented Programming and
other features that facilitate large software development projects C is not strictly a subset of C++, but it is possible to write “Clean C” that
conforms to both the C++ and C standards.
TRU-COMP2130
Introduction 6
Elements of a C Program
A C development environment includes System libraries and headers: a set of standard libraries and their header
files. For example see /usr/include and glibc. Application Source: application source and header files Compiler: converts source to object code for a specific platform Linker: resolves external references and produces the executable module
User program structure there must be one main function where execution begins when the
program is run. This function is called main int main (void) { ... }, int main (int argc, char *argv[]) { ... } UNIX Systems have a 3rd way to define main(), though it is not POSIX.1
compliantint main (int argc, char *argv[], char *envp[])
additional local and external functions and variables
TRU-COMP2130
Introduction 7
A Simple C Program
Create example file: try.c Compile using gcc:
gcc –o try try.c The standard C library libc is included automatically Execute program
./try Note, I always specify an absolute path Normal termination:
void exit(int status); calls functions registered with atexit() flush output streams close all open streams return status value and
control to host environment
/* you generally want to * include stdio.h and * stdlib.h * */#include <stdio.h>#include <stdlib.h>
int main (void){ printf(“Hello World\n”); exit(0);}TRU-
COMP2130
Introduction 8
Getting Started
C program files should end with “.c”. hello.c
#include <stdio.h> // similar to import statements in Java
// stdio.h includes the information about the standard library
int main() // similar to main method in Java
{ printf (“hello, world\n”); // printf() defined in stdio.h
return 0;}
How to compile? $ gcc hello.c or $ gcc hello.c -o hello If you do not have anything wrong, you will see a.out in the same
working directory. How to run?
$ ./a.outTRU-COMP2130
Introduction 9
Source and Header files
Just as in Java, place related code within the same module (i.e. file). Header files (*.h) export interface definitions
function prototypes, data types, macros, inline functions and other common declarations
Do not place source code (i.e. definitions) in the header file with a few exceptions.
inline’d code class definitions const definitions
C preprocessor (cpp) is used to insert common definitions into source files
There are other cool things you can do with the preprocessor
TRU-COMP2130
Introduction 10
Another Example C Program
example.c/* this is a C-style comment * You generally want to palce * all file includes at start of file * */#include <stdio.h>#include <stdlib.h>
intmain (int argc, char **argv){ // this is a C++-style comment // printf prototype in stdio.hprintf(“Hello, Prog name = %s\n”,
argv[0]);exit(0);
}
/* comments */#ifndef _STDIO_H#define _STDIO_H
... definitions and protoypes
#endif
/usr/include/stdio.h
/* prevents including file * contents multiple * times */#ifndef _STDLIB_H#define _STDLIB_H
... definitions and protoypes
#endif
/usr/include/stdlib.h
#include directs the preprocessorto “include” the contents of the fileat this point in the source file.#define directs preprocessor to define macros.
TRU-COMP2130
Introduction 11
C Standard Header Files
Standard Headers you should know about: stdio.h – file and console (also a file) IO: perror, printf,
open, close, read, write, scanf, etc. stdlib.h - common utility functions: malloc, calloc,
strtol, atoi, etc string.h - string and byte manipulation: strlen, strcpy,
strcat, memcpy, memset, etc. ctype.h – character types: isalnum, isprint, isupport,
tolower, etc. errno.h – defines errno used for reporting system errors math.h – math functions: ceil, exp, floor, sqrt, etc. signal.h – signal handling facility: raise, signal, etc stdint.h – standard integer: intN_t, uintN_t, etc time.h – time related facility: asctime, clock, time_t, etc.
TRU-COMP2130
Introduction 12
The Preprocessor
The C preprocessor permits you to define simple macros that are evaluated and expanded prior to compilation.
Commands begin with a ‘#’. Abbreviated list: #define : defines a macro #undef : removes a macro definition #include : insert text from file #if : conditional based on value of expression #ifdef : conditional based on whether macro defined #ifndef : conditional based on whether macro is not defined #else : alternative #elif : conditional alternative defined() : preprocessor function: 1 if name defined, else 0
#if defined(__NetBSD__)
Introduction 13
Common features
For the statement printf (“hello, world\n”);
“…” is a character string. This is also called a string constant.printf() is a library function to print a string to the terminal.
Data types - primitive data types
char, int, (short & long), float, double
Introduction 14
Operators
Mathematical– Subtraction, also unary minus+ Addition* Multiplication/ Division% Modulus-- Decrement++ Increment
Relational
> Greater than
>= Greater than or equal
< Less than
<= Less than or equal
= = Equal
!= Not equal
Introduction 15
Operators
Logical Operators:
&& AND
|| OR
! NOT
Introduction 16
Control structures
Control structuresif, if-else, for, while, do-while, switch
Introduction 17
Exercise
write a program to convert Fahrenheit temperature to Celsius temperature, using the given formula
formula: C = 5 / 9 × (F – 32)
Ask user for an option for C -> F
Or F -> C
18
Precedence and Associativity
19
Examples
x =10; y = ++x; y 11x =10; y = x++; y 10
int i = 3, j = 2, k;
i++; ij = ++i; j i k = i++; k i k = (--j+3) k j
4
5 55 6
47
20
l = 4;
n = 3;
m = 2;
x = l * n + m++; x
After the assignment to x.
m
14
3
21
int a,b;
a = 1;
b = 12;
printf (“a+++b = %d/n”, a+++b);
a = 1;
b = 12;
printf (“a++ +b = %d/n”, a++ +b);
a = 1;
b = 12;
printf (“a+ ++b =% d/n”, a+ ++b);
22
Precedence and Associativity
23
Both are lower in precedence than the arithmetic operators.
10 > 1 + 12 10 > (1 + 12) FALSE 0
Associativity: left to right.
int x;x = 100;printf(''%d", x>10); __?
24
!A is false (0) if A’s value is: __.
is true (1) if A’s value is: __.
!!5 ! (!5) ! (0) 1
5 && 3 ?
Examples
Introduction 25
Example
See
Introduction 26
Answer
Introduction 27
Comma operator
Lowest precedence of all the operators. Causes a sequence of operations, “do this and this and this…”. Is a binary operator.
expression_1, expression_2 Associates left to right.
expression_1 is evaluated firstexpression_2 is evaluated second
28
The Comma Expression as a whole has the value and type of expression_2.
Comma operator – Ex.
Introduction 29
Conditional Operator (Ternary)
A powerful and convenient operator that replaces certain statements of the if-then-else form.
Exp1 ? Exp2: Exp3
Introduction 30
Example
It is also possible to nest ternary
Introduction 31
Expressions Vs Statements
An expression in C is any valid combination of operators, constants, functions and variables.
A statement is a valid expression followed by a semicolon.
Func1(); A function call as a statement.
Y = X + Y; An assignment statement.
B + Func1(); Valid?
Introduction 32
Think Idea
c = (c > =‘a’ && c < = ‘z’) ? c - (‘z’ - ‘Z’):c;
TRU-COMP2130 C Programming 33
Example ‘C’ code
#include ...
/* print Fahrenheit-Celsius table for fahr = 0, 20, 40, ..., 300, using a loop */main(){ int fahr, celsius; int lower, upper, step;
lower = 0; /* lower limit of temperature scale */ upper = 300; // upper limit step = 20; // step size fahr = lower;
while (fahr <= upper) { celsius = 5 * (fahr-32) / 9; // integer value? printf("%d\t%d\n", fahr, celsius); fahr = fahr + step; }}
TRU-COMP2130 C Programming 34
printf("%d\t%d\n", fahr, celsius); %d specifies an integer argument (d: decimal).
Output1 -1720-6404...
Can we print better? Like 1 -1720 -640 4...
printf("%3d\t%6d\n", fahr, celsius);
TRU-COMP2130 C Programming 35
1 -1720 -640 4...
Is there any problem in the above output?The Celsius temperatures in the previous out are not accurate. For example 0o F is -17.8o C.Then?We can use float data type for fahr and celsius instead of int.
float fahr, celsius; Then how to print real numbers using printf()?
celsius = 5 * (fahr-32) / 9; // okay?printf("%3.0f\t%6.1f\n", fahr, celsius);%f specifies a floating point argument (f: floating point).6.1 means 1 decimal out of 6 digits.
TRU-COMP2130 C Programming 36
Some easy errors: printf("%d\t%6.1f\n", fahr, celsius); printf("%3.0f\t%6.1f\n", fahr); printf("%6.1f\n", fahr, celsius);
TRU-COMP2130 C Programming 37
Summary of printf() format specifiers %d print as decimal integer %6d print as decimal integer, at least 6 characters wide %f print as floating point %6f print as floating point, at least 6 characters wide %.2f print as floating point, 2 characters after decimal point %6.2f print as floating point, at least 6 characters wide and 2 after
decimal point Other format specifiers
%o for octal %x for hexadecimal %c for character %s for character string %% % itself
TRU-COMP2130 C Programming 38
Symbolic Constants
#define name replacement_list
#include <...>
#define LOWER 0 // similar to final variable in Java#define UPPER 300#define STEP 20
main(){ float fahr, celsius;
for (fahr = LOWER ; fahr <= UPPER ; fahr = fahr + STEP) { celsius = 5 * (fahr-32) / 9; printf("%3.0f\t%6.1f\n", fahr, celsius); }}
TRU-COMP2130 C Programming 39
Symbolic Constants
#define name replacement_list
#include <stdio.h>
#define LOWER 0 // similar to final variable in Java#define UPPER 300#define STEP 20
main(){ float fahr, celsius;
for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP) { celsius = 5 * (fahr-32) / 9; printf("%3.0f\t%6.1f\n", fahr, celsius); }}
TRU-COMP2130 C Programming 40
Character Input and Output
#include <stdio.h>
/* copy input to output; 1st version */main(){ int c;
c = getchar(); // in order to read a character while (c != EOF) { // EOF is defined in stdio.h.
// EOF means End of File, ^D. putchar(c); // in order to print a character c = getchar(); }}
Where did getchar(), EOF, and putchar() come from? Let’s run this program to understand I/O better.
TRU-COMP2130 C Programming 41
#include <stdio.h>
/* copy input to output; 2nd version */main(){ int c;
while ((c = getchar()) != EOF) // okay?putchar(c);
}
What if we use the follow code instead? while (c = getchar() != EOF)
The above code is equivalent to while (c = (getchar() != EOF))
This is because the precedence of != is higher than =.
TRU-COMP2130 C Programming 42
Operator precedence rules() [] -> .! ~ - (unary) + (unary) * & sizeof ++ --* / %+ -<< >>< <= > >=== !=&^|&&||= += -= *= /= %= &= |= ^= <<= >>=
TRU-COMP2130 C Programming 43
Boolean values in ‘C’
Syntax error? while (c = getchar() != EOF)
Let’s assume getchar() returns ‘A’. Then getchar() != EOF becomes TRUE.
The data type of c is int. Is there a boolean data type in C? No 0 is FALSE and non-zero value is considered as TRUE in C. Hence getchar() != EOF becomes 1, and c has 1. while(c) -> while(1). So, the loop repeats.
TRU-COMP2130 C Programming 44
Arrays
#include <stdio.h>
/* count digits, white space, others */main(){ int c, i, nwhite, nother, ndigit[10]; // very similar to Java
nwhite = nother = 0; // really necessary? for (i = 0; i < 10; ++i) ndigit[i] = 0;
while ((c = getchar()) != EOF) if (c >= '0' && c <= '9') ndigit[c-'0']++; else if (c == ' ' || c == '\n' || c == '\t') ++nwhite; else nother++;
printf("digits ="); for (i = 0; i < 10; i++) printf(" %d", ndigit[i]); printf(", white space = %d, other = %d\n", nwhite, nother);}
TRU-COMP2130 C Programming 45
A character, e.g., ‘3’, is an integer value. int c = ‘3’; is valid. ASCII table
TRU-COMP2130 C Programming 46
Functions
#include <stdio.h>
int power(int m, int n); // function declaration // What if it is not declared before
// main()?main(){ int i;
for (i = 0; i < 10; i++) printf("%d %d %d %d\n", i, power(2, i), power(-3, i), i);
return 0;}
/* power: raise base to n-th power; n >= 0 */int power(int base, int n){ int i, p; ... // How to implement?
TRU-COMP2130 C Programming 47
...
for (i = 0; i < 10; i++) printf("%d %d %d %d\n", i, power(2,i), power(-3,i), i);
return 0;}
/* power: raise base to n-th power; n >= 0 */int power(int base, int n){ int i, p;
p = 1; for (i = 1; i <= n; i++) p = p * base;
return p;}
TRU-COMP2130 C Programming 48
Arguments
/* power: raise base to n-th power; n >= 0; version 2 */int power(int base, int n){ int p;
for (p = 1; n > 0; n--) p = p * base;
return p;}
base, n and p are local variables that are used only in power(). When the function is called (or also called invoked), the values will be
copied (oac passed) into base and n. Even if those variables are updated with other values, the new values
will not be passed back to the caller function. How is this implemented in main memory?
This type of function calling is called call by value.
Character Arrays
#include <stdio.h>#define MAXLINE 1000
int getline(char line[], int maxline);void copy(char to[], char from[]);
main(){ int len; /* current line length */ int max; /* maximum length seen so far */ char line[MAXLINE]; /* current input line */ char longest[MAXLINE]; // longest line saved
max = 0; while ((len = getline(line, MAXLINE)) > 0) if (len > max) { max = len; copy(longest, line); }
if (max > 0) printf("%s", longest); return 0;}...
int getline(char s[], int lim){ int c, i;
for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i) s[i] = c; if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; // “...’\0’” return i;}
void copy(char to[], char from[]){ int i;
i = 0; while ((to[i] = from[i]) != '\0') ++i;}
In the same file
TRU-COMP2130 C Programming 50
In main(),while ((len = getline(line, MAXLINE)) > 0)The data type of line[] is an array.getline() can change the contents in line[], and the change in line[] can be used in main(). Very similar to Java.This type of function calling is called call by reference.How is this implemented in main memory?
line represents MAXLINE variables - line[0], line[1], ..., line[MAXLINE-
1]. How? Address should be passed. line contains the address of the first byte of line[0]. line[i] is the memory area pointed by the address line +
sizeof(char) * i.
addr value var
… … …
def abc line
… … …
abc ‘C’ line[0]
abc+1 ‘O’ line[1]
… … …
Main memory
TRU-COMP2130 C Programming 51
In getline(),int getline(char s[], int lim)The data type of the first parameter is an array. The address stored in line in main() is passed into s. Therefore s[i] will become equal to line[i]. Any change in this variable will be preserved so that the caller can use the change.This type of function calling is called call by reference.
s[i] = '\0';After all the characters are stored in s[] till EOF or ‘\n’,
‘\0’ is stored to mark the end of the character string.That is, a string is a list of characters with the end of ‘\0’, and a char array is usually used to keep a string.This is very important.
TRU-COMP2130 C Programming 52
In main(),if (max > 0) printf("%s", longest);%s is used to print a character string. The argument is a char array, not longest[], nor longest[0], and …What is the data type of longest?
char longest[MAXLINE];What value is stored in longest?
The address of the first byte of longest[0] to represent all longest[0], longest[1], ….
Can a char array be a character string?Yes. printf() with %s will try to print characters pointed by longest(, i.e., longest[0], longest[1], …,) until the character becomes ‘\0’.
TRU-COMP2130 C Programming 53
char name[256], tmp[256];name[0] = ‘C’;name[1] = ‘O’;name[2] = ‘M’;name[3] = ‘P’;name[4] = ‘\0’; // it is very important.printf(“course number = %s\n”, name);name[5] = ‘ ’;name[6] = ‘2’;printf(“course number = %s\n”, name);name[7] = ‘1’;name[8] = ‘3’;name[9] = ‘0’;name[10] = ‘\0’; // it is very important.printf(“course number = %s\n”, name);
What is the output?
External Variables and Scope#include <stdio.h>
#define MAXLINE 1000
int max; // similar to instance in Javachar line[MAXLINE]; char longest[MAXLINE];
int getline(void);void copy(void);
main(){ int len; extern int max, extern char longest[];
max = 0; while ((len = getline()) > 0) if (len > max) { max = len; copy(); } if (max > 0) /* there was a line */ printf("%s", longest); return 0;}
int getline(void){ int c, i;// extern char line[]; // no need to declare
for (i = 0; i < MAXLINE – 1 && (c=getchar)) != EOF && c != '\n'; ++i) line[i] = c; if (c == '\n') { line[i] = c; ++i; } line[i] = '\0'; return i;}
void copy(void){ int i;// extern char line[], longest[];
i = 0; while ((longest[i] = line[i]) != '\0') ++i;}
In the same file
TRU-COMP2130 C Programming 55
#include …
…
#define …
…
// declaration of global variables
…
// declaration (i.e., definitions) of functions
…
// implementation of functions
{
…
}
Any identifier declared early is visible in the same block or sub-blocks.
Visible to every function in the file
TRU-COMP2130 C Programming 56
Data Types and Sizes
Primitive data typesC Java Size
char, unsigned char byte 1B
char in Java uses 2Bs.
short, unsigned short short 2Bs
int, unsigned int int 4Bs
long, unsigned long long 8Bs
// there is no unsigned in Java
float float 4Bs
double double 8Bs
// boolean? TRUE: any non-zero value, boolean in Java
FALSE: zero
// string? “...”: with ‘\0’ at the end String in Java
sizeof(data_type) or sizeof(variable) gives the number of bytes used.
TRU-COMP2130 C Programming 57
Goto and Labels
for (i = 0; i < n; i++) for (j = 0; j < m; j++) if (a[i] == b[j]) goto found;/* didn't find any common element */...found:/* got one: a[i] == b[j] */...
Better not use goto statements Can you convert the above code so that you would not use goto?
TRU-COMP2130 C Programming 58
4. Functions and Program Structure
Function in C is the same as method in Java.
return-type function-name(argument declarations) Various parts may be absent.
TRU-COMP2130 C Programming 59
External Variables
If a large number of variables must be shared among functions, external variables (or also called global variables) are more convenient and efficient than long argument lists.
External variables are declared outside of any function, usually with initial values.
Automatic variables (local variables and parameters) are internal to a function; they come into existence when the function is entered, and disappear when it is left.
External variables, on the other hand, are permanent, so they can retain values from one function invocation to the next. Thus if two functions must share some data, yet neither calls the other, it is often most convenient if the shared data is kept in external variables rather than being passed in and out via arguments.
TRU-COMP2130 C Programming 60
Scope Rules
The scope of a name is the part of the program within which the name can be used.
The scope of an external variable or a function lasts from the point at which it is declared to the end of the file being compiled.
main() { ... }
int sp = 0;double val[MAXVAL];
void push(double f) { ... }
double pop(void) { ... }
Is sp visible in push()? Can sp and pop() be used in main()?
TRU-COMP2130 C Programming 61
Can we make external variables declared in file1 be used in file2?
in file1:
extern int sp;extern double val[];void push(double f) { ... }double pop(void) { ... }
in file2:
int sp = 0;double val[MAXVAL];
TRU-COMP2130 C Programming 62
Static Variables
The static declaration, applied to an external variable or function, limits the scope of that object to the rest of the source file being compiled.
External static thus provides a way to hide names from other files.
static char buf[BUFSIZE]; // only in this filestatic int bufp = 0; // only in this fileint getch(void) { ... }void ungetch(int c) { ... }
Static in Java has a bit different meaning.
TRU-COMP2130 C Programming 63
Register Variables
A register declaration advises the compiler that the variable in question will be heavily used.
The idea is that register variables are to be placed in machine registers, which may result in smaller and faster programs. But compilers are free to ignore the advice.
register int x;register char c;
f(register unsigned m, register long n) { register int i; ...}
Usually for index variables used in loop structures
TRU-COMP2130 C Programming 64
Initialization
Very similar to Java
In the absence of explicit initialization, external and static variables are guaranteed to be initialized to zero; but automatic and register variables have undefined (i.e., garbage) initial values.
TRU-COMP2130 C Programming 65
The C Preprocessor
File inclusion#include “filename” // from the working dir
or
#include <filename> // from the standard dir Macro substitution
#define name replacement_text#define max(A, B) ((A) > (B) ? (A) : (B))
Conditional inclusion#if !defined(HDR) // or #ifndef HDR #define HDR /* contents of hdr.h go here */#endif
TRU-COMP2130 C Programming 66
#if SYSTEM == SYSV #define HDR "sysv.h"#elif SYSTEM == BSD #define HDR "bsd.h"#elif SYSTEM == MSDOS #define HDR "msdos.h"#else #define HDR "default.h"#endif#include HDR