1 cs 162 introduction to computer science chapter 3 review c++ basics herbert g. mayer, psu status...

45
1 CS 162 Introduction to Computer Science Chapter 3 Review C++ Basics Herbert G. Mayer, PSU Status 11/10/2014

Upload: frank-walker

Post on 24-Dec-2015

219 views

Category:

Documents


1 download

TRANSCRIPT

1

CS 162Introduction to Computer Science

Chapter 3Review C++ Basics

Herbert G. Mayer, PSUStatus 11/10/2014

2

Syllabus C++ Program

g++ compiler

Lexical Rules

C++ Language Modules

Data Types

Expressions

Functions

External Names

Loops

Conditional Statements

3

Assumption Students have prior exposure to the C or C++

languages Understand some C++ elementary data

types, knows how to run programs, to write and call functions

Understand formal parameters, specifically value parameters

And knows the data type array All this will be refined and expanded here

4

C++ Program C++ programs define, input, manipulate, and output

data: using macros, data declarations, and executable statement

Data have types, which can be declared via predefined type names or by symbolic types names to define objects of such type: the latter by typedef

Actions of data manipulation are referred to as: execution of the C++ program

C++ and C strictly speaking execute actions in expressions, yet we shall refer to them as statements

Expressions also compute values, of such types as array, bool, char, int, float, pointer, struct, union, and some higher precision version of some scalar types

5

C++ Program Execution is logically grouped into modules, named

functions

A C++ program must specify one function, named main(), which defines where execution starts

There may be any number of further functions

Some of those, and perhaps data, can be defined in one or multiple compilation units (CU)

All CUs jointly have but one main() function

Data and functions declared in other CUs must be specified as extern to render them visible

Any data or function referred to in statements must be declared; in case of forward referencing issues such names must be announced, completed later in the text

6

Compile Command for g++

The GNU Project provides a freely available, open source C compiler called g++

Syntax for compiling a program via Unix command line:

g++ [options] file_list

where:

g++ → compiler name (in lowercase)

[options] → compilation options (optional)

file_list → list of source and/or object files

7

g++ Compiler Options

Option Description

-std=xxx

–std=c90 to compile to ISO C90 standard–std=c99 to compile to ISO C99 standard–std=gnu90 to compile to GNU C90 standard–std=gnu99 to compile to GNU C99 standard

-ansi Same effect as –std=c90

-pedantic Issue warning if C source is not strictly ISO compliant

-Wall Issue warnings on all questionable C constructs

-lm Link to the standard math library(required for some UNIX systems)

-o exec_file

Determines the name of the executable file(can be different from the source file name)

If -o is omitted, the default name is a.out (or a.exe).

8

g++ Compile ExampleYour source file is called prog1.c. Your compiler generates a default executable file named a.out

Type this at the command line (no extra checking):

g++ prog1.c

Or type this at the command line (full checking):

g++ -ansi -pedantic -Wall prog1.c

Or else:

g++ prog1.c

9

g++ Compile Example’Your source file is called prog1.cpp. Your compiler generates a default executable file named a.out

Type this at the command line (no extra checking):

g++ prog1.cpp

Or else to get no compatibility warning:

g++ -Wno-deprecated prog1.cpp

10

g++ Compile Example

Your source file is called mathprog.cpp. You prefer the executable file not to be named a.out, but mprog

Then type this command:

g++ mathprog.cpp –o mprog

11

g++ Compile Example

Your source files are ted.cpp and alice.cpp

You want the executable file to be named jupiter2

Type this at the command line:

g++ -Wno-deprecated ted.cpp alice.cpp –o jupiter2

12

Lexical Rules

C++ source program are free format, but to ease readability programmer should use line-feeds, indentation, and white space wisely

Programs consist of white-space, special symbols, reserved keywords, literals, and user-defined identifiers

13

Lexical Rules: White Space

C++ sometimes requires blanks to separate certain lexical tokens

White space consists of blanks, empty lines, tabs, comments, or any combinations of those

Line comments are introduced by the // double slash, which skips all text up to the end of the current line

Block comments are introduced by /* and ended by the matching s*/. All text in between is ignored

Comments cannot be nested; i.e. as soon as the end of some comment is found, subsequent text is considered part of the program

14

Lexical Rules: C++ Special Symbols

