Skip to main content
goto
•
•
•
goto allows you to jump unconditionally to arbitrary part o
f
your code (within the same function).
the location is identified using a label.
a label is a named location in the code. It has the same
form as a variable followed by a ’:’
start :
{
i f ( cond )
goto outside ;
/∗
some code /
∗
goto start ;
}
outside :
/∗ outside block /
∗
5
error handlin
g Language like C++ and Java provide exception mechanism to
recover from errors. In C, goto
provides a convenient way to exit from nested blocks.
f o r
( . . ) {
f o r
( . . ) {
i f ( error_cond )
goto
e r r o r ;
/∗ skips 2 blocks ∗
}
}
e r r o r
:
/
}
cont _flag =1;
for ( . . ) {
for ( i n i t ; c o n t _ f l a g ; i t e r
)
{
i f ( error_cond )
{
c o n t _ f l a g =
0;
break ;
}
/∗
i n n er loop /
∗
}
i f ( ! c o n t _ f l a g ) break ;
/∗ outer loop /
∗
7
Preliminarie
s
•
•
•
•
Input and output facilities are provided by the standard
library <stdio . h>
and not by the language itself.
A text stream consists of a series of lines ending with
The standard librar
y takes care of conversion from
’rn’ ’
− n’
A binar y stream consists of a ser ies of raw bytes.
The streams provided by standard library are buffered.
.
’n’
8
Standard output:formatt
ed
int char
printf (
printf (
printf (
pr
intf (
format [],
arg1,arg2 ,...)
);
format: %d (integer),argument:10 ∗
,10 ,20);
/
• printf() can be used for formatted output. •
It takes in a variable number of arguments. •
It returns the number of characters printed. •
The format can contain literal strings as well as format
specifiers (star
ts with %).
Examples:
"hello worldn"
"%dn" , 1 0 ) ; / ∗
"Prices:%d and%dn"
11
printf format specificatio
n
type
d,i
x,X
u c
s f
d
e,E
%
meaning
integer
integer (hex)
unsigned integer
character str
ing float
double
float(exp)
literal %
example
The format specification has the following component
s
%[flags ][ width ][. precision ][ length]<type>
type:
printf ( "%d",10); /
printf ( "%x",10); /
printf ( "%u",10); /
printf ( "%c",’A’); /
∗prints
10 /
∗ ∗
print 0xa /
∗
prints
∗
10 /
∗
prints
∗
A /
∗
printf ( "%s","hello"); / ∗pr
ints hello /
∗
printf ( "%f",2.3);
/
∗
prints 2.3 /
∗
∗
prints 2.3 /
∗
printf ( "%d",2.3);
/
1e3,1.2E3,1E −3
printf ("%d %%",10); /∗pr
ints 10% /
∗
12
printf format specification (con
t.)
pr
intf
( pr
intf
( pr
intf
( pr
intf (
,10)
,10)
,
,
)
)
%[flags ][ width ][. precision ]
[ modifier]<type>
width:
format output "10"
bb10 (b:space)
hello bbhello
"%d"
"%4d
"
"%s" "hello"
"%7s" "hello"
13
printf format specification (con
t.)
pr
intf
( pr
intf
( pr
intf
( pr
intf (
,10)
,
,
,10,
)
)
%[flags ][ width ][. precision ]
[ modifier]<type>
flag:
−10)
format output
10,+10,-10
0010
bbhello
hellobb
"%04d
"
"%d,%+d,%
+d"
"%7s" "hello"
"%-7s" "hello"
14
printf format specification (con
t.)
pr
intf
( pr
intf
( pr
intf
( pr
intf (
,
,
)
)
%[flags ][ width ][. precision ]
[ modifier]<type>
precision:
format output 1.14,1
1.14e+00,1e+02
hell h
"%.4s" "hello"
"%.1s" "hello"
"%.2f,%.0f,1.141,1.141)
"%.2e,%.0e,1.141,100.00)
15
Digression: character array
s
char ’h’,’e’,’l’’l’
Note:
use " if you want the string to contain ".
Since we will be reading and wr iting str ings, here is a br
ief digression
• strings are represented as an array of characters
• C does not restrict the length of the string. The end of the
str
ing is specified using 0.
For instance, "hello" is represented using the array
{ ’h’,’e’,’l’,’l’,’0’}.
Declaration examples: ∗
•
•
•
str []
=
str
[10]=
str []={
;
/ ∗compiler takes care of size /
;
/
∗make sure the array is large enough
/
∗
, ,0};
"hello"
"hello"
char
char
17
Digression: character array
s
Comparing strings: the header file < string . h> provides the
function int strcmp(char s[],char t [])
that compares two strings in dictionar
y order (lower case letters come after capital case).
• the function returns a value <0 if s comes before t
• the function return a value 0 if s is the same as t
• the function return a value >0 if s comes after t
• strcmp is case sensitive
Examples
strcmp( , ∗ ∗
strcmp
(
strcmp
(
strcmp
(
,
,
)/ <0 /
,
)
/
∗==0∗
/
)
/
∗>0
/
∗
)
/ ∗>0
/
∗
•
•
•
•
"A" "a"
"aA" "a"
"aA" "aA"
"IRONMAN"
"BATMAN"
18
Formatted inpu
t
int scanf(char∗
format ,...) is the input analog of printf.
•
scanf reads characters from standard input, interpreting
them according to format specificatio
n
•
Similar to printf , scanf also takes variable number of
arguments.
• The format specification is the same as that for printf
• When multiple items are to be read, each item is assumed
to be separated by white space.
• It returns the number of items read or EOF.
• Important: scanf ignores white spaces.
• Important: Arguments have to be address of variables
(pointers).
19
Formatted inpu
t
cha
r ∗
pr
intf
( pr
intf
( pr
intf
( pr
intf
( pr
intf
( pr
scanf( format ,...)
,x)
,x)
,f) ,
str)
,str)
,fname,lname)
scanf(
scanf(
scanf(
scanf(
scanf(
scanf(
,&x)
,&x)
,&f) ,
str) /∗
note no & required /
∗
,str)
/
∗note no & required
/
∗
,fname,lname)
int
Examples:
is the input analog of pr
intf.
"%d"
"%10d
"
"%f
"
"%s
"
"%s
"
"%s
%s
"
"%d
"
"%d
"
"%f "
"%s
"
"%20s
"
"%20s
%20s"
20
String input/
output
Instead of wr iting to the standard output, the for
matted data can be wr itten to or read from character arrays.
int sprintf (char string [], char format[],arg1,arg2)
• The format specification is the same as printf. •
The output is written to string (does not check size). •
Returns the number of character written or negative value
on error.
int sscanf(char str [], char format [],
arg1,arg2)
• The format specification is the same as scanf;
• The input is read from str variable.
• Returns the number of items read or negative value on
error.
21
File I/
O
So far, we have read from the standard input and written to th
e standard output.
C allows us to read data from text/binary files using fopen().
FILE ∗
fopen(char name[],char mode[])
• mode can be "r" (read only),"w" (write only),"a" (append)
among other options.
"b" can be appended for binary files.
•
fopen returns a pointer to the file stream if it exists or
NULL otherwise.
• We don’t need to know the details of the FILE data type.
• Important: The standard input and output are also FILE*
datatypes (stdin,stdout).
•
Important: stderr corresponds to standard error
output(different from stdout
).
22
File I/
O(cont.)
int fclose ( FILE∗
fp)
•
•
closes the stream (releases OS resources).
fclose() is automatically called on all open files when
program terminates.
23
File input
int
cha
r
#defin
e
char int
[]
fgets(
getc
( FILE ∗
fp)
line
[],
getchar() getc( stdin )
maxlen,FILE∗
fp)
•
•
•
• reads a single character from the stream. •
returns the character read or EOF on error/end of file.
Note:
getchar simply uses the standard input to read a
character. We can implement it as follows:
reads a single line (upto maxlen characters) from the input
stream (including linebreak).
returns a pointer to the character array that stores the line
(read-only)
return NULL if end of stream.
24
6.087 Lecture 5 – January 15,
2010
Review
Pointers and Memory Addresses
Physical and Virtual Memory
Addressing and Indirection
Functions with Multiple Output
s
Arrays and Pointer Arithmetic
Str ings
Str
ing Utility Functions
Searching and Sor
ting Algorithms
Linear Search
A Simple Sor t
Faster Sorting
Binar
y Search 5
Pointers and
addresses
•
•
•
•
Pointer: memory address of a variable
Address can be used to access/modify a variable from
anywhere
Extremely useful, especially for data structures
Well known for obfuscating code
5
Physical and virtual
memory
•
•
Virtual memory: abstraction by OS, addressable space
accessible by your code
Physical memory: physical resources where data can be
stored and accessed by your computer
cache RAM
hard disk
removable storage
•
•
•
•
6
Physical memory
considerations
•
•
•
Different sizes and access speeds
Memory management – major function of OS
Optimization – to ensure your code makes the best use of
physical memory available
• OS moves around data in physical memory during
execution
• Embedded processors – may be very limited
7
Addressing
variables
•
•
•
•
Address of a variable of type t has type t *
How to find an address of a variable? The
Every variable residing in memory has an address!
What doesn’t have an address?
operator
•
•
•
∗
register variables
constants/literals/preprocessor defines
expressions (unless result is a variable)
&
in
t
doubl
e
in
t
∗
doubl
e
n = 4;
pi = 3.14159;
pn = &n; / ∗ address of integer n /
∗
∗ ppi =&pi; / address of double pi
∗ /
9
Dereferencing
pointers
•
•
•
•
I have a pointer – now what?
Accessing/modifying addressed variable:
dereferencing/indirection operator *
∗ ∗
Dereferenced pointer like any other variable
null pointer, i.e. 0(NULL): pointer that does not reference
anything
/ prints "pi = 3.14159n "
printf ( "pi = %gn" , ∗
ppi );
/∗ pi now equals 7.14159 /
∗
∗ ppi = ppi + pn ;
∗ ∗
/
10
Casting
pointers
• Can explicitly cast any pointer type to any other pointer
type
ppi =(double ∗)pn; / pn originally of type ( int ) /
∗ ∗ ∗
• Implicit cast to/from void * also possible (more next
week. . . )
• Dereferenced pointer has new type, regardless of real type
of data
• Possible to cause segmentation faults, other
difficult-to-
identify errors
• What happens if we dereference now?
ppi
11
Functions with multiple
outputs
• Warning about x and
being used before initialized
• Consider the Extended Euclidean algorithm
ext_euclid(a,b) function from Wednesday’s lecture
• Returns gcd(a, b), x and y s.t. ax + by = gcd(a, b)
• Used global variables for x and y
• Can use pointers to pass back multiple outputs:
int ext_euclid(int a, int b, int ∗x, int y);
∗
• Calling ext_euclid(), pass pointers to variables to
receive x and y:
y
int x, y, g; /
∗ assume a, b declared previously
g = ext _euclid (a,b,&x,&y );
/
∗
12
Accessing caller’s variables
•
•
•
•
Calling
function:
Want to write function to swap two integers
Need to modify variables in caller to swap them
Pointers to variables as arguments
∗
voi
d in
t
x
int
}
swap( int
temp =
= ∗y;
y = temp ;
x,
x;
int a = 5, b = 7;
swap(&a , &b ) ;
/∗ now, a=7, b=5 /
y) {
∗
∗
∗
∗
∗
swap()
13
Variables passing out of
scope
• What is wrong with this code?
char ∗
char
return
#include
}
int main ( void )
<stdio .h>
get_message ( )
msg[] =
msg ;
{
char
puts(string );
return 0;
∗ string = get_message();
}
;
{
"Aren’t pointers fun?"
14
Variables passing out of
scope
•
• What is wrong with this code?
Pointer invalid after variable passes out of scope
char ∗
char
return
#include
}
int main ( void )
<stdio .h>
get_message ( )
msg[] =
msg ;
{
{
char
puts(string );
return 0;
∗ string = get_message();
}
;
"Aren’tpointers fun?"
14
6.087 Lecture 5 – January 15,
2010
Review
Pointers and Memory Addresses
Physical and Virtual Memory
Addressing and Indirection
Functions with Multiple Output
s
Arrays and Pointer Arithmetic
Str ings
Str
ing Utility Functions
Searching and Sor
ting Algorithms
Linear Search
A Simple Sor t
Faster Sorting
Binar
y Search 15
Arrays and
pointers
• Primitive arrays implemented in C using pointer to block of
contiguous memor
y
• Consider array of 8 ints:
int arr [8];
• Accessing arr using array entry operator:
int a = arr [0];
• arr is like a pointer to element 0 of the array:
int ∗pa = arr; � int
pa = &arr[0];
∗
•
Not modifiable/reassignable like a pointer
15
The
operator
sizeof()
•
•
•
• More about
Array length:
∗
next week. . .
For primitive types/variables, size of type in bytes:
int s= sizeof(char); / ∗ == 1 /
∗
∗ sizeof(f) ==8 /
∗ (64-
bit OS)
double
f; /
For primitive arrays, size of array in bytes:
int arr [8]; / ∗ sizeof(arr) == 32 /
∗ (64-
bit OS)
long
arr [5]; /
∗ sizeof(arr) == 40 /
∗ (64-
bit OS)
/ needs to be on one line when implemented ∗
/
#define array _length(arr) ( sizeof (arr) == 0 ?
0 : sizeof ( arr )/ sizeof ((arr )[0]))
sizeof()
16
Pointer
arithmetic
•
•
Suppose int ∗pa = arr
;
Pointer not an int, but can add or subtract an int from a
pointer :
pa + i points to arr[i]
• Address value increments by i times size of data type
Suppose arr[0] has address 100. Then arr[3] has
address 112.
• Suppose char pc= (
∗ char )pa; What value of i
∗
satisfies
(int ∗)( pc+i)
== pa + 3?
17
Pointer
arithmetic
•
•
Suppose int ∗pa = arr
;
Pointer not an int, but can add or subtract an int from a
pointer :
pa + i points to arr[i]
• Address value increments by i times size of data type
Suppose arr[0] has address 100. Then arr[3] has
address 112.
• Suppose char pc= (
∗ char )pa; What value of i
∗
satisfies
(in
t
)
(pc+i) == pa + 3
?
i
∗
• =12
17
6.087 Lecture 5 – January 15,
2010
Review
Pointers and Memory Addresses
Physical and Virtual Memory
Addressing and Indirection
Functions with Multiple Output
s
Arrays and Pointer Arithmetic
Str ings
Str
ing Utility Functions
Searching and Sor
ting Algorithms
Linear Search
A Simple Sor t
Faster Sorting
Binar
y Search 18
Strings as arrays
• Strings stored as null-terminated character arrays (last
character == ’ 0’)
• Suppose char str[] = "This is a string."; and
char∗ pc= str;
• Manipulate string as you would an array
∗
puts( str );
( pc+10) = ;
/* prints "This is a String ."
*/
’S’
18
String utility
functions
•
•
String functions in standard header string.h
Copy functions: strcpy(), strncpy()
char
char
to strt
o
∗ strcpy(strto,strfrom); –copy strfrom
to
∗ strncpy(strto,strfrom,n); –copy n
chars from
• Comparison functions: strcmp(), strncmp()
int
strcmp(str1,str2); – compare
, ; return
0
equal, positive if > , negative if <
str1str2
int strncmp(str1,str2,n); – compare first
chars of
str2
• String length: strlen()
int
strlen ( str ); – get length of str
if
and
str1 str2
str1str2
n str1
strto
strfrom
19
More string utility
functions
• Concatenation functions: strcat(), strncat()
char
char
end of strto
∗ strcat(strto,strfrom); –add strfrom to end of strto ∗
strncat(strto,strfrom,n); –add n chars from strfrom to
• Search functions: strchr(), strrchr()
char
first occurrence, or NULL if not found
∗ strchr(str,c); – find char c
in str, return pointer to
char
last occurrence, or NULL if not found
∗ strrchr(str,c); –findchar c in str, return pointer to
•
Many other utility functions exist. . .
20
File outpu
t int
int
int
#defin
e
int
char
char
putc
(
fputs
(
fscanf
( FILE ∗
c ,
FILE ∗
fp
,
fp)
line [], FILE∗
fp)
putchar(c) putc(c , stdout
)
format [],
arg1,arg2)
•
•
•
•
similar to scanf,sscanf
reads items from input stream fp
.
wr
ites a single line to the output stream.
retur ns zero on success, EOF otherwise.
• writes a single character c to the output stream.
• returns the character written or EOF on error.
Note:
putchar simply uses the standard output to write a
character. We can implement it as follows:
25