Title: C : Introduction
1The bool Type (C)
false, true
promotable to type int false 0, true 1
bool found false int occurrence_count
0 while (/ mumble /) found look_for
(/ something /) // founds value
promoted to either 0 or 1 occurrence_count
found
2References (more)
Primarily used as the formal parameters of
functions.
// return status of access. place value in
parameter bool get_next_value (int next_value)
An invocation
int ival while (get_next_value (ival)) //
value of ival may be modified
// during the call ---
call by reference
The parameter binding is equivalent to the
definition int next_value ival
3No Array of References
int ia 0, 1, 2 const int array_size
3 int ix, jx, kx // ok array of pointers of
type int int iap ix, jx, kx //
error array of references not allowed int iar
ix, jx, kx
4Enumeration Types
// black 0, blond 1, brunette 2,
red 3 enum HairColor black, blond,
brunette, red HairColor hc black
enum Month Jan1, Feb, Mar, Apr,
May, Jun, July, Aug, Sep, Oct, Nov,
Dec Month Mon Dec
5C-style Character Strings
char st STRING char st1
// in order to use the following
functions include // return the
length of the string int strlen(const char)
// strlen(st) 6 \0 not counted // compare
two strings for equality int strcmp(const char,
const char) // copies the second string into the
first int strcpy(char, const char)
C Primer, 3rd ed. by S. B. Lippman and J.
Lajoie.
6More on C Strings
include const char st The
expense of spirit\n
22
void main() int len 0 while
(st) len st st len 1 //
not elegant cout endl
terminating null char
The expense of spirit\n\0
st
Output 22 The expense of spirit
7Application Reversing Names
char Name11Tom Hanks, Newname30 char p
NULL
k
s
H
a
n
T
o
m
p strchr(Name, ) // pointer to the first
blank
p
p 0 // replace blank with NULL
strcpy(Newname, p1) // copy the last name
strcat(Newname, , ) // add , and blank
strcat(Newname,Name) // concatenate the first
name
8C String Class
include // include the associated
header file string st (The expense of
spirit\n) cout st characters, including the newline\n
To test an empty string
if (!st.size()) // ok empty
or, more directly,
if (st.empty()) // ok empty
9Initialization Copying
string st3(st) if (st st3) // the
initialization worked string st2 // empty
string st2 st3 // copy st3 to st2
How is copying performed?
10String Arithmetics
string s1(hello, ) string s2(world\n)
string s3 s1s2 // s3 hello,
world\n s1 s2 // s1
hello, world\n
Mixing C string objects and C character
strings string s1( hello )
string s2( world ) const char pc ,
string s3 s1 pc s2 \n
11Assignment of C-style Char Strings
string s1 const char pc a character array
s1 pc // ok char str s1 //
compile-time type error
No support for implicitly converting a string
object to a C char string.
const char str s1.c_str() // ok
12Access of Characters
string str(cs.iastate.edu ) // replace all
periods with an underscore. int size
str.size() for (int i 0 i if (stri .) stri _ //
cs_iastate_edu
Or, use a generic algorithm (topic in the
future)
include include replace
( str.begin(), str.end(), ., _)
13const Qualifier
for ( int index 0 index // 1. what does the number 512 mean? // 2. if
we need to use 1024 instead, we have to
change // the 1024 occurrences of 1024 in
our program. -(
Two needs for const - readability
- maintainability
const int bufSize 512 // input buffer size
// avoids accidental change of the value of
bufSize for ( int index 0 index index ) // problems 1 2 are now
fixed. if (bufSize 0) // error attempt
to write to const object
14Usage of const
const double pi // error uninitialized
const const double minWage 9.60 double ptr
minWage // error attempt to have a pointer
// to a
nonconstant address a constant. const double
cptr 0 cptr minWage // ok
now
int errNumb 0 int const curErr errNumb
// ok, a constant pointer to a //
nonconstant object curErr myErrNumb //
error attempt to assign to a constant
// pointer (not
strictly enforced sometimes)
const double pi 3.14159 const double const
pi_ptr pi // a constant pointer to
// a constant object
15Type Conversions
Implicit type conversion - promoting
the smaller type to a larger type in arithmetic
- carried out automatically by the compiler
int ival 0
ival 3.451 3 // truncation
// all integral types smaller than an integer
are promoted to an // integer
before evaluation. char cval
bool found enum mumble m1, m2, m3 mval
unsigned long ulong cval ulong ulong
found mval ulong
16Explicit Conversions
static_cast, dynamic_cast, const_cast, and
reinterpret_cast
- dereferencing a void pointer
void pv const char pc a casting call pc
static_cast(pv)
- overriding the usual standard conversions
- double dval 8.6
- int ival 5
- ival static_cast ( dval ) 2.7
- ival dval // ival 13 loss of
data!
- disambiguating multiple conversions
17Other Types of Conversion
const_cast casts away the const-ness extern
char string_copy( char ) // function defined
in another file const char pc_str char pc
string_copy( const_cast(pc_str))
reinterpret_cast performs a low-level
reinterpretation complex pcom char
pc reinterpret_cast (pcom)
dynamic_cast converts the pointer to a base
class to a pointer to a derived class,
18The iostream Library
Standard stream objects
include include void
main() string in_string // write
literal string to users terminal cout please enter your name // read users
input into in_string cin in_string
if (in_string.empty()) //
generate an error message to users terminal
cerr empty!\n else cout in_string
19File Input/Output
include include // must
be included to use the file stream
ofstream velocityProfile("velocities.txt") //
tied a pointer to the file velocities.txt
for (int i0 ii 0.02 // input velocity Collision(
vInput, vOutput) // generate velocity after
collision velocityProfile vOutput velocityProfile.close() // close the file
pointer
// the pointer will be automatically closed
at the end of
// the function if not using close()
20File Input/Output (contd)
include include include
int main() int num
string ifile cout of file to sort cin ifile
ifstream infile(ifile) if (!infile)
cerr input file endl return -1
infile num // number of integers to sort
string ofile ifile .sort
// construct an ofstream output file
ofstream outfile(ofile.c_str()) if
(!outfile) cerr unable to open output file
int items new int num for
(int i 0 i
itemsi // read the integers //
sorting // output for (i 0
i outfile
21End of File
The function eof() returns true when no more data
to read, i.e., when its at the end of the file,
and false otherwise.
void main(void) int data //
file contains an undermined number of integer
values ifstream fin // declare stream
variable name fin.open("myfile",iosin)
// open file assert (!fin.fail(
)) fin data // get first
number from the file (priming the input
statement) // You
must attempt to read info prior to an eof( )
test. while (!fin.eof( )) //if not at
end of file, continue reading numbers
cout numbers to screen fin
data //get next number from
file fin.close( ) //close
file
22Structs
Aggregate data items into a single named variable.
? Declare a struct
struct StudentScore string name
double score p
members or fields
(possibly of different types)
? Declare struct variables
StudentScore student1 // storage
allocation StudentScore student2 John Doe,
79.5
23An Example
enum suit clubs, diamonds, hearts, spades
typedef int pips struct card suit
s pips p // 1 13 // means A, 2,
, 10, J, Q, K card c1, c2 // storage
allocation for c1 and c2
24struct Access Initialization
enum suit clubs, diamonds, hearts, spades
typedef int pips struct card suit
s pips p // 1 13 // means A, 2,
, 10, J, Q, K card c1, c2 // storage
allocation for c1 and c2
card pc c1 c1.p 5 c1.s diamonds
c2.p 12 c2.s spades cout p // output c1.p cout // output c1.s
25Combining Arrays and Structs
// arrays of structs StudentScore
cs228Scores50 cs228Scores0.name Ringo
Starr cs228Scores0.score 91.0
// anonymous declaration // and
initialization struct int a, b, c
triple2 3, 3, 6 , 4, 5, 5
// struct containing an array struct
FavoriteThings string animal string
food int numbers4 FavoriteThings
myFavorites myFavorites.food chocolate
myFavorites.numbers3 42
26Stacks
A special version of linear list where items are
added and deleted at only one end of the list
called the top.
Push
Pop
top
Pop
7
7
top
top
top
7
5
top
5
5
5
5
3
3
3
3
3
2
2
2
2
2
ch_stac1.h, ch_stac1.cpp
Last-in, first-out (LIFO)
272-D Dynamic Array of struct
// Dynamic arrays in two dimensions struct twod
double base int
row_size, col_size
0 1 col_size-1
0
base
1
row_size-1
void allocate(int r, int c, twod m)
m.base new double r for (int i 0
i c m.row_size r m.col_size
c
void deallocate(twod m) for (int i 0 i
delete m.base m.row_size 0
m.col_size 0