15

Lexical Rules: Reserved Keywords

All keywords reserved in the C programming language are also carried over into C++. There are 32 such inherited reserved words:

auto const double float int short struct unsigned

break continue else for long signed switch void

case default enum goto register sizeof typedef volatile

char do extern if return static union while

16

Lexical Rules: Reserved Keywords

There are 30 additional C++ reserved keywords not part of C, new in C++. If certain C programs are compiled as-is with a C++ compiler, and such C programs happen to use –as identifiers– new C++ keywords, they cause compilation errors. Some C++ compilers allow switches to gracefully handle such conflicts

asm dynamic_cast namespace reinterpret_cast try

bool explicit new static_cast typeid

catch false operator template typename

class friend private this using

const_cast inline public throw virtual

delete mutable protected true wchar_t

17

Lexical Rules: Literals Integer literals of base 10 consist of 1 or more

decimal digit ‘0’..’9’

Except for the value 0 the first digit of a decimal integer may not be 0

Octal digits are integers of base 8; their first digit must be 0; only digits ‘0’..’7’ are allowed

Hexadecimal literals are introduced by 0x, and may contain the 10 decimal digits, and 6 more for the values 11 to 15, written as ‘a’..’f’, or uppercase ‘A’..’F’. Example: 0x2a, stands for decimal 42

Char literals are enclosed between a pair of ‘ and ‘, for example: ‘A’ for upper case a. Some non-printable special characters are escaped by \, e.g. ‘\n’, ‘\t’, ‘\0’ ‘\\’

18

Lexical Rules: Literals There is no true string type in C++, but string literals

are included; they are character strings enclosed between a pair of “. For example “Hello” defines string Hello. An implied ‘\0’ character is appended at each string literal; thus “Hello” is 6 characters long

Float (AKA floating-point) literals are numeric literals with a possible fraction. They can have integer and fractional parts, be signed, and be scaled; e.g.:

3.142592 // for PI+3.142592 // for PI with redundant sign-3.142592 // negative PI0.3142592E1 // PI scaled by factor * 1031.42592E-1 // PI scaled by 10-1

Bool literals are: true and false

19

Lexical Rules: Identifiers C++ Identifiers consist of 1 or more letters ‘a’..’z’,

‘A’..’Z’, digits ‘0’..’9’ and ‘_’ underscores Underscore counts as a letter Excluded are reserved keywords The first character must be a letter or underscore _ Identifiers are case sensitive, i.e. MyMin and Mymin

are distinct, legal identifiers They must fit on 1 line The maximum length depends on the C++ compiler,

i.e. it is possible to write a test program with seeming distinct identifiers that will fail to compile correctly on some compilers

Good advice to “not make them too long,” i.e. not longer than, say, ½ line worth of characters

20

C++ Language Modules A C++ program consists of 1 compilation unit (CU)

or more, exactly one of which must specify the main() function

Each CU is a named file, generally with the .cpp file name extension; extension .c is also legal

A CU may contain comments and white-space, macro definitions, type specifications, data declarations, external declarations, forward announcements, and functions

A CU may include other text via so called #include actions; these may include into the current CU actual files, or predefined actions provided by the C++ run-time system

21

C++ Language Modules: comments Comments are meant to clarify, where the pure

source might not be adequate A // sequence not part of a string literal starts a line

comment, which skips every charac ter up to the end of the current line

A /* sequence starts a block comment, which may be any number of characters long, and ends at the next possible */ sequence

Samples:

// define globally visible struct

// and init its sole field in init()

/* another comment, ending . . .

* on next line:

*/

22

C++ Language Modules: macros C++ macros allow the textual substitution of

program parts, with the goal of writing more compact and easier to maintain source programs

A macro definition starts with the #define directive, followed by the macro name and macro body

Macros may have formal macro parameters, which are substituted at macro invocation by their matching actual parameters

Then comes the macro body, which will be textually expanded each time the macro name occurs in the source

All of this is written logically on 1 line; but if physically multi-line macro bodies are needed, this can be simulated with the \ line continuation character at the end of each line of text

23

C++ Language Modules: macros Simple macro definition:#define MAX 1000

Macro use:float matrix[ MAX ][ MAX ]; // used for linear algebra equation

More complex macro definition:#define ASSERT( condition, message, value )

\

if ( ! ( condition ) ) {\

printf( "<><> error: %s. Is instead: %d\n", message, value ); \

}

Macro use:ASSERT( value == 110, ”change_int_val should be 110", value );

24

C++ Language Modules: typedefC++ typedefs define new symbolic type names, used for consistent type naming

#define NUM_ELEMENTS 100

// define type for integer array of 100 elements:

typedef int int_arr_tp[ NUM_ELEMENTS ];

int_arr_tp a1; // object a1[], type: int array

void sample( int_arr_tp a ) // formal a[], type: int array

{ // sample

a[ i ] = . . .

25

C++ Language Modules: extern Scope attribute extern explains that the actual,

named object is defined in a different compilation unit (CU), but that name can be referenced here

Scope attribute global –i.e. defined outside any function body– and without static qualifier is externally global, visible in another CU as well!!

Combination of the 2 allows one name to be used in 2 CUs

Example below defines int foo to be external, using the g++ compile command; foo is defined in ext1.cpp, and referred to as an extern in ext2.cpp; the command below compiles and links both:

g++ ext1.cpp ext2.cpp

26

C++ Language Modules: extern// compilation unit ext1.cpp

// just a single int: foo

int foo = 109;

// compilation unit ext2.cpp

#include <stdio.h>

main( void )

{ // main

extern int foo;

printf( “foo = %d\n”, foo );

return 0;

} //end main

Output: foo = 109

27

Data Types Objects manipulated by C++ programs have defined

types; some other languages are more lax

We say: “C++ is a loosely typed language”, since objects entering into operations must be compatible with required types, yet a few implied conversions (e.g. char and int, or int and float) are allowed: But doing so without casting can be dangerous

Predefined types include: array, bool, char, double, int, float, struct, union, unsigned, and void; most of those are reserved keywords in C++ (and C)

Typedef, arrays, pointers, unions, and structs allow the user to craft more complex types suitable for specific use

Complex types allows us to build complicated data structures, such as trees, B-trees, graphs, etc.

28

Data Type: bool

Identified by reserved keyword bool

Objects of type bool can be assigned boolen expressions, including literals true and false

Example:

bool found;

bool b1, b2;

bool in_set = false;

if ( in_set ) { // then . . .

29

Data Type: char

Identified by reserved keyword char

Objects of type char can be assigned small integer expressions, including char type literals, e.g. ‘X”

Example:

char c;

char small_a = ‘a’, big_a = ‘A’;

char c1;

. . .

c1 = ( c>=‘A’ ) && ( c<=‘Z’ ) ? c -’A’ : c;

30

Data Type: float

Identified by reserved keyword float

Objects of type float can be assigned floating-point expressions, including float literals; consts cannot be assigned

Example:

float f1;

const float pi = 3.1415926535897932384626433832;

float f2 = 0.314159E1;

float f3 = 0.314159E+1;

float f4 = 31.4159E-1;

float f5 = +3.14159E0;

31

Data Type: double Identified by reserved keyword double

Objects of type double-precision floating-point can be assigned long floating-point expressions:

#include <stdio.h>#define PI 3.14259#define LPI 3.14159265358Lfloat f = PI;double fl = LPI;int main( void ){ // main

printf( " format f %f\n", f ); printf( " format fl %fl\n", fl );

return 0;} //end main

format f 3.142590 format fl 3.141593l

32

Data Type: int Identified by reserved keyword int

Int can be unsigned; cab be abbreviated unsigned

Objects of type int can be assigned integer type expressions, including literals, such as 0, 100, 0x34, and char values, causing implicit type conversion

Example:

int i;

int year = 2014;

const int this_year = 2014; // no change

int limit = LONG_MAX:// from limits.h

int j = -1;

33

integer Limits, from <limits.h>

34

Data Type: struct

Structures are single, composite objects consisting of multiple named fields of possibly different types

Introduced by reserved keyword struct In C++ we refer to them as structure or struct Note difference with arrays, where all

elements are of the same type, identified by indexing; in struct all fields may be different, but can be the same too

C++ allows assignment of structs, though not the assignment of arrays!

35

Data Type: struct Best to use typedef, and then reference

new type name for struct objects and struct parameters

The struct name refers to the whole, complete structure

The elements are accessible through qualified naming, identified by the . special symbol

Formal parameters may, of course, be of struct type

And are by default: value parameters In C++ they can be specified as reference

parameters via the & operator

36

Data Type: struct Sample 1

typedef struct str { int i_field; float f_field; char c_field;} str_type;str_type s1, s2; int demo_struct( void ){ // demo_struct str_type s3, s4, s5; s1.i_field = 2014; s1.f_field = 2014.5; s1.c_field = 'h'; cout << "field s1.c = '" << s1.c_field << "'" << endl; s3 = s1; cout << "field s3.i_field = " << s3.i_field << endl; . . .

37

Data Type: struct Sample 2

38

Data Type: struct Sample 3typedef struct str { int i_field; // some int char * s_ptr; // some string} str_type;str_type s1, s2; void str_demo_val( str_type s ){ // str_demo_val s.s_ptr = "inside val"; cout << "in str_demo_val, s.s_ptr = " << s.s_ptr << endl;} //end str_demo_val int main( void ){ // main

str_type s3, s4;s1.s_ptr = "China is beautiful"; s2 = s3 = s1;str_demo_val( s3 );cout << "after str_demo_val, s_ptr = " << s3.s_ptr << endl;

} //end main

in str_demo_val, s.s_ptr = inside valafter str_demo_val, s_ptr = China is beautiful

39

Data Type: struct Sample 4typedef struct str { int i_field; char * s_ptr;} str_type;str_type s1, s2; // two global structs,

s1 and s2  

void str_demo_ref( str_type & s )// ref struct parameter s{ // str_demo_ref s.s_ptr = "inside ref"; // changes actual! cout << "in str_demo_ref, s.sptr = " << s.s_ptr << endl;} //end str_demo_ref

int main( void ){ // main str_type s3, s4; s1.s_ptr = "China is beautiful"; s2 = s3 = s1; cout << ”before str_demo_ref, s3.s_ptr = " << s3.s_ptr << endl; str_demo_ref( s3 ); cout << "after str_demo_ref, s3.s_ptr = " << s3.s_ptr << endl;} //end main before str_demo_ref, s3.s_ptr = China is beautifulin str_demo_ref, s.sptr = inside refafter str_demo_ref, s3.s_ptr = inside ref 

40

Data Type: pointer Identified by pointer type special symbol *

Point to other C++ objects, via pointer of operator &

. . .int main( void ){ // main

int i = 2014; // i is integerint *pi = & i; // pi is pointer to icout << " i = " << i << ", *pi = " << *pi <<

endl;printf( "size of pi = %d\n", sizeof( pi ) );printf( "pointer pi = %d\n",

abs( int( pi ) ) );} //end main

i = 2014, *pi = 2014size of pi = 4pointer pi = 4195780

41

Data Type: pointer, More Samples#include <iostream.h>#include <stdio.h>int i = 10; // intconst int ci = 11; // int constconst int * pic = & ci; // ptr to int constint * const cpi = & i; // const ptr to int

const int * const cpic = pic; // const ptr to int const

int main(){ //main cout << " i = " << i << endl; cout << " ci = " << ci << endl; cout << " pic = " << (int)pic << endl; // C++ printf( " pic = %d\n", pic );

// C cout << " *pic = " << *pic << endl; cout << " cpic = " << (int)cpic << endl; cout << "*cpic = " << *cpic << endl; // legal stuff return 0;} //end main

42

Data Type: pointer, More Samples

i = 10 ci = 11 pic = 70732 pic = 70732 *pic = 11 cpic = 70732*cpic = 11

43

Data Type: array An array is a composite data structure of 1 or more

elements, all of the same type

Each element of an array with size elements is accessible through indexing

The lowest (first) index is 0; the last index is size-1

Arrays may be passed as parameters, in which case they are formal reference parameters; this is the same as other C++ parameter types declared with &

Indexing is accomplished via integer expressions in [ and ] brackets

The index expression must refer to a legal element, lest array bounds are violated

The elements of an array may be arrays

44

Data Type: array

45

Array Manipulation

Touch all i columns of an array’s row, a[ row ][ i ] and all i rows of an array’s column col, b[ i ][ col ] to perform some arithmetic

This C++ code may be the inner loop, nested inside a doubly nested loop that handles all rows and all columns of a 2-D array