68
PART 2 Features of C++ Project management Constants and variables Data types and operations Expressions and assignment Control structures and looping Type casting Default parameters

PART 2 Features of C++ - Hi

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: PART 2 Features of C++ - Hi

PART 2

Features of C++

• Project management

• Constants and variables

• Data types and operations

• Expressions and assignment

• Control structures and looping

• Type casting

• Default parameters

Page 2: PART 2 Features of C++ - Hi

Part 2, Page 2 C++ Programming

maxline.cpp /* MAXLINE.CPP: Find & print the longest line from input. Functions in separate files, parameters passed */ // iostream.h should be in all files containing I/O #include <iostream> using namespace std; // all functions invoked should be declared external // and their type should be specified extern int getline(char [], int); extern void copy(char [], char[]); main() // Computes and prints the longest line { const int maxline=1000; // maximum input line size int len, // current line length max = 0; // maximum length seen so far char line[maxline], // current input line save[maxline]; // longest line saved here while ( (len = getline(line, maxline)) > 0 ) if (len > max) // beat previous length { max = len; // record this length copy(save, line); // and save line } if (max > 0) // there was a line { cout << "\nlength of longest line: " << (max-1); cout << "\nthe longest line is:\n\n"; cout << save << endl; } return 0; }

Page 3: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 3

SEPARATE SOURCE FILES

• Sometimes source code is so long that it must be divided into files.

• Sometimes source code exists in project source code libraries for common use.

• When defining classes and objects, each group of class definitions will generally reside in a separate file.

• Variables and functions used across files must be declared in such a way that needed information is available when each file goes through the compiler. The extern specifier declares that variables and functions are to be found in other files. Actually, since functions are external by default, the extern specifier could have been omitted in front of the declarations (prototypes) for the functions getline and copy.

• Each file can be compiled separately, or several files can be compiled together.

• Finally, the parts are linked together to form the final executable version of the program.

• For example, main, getline, and copy are divided into three files, with function main() in file maxline.cpp, function getline(s, lim) in file getline.cpp, and function copy(s1,s2) in file copy.cpp.

• Note that the function main() in file maxline.cpp requires two extern statements to declare the functions called by the function main(), but not defined in the file maxline.cpp.

Page 4: PART 2 Features of C++ - Hi

Part 2, Page 4 C++ Programming

getline.cpp /* GETLINE.CPP this routine fetches a line - the file needs a define for input */ #include <iostream> using namespace std; // the file needs no external statements int getline(char s[], int lim) // Get input line into array s. Check is // performed to avoid overflowing the array. The // function getline returns the length of the input // line, including a newline character, if present. // The array s is terminated with an ascii null { char c; // input character int i = 0; // intra-line counter while( i<lim-1 && cin.get(c) && c != '\n' ) s[i++] = c; if (c == '\n') // did we fall out with a \n? s[i++] = c; // if so, keep it s[i] = '\0'; // always terminate strings! return(i); }

Page 5: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 5

copy.cpp // COPY.CPP: separately compiled function to copy a string // needs no includes, defines, or externals // copy 'from' into 'to'; assume 'to' is big enough void copy(char to[], char from[]) { int i = 0; // string position counter while( (to[i] = from[i]) != '\0' ) // move & check ++i; }

Page 6: PART 2 Features of C++ - Hi

Part 2, Page 6 C++ Programming

Compiling Separate Files Without A Project Manager

VMS

cxx getline cxx copy cxx maxline link maxline, getline, copy run maxline

Turbo C++

tcc -c getline tcc -c copy tcc maxline getline.obj copy.obj maxline

Borland C++

bcc -c getline bcc -c copy bcc maxline getline.obj copy.obj maxline

Page 7: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 7

SEPARATE COMPILATION

• Many times there are common functions that do not change. It is inefficient to recompile a function each time it is used in a program.

• The idea is to not only divide the source code into separate files, but also to compile these files separately, storing the compiled version of the program rather than the source code.

• Separate compilation reduces compile time if there are many programs that need the functions stored in getline.cpp and copy.cpp, or if they are lengthy functions not subject to frequent change.

• Without a project management system, the programmer needs to keep track of which programs need compilation and which ones don't, then supply the appropriate command-line options during compile. This is an error-prone process.

• The -c option on the tcc or bcc command tells the compiler to suppress the loading phase of the compilation (thus not looking for a function main(), nor expecting all parts of the program to be present.) It also forces the creation of the object files getline.obj and copy.obj, respectively.

• An integrated project manager, in contrast, keeps track of when each source code file was last modified and last compiled. It keeps track of the source code files contributing to each object file and when the object file was last created. It keeps track of all of the files contributing to any .exe files and when each was made.

• Before executing a program in an integrated project manager, the system determines which source code needs to be re-compiled, which object files need to be re-linked, and which executable need to be re-built. This removes sources of errors.

• The project needs to be configured (once) by inserting the source code files, by category, into the project. While this is more work than a command-line compile, it only needs to be done once.

• For large projects, the project is placed in its own workspace. The source code files for the project are placed in a separate directory, perhaps with subdirectories.

Page 8: PART 2 Features of C++ - Hi

Part 2, Page 8 C++ Programming

maxline2.cpp /* MAXLINE2.CPP: Find & print the longest line from input. Uses global variables, no parameters passed */ #include <iostream> using namespace std; const int maxline = 1000; // maximum input line size int max = 0; // maximum length seen so far char line[maxline]; // current input line char save[maxline]; // longest line saved here int getline(void); void copy(void); // Computes and prints longest line; specialized version main() { int len; // current line length max = 0; while ( (len = getline()) > 0 ) if (len > max) // beat previous length { max = len; // record this length copy(); // and save line } if (max > 0) // there was a line { cout << "\nlength of longest line: " << (max-1); cout << "\nthe longest line is:\n\n"; cout << save << endl; } return 0; }

Page 9: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 9

maxline2.cpp EXPLANATION

• The three functions comprising this program file accomplish the same goal as in maxline1.cpp, but are organized in a very different way.

• In maxline1.cpp, all data was local to each function. Whenever one function needed information from another it had to be passed back and forth via parameters and return values. This is not always practical.

• In maxline2.cpp, the integer max, and the character arrays line and save are defined to be external (or global) variables. This means they are available to all functions that want them without using parameters or return values. An external definition is made by merely placing the definition outside of any function.

• Since the philosophy of data sharing between functions has been altered, the declarations of the functions, as well as the functions themselves, must be altered. No data needs to be passed to getline, so we must declare that getline takes no parameters. This is done with the statement

int getline(void); which also declares that getline will (still) return an integer.

• Likewise, the function copy does not need any parameters, and, since it doesn't need to return any values either, it is declared as

void copy(void);

• For a function to use an external variable defined in the same file, it need do nothing but use the variable name in the correct way. For a function to use an external variable defined in another file, it must declare its use at the beginning. If another function that wished to use the variable max were written with its source code in a different file, it would need to have the following statement in the beginning:

extern int max;

Page 10: PART 2 Features of C++ - Hi

Part 2, Page 10 C++ Programming

maxline2.cpp (continued) /* Get input line into array line. The function getline returns the length of the input line, including a newline character, if present. The array line is terminated with an ascii null; specialized version */ int getline(void) { char c; // input character int i = 0; // intra-line counter while( i<maxline-1 && cin.get(c) && c != '\n' ) line[i++] = c; if (c == '\n') // did we fall out with a \n? line[i++] = c; // if so, keep it line[i] = '\0'; // always terminate strings! return(i); } // copy: copy 'line' into 'save'; // assume 'save' is big enough; specialized version void copy(void) { int i = 0; // string position counter while( (save[i] = line[i]) != '\0' ) // move & check ++i; }

Page 11: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 11

maxline2.cpp EXPLANATION (Continued)

• Note that this program becomes "easier" to write without parameters. It will probably also achieve minor performance gains in execution speed.

• The functions, however, are much less general. They will only work with properly named external variables. The external names also get involved in the linking process. So while execution may go a bit faster, compiling and linking will take longer.

• In general, external variables should be avoided in favor of passing parameters at almost all costs. The most notable exception to this rule is for keeping track of machine status information across a variety of routines. In particular, error status is the most common status information that might require the use of global variables.

Page 12: PART 2 Features of C++ - Hi

Part 2, Page 12 C++ Programming

UNIX AND DOS REDIRECTION AND PIPES

• Normally, a C++ program written for a UNIX or DOS system is written to read its data from "standard input" and write its data to "standard output." Usually, standard input and standard output default to the user terminal.

• If it is desired to take input from a file rather than the terminal, input redirection can be used. This is done by using the < sign followed by the filename. For example, suppose that the C++ program maxline.cpp has been compiled to generate the executable file maxline.exe. To run the program, taking input from the file named mydata.dat, the following command is used:

maxline < mydata.dat

• Likewise, if it is desired to send the output to a file rather than to a terminal, output redirection can be used. This is done by using the > sign followed by the filename. Thus to run the maxline program sending the output to the file named myoutput.dat, the following command is used:

maxline > myoutput.dat

• Both input and output can be redirected in a single command as follows:

maxline < mydata.dat > myoutput.dat

• Sometimes it is desirable to make the output of one program the input to another following program. This is done by using the pipe construction. A pipe is constructed by placing a | character between the two processes. For example, the UNIX and DOS command more causes output to be sent to the terminal in screenfuls. To obtain the results of a C++ program at the terminal in screenfuls, use the following command:

maxline | more

Page 13: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 13

VMS REDIRECTION

• In VMS temporary input redirection is achieved by using a VMS command to temporarily change the default location that VMS uses for program input. Thus to run the compiled C++ program named maxline.exe that takes input from the file named mydata.dat, the following two commands need to be executed in sequence (with no other commands in between):

$ define /user_mode sys$input mydata.dat $ run maxline

• Likewise, temporary output redirection in achieved in VMS by a similar define statement. To run the compiled C++ program named maxline.exe that sends the output to a file named myoutput.dat, the following two commands need to be executed in sequence:

$ define /user_mode sys$output myoutput.dat $ run maxline

• If both input and output redirection are desired, then two define statements are required prior to the run statement. In addition, the define for sys$input must come after the define for sys$output as follows:

$ define /user_mode sys$output myoutput.dat $ define /user_mode sys$input mydata.dat $ run maxline

Page 14: PART 2 Features of C++ - Hi

Part 2, Page 14 C++ Programming

declar.cpp /* DECLAR.CPP: The sqrt and log are math functions (in the C or C++ library) that return the square root and natural logarithm, respectively, of their arguments. Both functions take doubles as their arguments and return doubles. Under Unix, the fact that the math functions in the math library are being used must be conveyed to the linker. If prog.cpp is a C++ program that uses these math functions, then the program is compiled as: % cpp prog.cpp -o prog -lm (-lm tells the linker to use the math library) */ #include <iostream> using namespace std; // The following declaration(s) for sqrt and log are // necessary - remove them or get them wrong and see what // happens. The point of this program is that all // functions MUST be declared before they are used. #include <math> // always gets it "right" // extern double sqrt(), log(); // old C style won't work // extern "C" double sqrt(double), log double); //Borland // extern double sqrt(double), log(double); //VAX // risky trying to "hand craft" library function prototype main() { double c; for ( c = 1.0; c <= 10.0; ++c ) cout << c << " " << sqrt(c) << " " << log(c) << endl; for ( c = 1.0; c <= 10.0; ++c) cout << c << " " << log(c) << " " << sqrt(c) << endl; return 0; }

Page 15: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 15

declar.cpp EXPLANATION

• This program invokes functions not included in any of the programmer's source code files. The functions are mathematical functions included in the C math library.

• To use these functions two things are needed. First, the proper declarations must be given in the source file. Second, the proper object code for the functions used must be obtained.

• It is very risky to try to specify the function declarations explicitly. The proper way to obtain a correct function prototype by using the statement:

#include <math.h> which is merely a file containing declarations of the various functions

in the math library. The enclosing < and > tell the compiler to look for the file math.h in the disk area set aside for the compiler’s header library.

For each library function used, the programmer needs to know the name of the header file that needs to be included to obtain the correct function prototype.

• To obtain the object code:

Unix needs the -lm option given to the C compiler (or the loader) when the program is compiled (loaded).

VMS needs the logical name lnk$library set to sys$library:vaxcrtl (which it also needs for all I/O functions)

Page 16: PART 2 Features of C++ - Hi

Part 2, Page 16 C++ Programming

size.cpp /* SIZE.CPP: Find out how much storage (in bytes) is allocated for variables of each type */ #include <iostream> using namespace std; main () { int a, b, c, d, e, f, g, h; double *i; a = sizeof (short); cout << "short integers occupy " << a << " bytes\n"; b = sizeof (int); cout << " integers occupy " << b << " bytes\n"; c = sizeof (long); cout << " long integers occupy " << c << " bytes\n"; d = sizeof (char); cout << " characters occupy " << d << " bytes\n"; e = sizeof (float); cout << "floating point occupy " << e << " bytes\n"; f = sizeof (double); cout << "double precis. occupy " << f << " bytes\n"; g = sizeof ('X'); cout << "a char const occupies " << g << " bytes\n"; h = sizeof (i); cout << " pointers occupy " << h << " bytes\n"; return 0; }

Page 17: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 17

Lab 1 for Part 2

1. Try compiling and executing declar.c five different times: a. with the preferred #include <math.h> statement b. with the complete declaration: extern double sqrt(double), log(double); statement c. with a pre-ANSI declaration: extern double sqrt(), log(); d. with no declaration statement e. with a totally incorrect declaration of sqrt and log, such as extern long sqrt(char), log(unsigned); Do this with the most sensitive error checking the compiler will allow. Where are problems detected in each case?

2. Change the program declar.c so that it attempts to take the square root and natural logarithm of integers. Do this by replacing the definition of the variable c and the controlling for loops as follows: int c; for (c = 1; c <= 10; ++c) Now repeat your attempt to use various declarations for the functions to see what happens.

3. Re-write the program written in lab 2 for part 1 by writing functions to compute the square and the cube of a double precision number. Place the function for computing the square in the same file as main, and place the function for computing the cube in a different file by itself.

4. HOMEWORK: a. Inventory the machines you have access to, determining which machines have C++ compilers already installed on them. b. Install whatever C++ compilers you have access to on whatever machines they will run on. c. Check out these compilers by running, in sequence, the programs hello.cpp, hello2.cpp, cpy2.cpp, and maxline.cpp. d. Run the program size.cpp on all machines and C++ compiler combinations that you have. Keep these results for future reference. e. Check the documentation to determine the compiler version number and the C++ version that it implements

Page 18: PART 2 Features of C++ - Hi

Part 2, Page 18 C++ Programming

CHARACTER CONSTANTS

'A' to 'Z' Capital letters 'a' to 'z' Lower case letters '0' to '9' Digits

'!', '#', etc. Special printable characters '\a' Alert (bell) character '\b' Backspace '\f' Form feed (page eject, top of form) '\n' Newline (linefeed) '\r' Carriage return '\t' Tab '\v' Vertical tab '\\' Backslash '\?' Question mark '\'' Single quote '\"' Double quote '\0' Null (by convention, a string terminator) '\014' The character whose octal code is 014 (in ASCII,

a form feed)

Page 19: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 19

NUMERIC CONSTANTS

• Integer constants: 123 decimal integers 0173 leading zero indicates octal integers (=123 decimal) 0X7B leading 0X indicates hexadecimal integers (=123 decimal)

• Long integer constants: 123L trailing L indicates long integer 0173L long integer expressed in octal 0X7BL long integer expressed in hexadecimal

• Unsigned integer constants: 123U trailing U indicates unsigned integer 0173U unsigned integer expressed in octal 0X7BU unsigned integer expressed in hexadecimal

• Unsigned long integer constants 123UL trailing UL indicates both unsigned and long 0173UL unsigned, long, in octal 0X7BUL unsigned, long, in hexadecimal

• Double precision constants: 123. decimal point or e or E must appear. .123E3 significant digits before or after decimal point must appear 12300e-2 number may be in standard or scientific notation

• Floating point (single precision) constants: 123.0F trailing F indicates float 1230E-1F type float in scientific notation

• Extended double precision constants: 123.L trailing L with decimal point or e or E

Page 20: PART 2 Features of C++ - Hi

Part 2, Page 20 C++ Programming

strlen.cpp /* STRLEN.CPP: Return length of s: K&R, page 39 */ #include <iostream> using namespace std; int strlen (char s[]); // test strlen main() { cout << strlen("Hi there") << endl; return 0; } int strlen(char s[]) { int i; i = 0; while (s[i] != '\0') ++i; return i; }

Page 21: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 21

STRING AND LOGICAL CONSTANTS

• There is no built-in string data type in C++. (The is a String class available in a class library.) String constants are arrays of characters terminated by a null.

"I am a string" A string "" The null string " " A string with one blank "x" Note that "x" is not the same as 'x'

• Since all strings are terminated by nulls, the above function is able to determine string length by marching through memory, starting at the beginning of the string, until a terminating null ('\0') is found.

• Although there is a built-in logical data type in C++ (bool), this is a recent feature. Older code used some integer type (usually int). Zero is considered false whenever a truth value is expected, and all non-zero values are considered true. Whenever a truth value is converted to an integer, true converts to a 1 and false converts to a 0. Older programs using logical values usually include the definitions:

#define FALSE 0 #define TRUE 1

Page 22: PART 2 Features of C++ - Hi

Part 2, Page 22 C++ Programming

decdef.cpp /* DECDEF.CPP: Demonstrate differences between definitions (DEF) and declarations (dec) */ #include <iostream> /* dec */ using namespace std; /* dec */ int addone (int); /* dec */ main() /* DEF of function main */ { int x; /* DEF */ int y = 1; /* DEF */ x = addone(y); cout << x << endl; return 0; } int addone (int i) /* DEF of function addone */ { ++i; return i; }

Page 23: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 23

DECLARATIONS AND DEFINITIONS

• DEFINITION - specifies type, allocates storage, (optionally) initializes value, may occur only once ever.

All variables and functions must be defined explicitly.

• DECLARATION - allows type/usage/multi-dimensional array parameters to be known where needed by compiler to generate correct code - occurs in every file or function that must know of declaration.

All undeclared functions become int functions. It is not considered acceptable to rely on default data typing.

All functions declared without a parameter list default to being functions taking no parameters. Thus the following two declarations are equivalent: int myfunc(); int myfunc(void);

• The program above contains a function addone to add one to its input parameter, and a function main to test it.

Definitions are marked with /* DEF */

Declarations are marked with /* dec */

Page 24: PART 2 Features of C++ - Hi

Part 2, Page 24 C++ Programming

STORAGE CLASS SUMMARY

Storage Class: Auto Static External Register

May be defined at the top of a block

Yes Yes No Yes

May be defined at the top of a file

No No Yes No

Extends throughout block and subblocks

Yes Yes Yes Yes

Extends outside block if declared

No No Yes No

Name exported to the linker

No No Yes No

Initialized before program execution

No Yes Yes No

Initialized at start of block

execution

Yes No No N/A

Default initialization

garbage zero zero garbage

Retains value between block executions

No Yes Yes No

Page 25: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 25

STORAGE CLASSES FOR VARIABLES

• All C++ variables have a storage class in addition to a data type.

• A variable can be of storage class auto(matic), static, extern(al), or register.

• For variables, storage class determines the scope, lifetime, and initialization of the variable.

• Each variable has a default storage class, which can be overridden by explicitly stating the storage class in front of the data type.

• Variables defined outside of any blocks default to extern storage class

• Variables defined inside of any block default to auto storage class

Page 26: PART 2 Features of C++ - Hi

Part 2, Page 26 C++ Programming

scope1.cpp /* SCOPE1.CPP: Check the scope of variables */ #include <iostream> using namespace std; void help1(void); void help2(void); int i = 10; main() { int i = 20; cout << "local i = " << i << endl; cout << "global i = " << ::i << endl; { int i = 30; // local to block cout << "inner block i = " << i << endl; } cout << "back to local i = " << i << endl; help1(); cout << "local i after help1 = " << i << endl; help2(); cout << "local i after help2 = " << i << endl; return 0; } void help1(void) { int i = 40; cout << "in help1 i = " << i << endl; return; } void help2(void) { cout << "in help2 i = " << i << endl; return; }

Page 27: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 27

SCOPE, LIFETIME, INITIALIZATION

SCOPE:

Scope is that part of a program in which the variable is known.

Auto, static, and register storage class specifiers are permitted only in definitions in blocks, generally at the beginning. Their scope extends from the point of definition throughout the block and all subblocks that do not have another variable defined with the same name.

External specifiers may appear as definitions at the top level in a file (without the extern specifier), or as declarations of external variables defined elsewhere (with the extern specifier) anywhere. Their scope extends throughout the file in which they were defined from the point of definiton, and in all files and blocks that declare it. Since the variable name is exported to the linker, this includes functions in other files.

LIFETIME:

Lifetime is that portion of an execution during which a variable has a value.

Automatic and register variables have a lifetime only for the duration of the block. When execution passes outside the block that contains them, their values are lost.

Static and external variables have a lifetime for the duration of the program execution. Whenever a block is re-entered, the static variables defined within that block contain the same value they had when the block was last exited. External variables, known to many blocks, carry their values from block to block.

INITIALIZATION:

Initialization is the process of assigning a value to the variable at the time of its creation.

If the variable is static or external then the initialization is done only once, before the program starts executing. Automatic variables are initialized each time the function they are in is called. Register variables cannot be initialized.

Page 28: PART 2 Features of C++ - Hi

Part 2, Page 28 C++ Programming

storage1.cpp /* STORAGE1.CPP: Illustrates static and automatic storage class for variables. */ #include <iostream> using namespace std; void storage (void); main() { int j; for(j = 0; j < 5; ++j) // repeat 5 times storage(); return 0; } void storage(void) { static int a; // check default initialization static int b = 10; // check static initialization auto int c = 20; // check auto initialization int d = 30; // check default initialization // auto is the default cout << "static a = " << a++ << ", b = " << b++ << " "; cout << "auto c = " << c++ << ", d = " << d++ << endl; }

Page 29: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 29

INITIALIZATION OF VARIABLES

• Static and external variables are always initialized. By default, they are initialized to zero. If variables are to be initialized to non-zero values, they are initialized in the same C++ statement that defines them.

• Automatic variables for which there is no explicit initializer have undefined (garbage) values. Each time the function or block they are in is called they begin with garbage values. If non-garbage values are desired each time the block is entered, the variable must be initialized in the statement that defines them.

• Examples: int x =0, y, z=-4; char w = '8';

• Static and external variables are initialized once per program just prior to the beginning of execution.

• Automatic variables are initialized once each time the block in which they are defined is entered during execution.

Page 30: PART 2 Features of C++ - Hi

Part 2, Page 30 C++ Programming

array1.cpp /* ARRAY1.CPP: program to demonstrate initialization of arrays */ #include <iostream> using namespace std; main() { static int y[5] = {6, 8, 10, 12, -14}; static char greet[] = "hello"; cout << "y(0) = " << y[0]; cout << " y(4) = " << y[4] << endl; cout << "greet(1) = " << greet[1] << endl; return 0; }

Page 31: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 31

INITIALIZATION OF ARRAYS

• Arrays can also be initialized.

• The syntax is: static type name[] = {iv, iv, iv, ... , iv}; or extern type name[] = {iv, iv, iv, ... , iv}; or type name[] = {iv, iv, iv, ... , iv}; where iv represents an initial value.

• For example, the following two initializations are equivalent: static int y[5] = {6, 8, 10, 12, -14}; or static int y[] = {6, 8, 10, 12, -14};

• However, the following two initialization are not the same: static char n[] = {'H', 'E', 'L', 'L', 'O'}; (dimension is 5, if terminating null is desired it must be explicitly

added) static char n[] = {"HELLO"};/*braces optional*/ (dimension is 6, terminating null is included in all string constants)

• If an array is initialized with fewer elements than the number defined, the remaining array elements are initialized to zero

int y[5] = {2, 3}; // Array contains 2,3,0,0,0

Page 32: PART 2 Features of C++ - Hi

Part 2, Page 32 C++ Programming

static.cpp /* STATIC.CPP: Program to demonstrate static function */ #include <iostream> using namespace std; static double f (double); main() { double z; for (z = 0; z < 10; z++) cout << f(z) << endl; return 0; } static double f (double x) { // evaluate x^3 + 2x^2 - 3x + 3 return x * (x * (x + 2.0) - 3.0) + 3.0; }

Page 33: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 33

FUNCTION STORAGE CLASS

• A function can have either a static or external storage class.

• If a function has storage class external then it can be referenced in files other than the one in which it was defined. If a function has storage class static then it can be referenced only in the file in which it was defined.

• If a function is defined without specifying a storage class, it is external. A function can be declared static by placing the keyword static in the definition of the function.

• In the example above, the function f was written for the purpose of easing the evaluation of a frequently used mathematical function within the file. However, it may be undesirable for this function to be available to any other function besides main. The static storage class ensures this "security." (For example, f could be a password encryption function that we wish to make available only to this one piece of privileged code.)

Page 34: PART 2 Features of C++ - Hi

Part 2, Page 34 C++ Programming

math.cpp /* MATH.CPP: Program to illustrate associative problems with addition */ #include <iostream> using namespace std; main() { double a, b, c, x, y, z; x = 1.2e+30; y = -1.2e+30; z = 2.3; a = x + y; // should be zero b = x + z; // 1.2e+30 to 28 sig. digits c = y + z; // -1.2e+30 to 28 sig. digits cout << (a+z) << ' ' << (b+y) << ' ' << (c+x) <<endl; cout << (x+y+z) << ' ' << (x+z+y) << ' ' << (y+z+x) << endl; // no guarantees cout << ((x+y)+z) << ' ' << (x+(y+z)) << ' ' << ((x+z)+y) << endl; // OK return 0; }

Page 35: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 35

ARITHMETIC OPERATIONS

+ Adds two numbers, but A + B means add A to B or add B to A. So A + B + C may add A and B first, or B and C first. Use parentheses to force grouping.

- Subtracts two numbers.

* Multiplies two numbers. As in addition, A * B means multiply A by B or multiply B by A.

/ Divides two numbers. If both are of type int, it performs an integer division, truncating the result.

% Computes the remainder from integer division. This operator doesn't apply to float or double types.

unary - Changes the sign of the operand following it.

Page 36: PART 2 Features of C++ - Hi

Part 2, Page 36 C++ Programming

getline.cpp /* GETLINE.CPP this routine fetches a line - the file needs a define for input */ #include <iostream> using namespace std; // the file needs no external statements int getline(char s[], int lim) // Get input line into array s. Check is // performed to avoid overflowing the array. The // function getline returns the length of the input // line, including a newline character, if present. // The array s is terminated with an ascii null { char c; // input character int i = 0; // intra-line counter while( i<lim-1 && cin.get(c) && c != '\n' ) s[i++] = c; if (c == '\n') // did we fall out with a \n? s[i++] = c; // if so, keep it s[i] = '\0'; // always terminate strings! return(i); }

Page 37: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 37

RELATIONAL AND LOGICAL OPERATORS > Greater than >= Greater than or equal to < Less than <= Less than or equal to == Equal to != Not equal to

&& Logical and (guaranteed to stop left-to-right as soon as first false in a set of conjoined expressions is found)

|| Logical or (guaranteed to stop left-to-right as soon as first true in a set of disjoined expressions is found)

• In the example above, the statement while( i<lim-1 && cin.get(c) && c != '\n' ) s[i++] = c; will check for array space first, and then, only if there is space, read a

character.

Page 38: PART 2 Features of C++ - Hi

Part 2, Page 38 C++ Programming

Type Conversion Examples

• Conversions are done across assignment. Note that: int i; char c; i = c; c = i; is guaranteed not to change valid characters.

• Values are widened, rounded, or truncated as necessary.

int i; double x; i = x; truncates the value stored in x (2.9 becomes 2, -3.6 generally becomes

-3, but is permitted to “truncate” to -4).

float a; double x; a = x; rounds the value of x to the nearest value that can be stored in a.

long w; int i; i = w; drops off the high-order bits in the representation of w.

Page 39: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 39

TYPE CONVERSION

• Conversions need to be done whenever - a set of actual parameters doesn’t exactly match a function prototype - arithmetic is done on two operands of different types - assignment is done from one type to another - initialization is done with a type different than the object initialized

• Expressions that don't make sense are disallowed. e.g. floating point subscripts

• Expressions that might lose information draw warnings.

• Conversions that widen one operand to make both operands of the same type are done automatically.

• Characters are converted to integers using a machine-dependent conversion routine. (Usually, they just allow the bit pattern representing the character to be interpreted as a binary number.) Standard characters are guaranteed to produce positive integers, but arbitrary patterns stored in character variables may not yield positive integers.

• The following rules apply to type conversion in simple cases (no unsigned operands).

If either operand is long double, convert the other to long double.

Otherwise, if either operand is double, convert the other to double.

Otherwise, if either operand is float, convert the other to float.

Otherwise, if either operand is long int, convert the other to long int.

Otherwise, (must have char, short int, enum, and/or int), convert to int.

Page 40: PART 2 Features of C++ - Hi

Part 2, Page 40 C++ Programming

cast.cpp /* CAST.CPP: Program illustrates the use of a cast to coerce a function argument to be of the correct form.*/ #include <iostream> #include <math> using namespace std; /* The above include is present so that the return type of the sqrt math function is properly declared, and the value passed is converted, if necessary, to the correct type. The function sqrt takes one double argument and returns a double. In general, replacing the above #include with: extern double sqrt(double); will not work because sqrt might not be from C++ code */ main() { int n = 2; cout << sqrt(n) << '\n'; // int silently converted // to double because of declation in math.h cout << sqrt( double(n) ) << endl; // better return 0; }

Page 41: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 41

TYPE CASTING

• To create any type conversion necessary prior to performing an operation, making an assignment, or invoking a function, an expression may be cast into another type. This can be done in one of two ways:

Method 1: (type-name) expression

- by placing the desired type name in parentheses in front of the variable or expression. For example: int n; double z; ... z = sqrt( (double)n ); // n is cast as a double

invokes the square root math function with a valid type, a double precision value that is the double precision equivalent of the integer stored in n. This method will become obsolete.

Method 2: type-name (expression)

- Alternate syntax looks more like a function call, is easier to read, and allows C++ extensions to be applied to type casting. For example: float x[10], y, z; y = x[int(z)];

is a legal construction, since the floating point variable z is first cast into an integer type (through truncation) before being used as a subscript.

• Use of casts is much better than relying on defaults. It documents what is being done and shows that the type conversions being done were intended.

• Void is different from any data type, cannot have variables of type void - use re-casting to void of a return parameter you wish to ignore

Page 42: PART 2 Features of C++ - Hi

Part 2, Page 42 C++ Programming

array4.cpp // ARRAY4.CPP: test arrays, casts, const, sizeof #include <iostream> using namespace std; main() { const int maxsize = 100; // instead of #define float arry[maxsize]; for (int i = 0; i < 100; i++) arry[i] = float(3 * i); cout << "array[12] = " << arry[12] << '\n'; cout << "sizeof(arry) = " << sizeof(arry) << '\n'; cout << "sizeof(arry[12]) = " << sizeof(arry[12]) << '\n'; cout << "sizeof(float) = " << sizeof(float) << '\n'; cout << "sizeof(12) = " << sizeof(12) << '\n'; cout << "sizeof(1.2) = " << sizeof(1.2) << '\n'; cout << "sizeof('X') = " << sizeof('\n') << '\n'; return 0; }

Page 43: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 43

CONSTANTS AND VARIABLES • In the program array4.cpp, the variable maxsize takes the place

of the #defined constant in earlier programs. A variable declared const can be used to specify array size and any where else a compile-time constant is required.

• C++ allows variables to be defined in many more places within the code (closer to the point of usage), not just at the heads of blocks. This is particularly useful for "meaningless" loop counters.

• In the program array4.cpp, the variable i is defined inside the initialization portion of the for statement, used within the for loop, and is undefined anywhere else (proposed ANSI standard - currently is defined for the remainder of the block).

• The sizeof operator works for built-in data types and objects, user-defined classes and objects, and aggregates of objects

Page 44: PART 2 Features of C++ - Hi

Part 2, Page 44 C++ Programming

plusplus.cpp // PLUSPLUS.CPP: Test ++ and -- operators #include <iostream> using namespace std; main() { int a = 10, b = 20, c = 30, d = 40, e = 50, f = 60, g = 70, h = 80, i = 100, j = 100, k, l; a++; ++b; c--; --d; cout << "a=" << a << " b=" << b; cout << " c=" << c << " d=" << d << endl; cout << e++ << " " << ++f; cout << " " << g-- << " " << --h << endl; k = i++; l = ++j; cout << "i=" << i << " j=" << j; cout << " k=" << k << " l=" << l << endl; return 0; }

Page 45: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 45

INCREMENT AND DECREMENT OPERATORS

• The increment operator ++ adds one to its operand. The decrement operator -- subtracts one from its operand.

• There are two ways to use the operator, prefix (before the operand) and postfix (after the operand). The prefix operator increments the operand before using it. The postfix operator increments the operand after using it.

• Example: int x, n; n = 5; x = n++; sets x to 5, but int x, n; n = 5; x = ++n; sets x to 6. In both cases, n becomes 6.

• Increment and decrement apply only to variables, not expressions.

Page 46: PART 2 Features of C++ - Hi

Part 2, Page 46 C++ Programming

getbits.cpp /* GETBITS.CPP: Function to extract bits Extract n bits from x starting at bit position p where least significant bit is numbered bit 0 */ unsigned getbits(unsigned x, unsigned p, unsigned n) { return((x >> (p+1-n)) & ~(~0 << n)); }

Page 47: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 47

BIT MANIPULATION

• C++ is capable of doing the following bit manipulation:

& bitwise AND (logical product)

| bitwise inclusive OR (selective set)

^ bitwise exclusive OR (XOR) (selective complement)

<< left shift (zero fill on the right - 2's complement multiplication by powers of 2)

>> right shift: for unsigned, zero fill on the left (both a logical shift and an unsigned divide by powers of 2. For signed, it may do a sign extension or zero fill on the left.

~ one's complement (independent of word length)

• The function getbits(x, p, n) returns a right-adjusted n-bit field of x that begins in position p. (p is the position of the leftmost bit of the extracted field.) The least significant bit, by convention, is bit 0.

Page 48: PART 2 Features of C++ - Hi

Part 2, Page 48 C++ Programming

assign.cpp /* ASSIGN.CPP: Program to illustrate the assignment operator */ #include <iostream> using namespace std; main() { double x = 2.0, y = 3.0, z = 8.0; x += 5.0; y *= 12.0; z /= 2.0; cout << "x = " << x << " y = " << y; cout << " z = " << z << endl; return 0; }

RESULTS OF ASSIGN.CPP x = y = z =

Page 49: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 49

ASSIGNMENT OPERATORS

• Expressions such as i = i + 2; in which the left hand side is repeated on the right can be written in the

compressed form i += 2; using the assignment operator += .

• The following binary operators have a corresponding assignment operator op=, where op is one of the following:

+ - * / % << >> & ^ |

• If e1 and e2 are expressions and op is one of the above, then

e1 op= e2

is equivalent to

e1 = e1 op e2

• For example, x /= 2 is equivalent to x = x/2

Page 50: PART 2 Features of C++ - Hi

Part 2, Page 50 C++ Programming

condit1.cpp // CONDIT1.CPP: Example of the conditional operator. #include <iostream> using namespace std; main() { int x = 10, y; y = x > 2 ? 3 : 5; cout << "x = " << x << ", y = " << y << endl; return 0; }

condit2.cpp /* CONDIT2.CPP: Program introduces the preprocessor directive to define macros */ #include <iostream> using namespace std; #define max(a,b) ( (a) < (b) ) ? b : a main() { int x, y, z; x = 1; y = 5; z = 0; cout << "x = " << x << ", y = " << y; cout << ", z = " << z << endl; z = max(x,y); cout << "x = " << x << ", y = " << y; cout << ", z = " << z << endl; return 0; }

Page 51: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 51

CONDITIONAL EXPRESSION OPERATOR

• The conditional expression operator causes the evaluation of one out of two alternative expressions. The value of the conditional expression operator is the result of the expression evaluated.

• References: Kochan Pg. 88, KR Pg. 51.

• The general format of the conditional expression operator is as follows:

condition ? expression1 : expression2

• If the result of the evaluation of the condition is TRUE ( non-zero ), then expression1 is evaluated and the result of the evaluation becomes the result of the operation. If the condition evaluates FALSE ( zero ), then expression2 is evaluated and its value becomes the result of the operation.

• For example: int x, y, z; ... z = x > 2 ? 3 : 5; After the conditional expression is evaluated, z will have a value of 3

or 5, depending on whether x is greater than 2 or less than or equal to 2.

• NOTE: The conditional expression operator is written with two operators ( ? and : ) and three operands.

Page 52: PART 2 Features of C++ - Hi

Part 2, Page 52 C++ Programming

condit3.cpp /* CONDIT3.CPP: Beware of possible side effects when using macros */ #include <iostream> using namespace std; #define max(a,b) ( (a) < (b) ) ? b : a main() { int x, y, z; x = 1; y = 5; z = 0; cout << "x = " << x << ", y = " << y; cout << ", z = " << z << endl; z = max(++x,++y); cout << "x = " << x << ", y = " << y; cout << ", z = " << z << endl; return 0; }

RESULTS OF CONDIT1.CPP x = y =

RESULTS OF CONDIT2.CPP x = y = z = x = y = z =

RESULTS OF CONDIT3.CPP x = y = z = x = y = z = %

Page 53: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 53

SIDE EFFECTS IN PARAMETERS

• The ++ operator increments a variable as a "side effect." Many function calls also produce results as side effects. (For example, when calling a function with the name of an array, any modification to the contents of the array is a side effect.)

• Side effects should be avoided in the specification of parameters in a parameter list. This is because you never know for sure whether a function call is a real function call or whether it will be expanded as a macro.

• In the example program condit3.cpp, the function max is actually implemented as a macro. The macro needs to reference the larger of the two parameters twice: once to make the comparison, and a second time to use its value as the result of the expression. Any side effect in the parameter list will occur twice for the larger value.

• Moral: Keep Parameter Lists Simple

Page 54: PART 2 Features of C++ - Hi

Part 2, Page 54 C++ Programming

PRECEDENCE CHART OF C++ OPERATORS OPERATOR NAME OVER GROUPING

() function call yes left-to-right [] array element yes . structure, union member no -> structure, union pointer yes :: scope access no ! logical not yes right-to-left ~ one's complement yes + (unary) plus yes - (unary) minus yes ++ increment yes -- decrement yes & address yes * indirection yes

(type) type cast yes sizeof size in bytes yes new dynamic storage allocation yes

delete dynamic storage deallocation yes .* deref pointer to class member no left-to-right ->* deref ptr to ptr to class mem yes * multiplication yes left-to-right / division yes % remainder yes + addition yes left-to-right - subtraction yes << shift left yes left-to-right >> shift right yes < less than yes left-to-right <= less than or equal yes > greater than yes >= greater than or equal yes == equal yes left-to-right != not equal yes & bitwise and yes left-to-right ^ bitwise exclusive or yes left-to-right | bitwise or yes left-to-right && logical and yes left-to-right || logical or yes left-to-right ?: conditional no right-to-left = assignment operator yes right-to-left += assignment replace add yes -= assignment replace subtract yes *= assignment replace multiply yes /= assignment replace divide yes %= assignment replace remainder yes <<= assignment replace shift left yes >>= assignment replace shift right yes &= assignment replace and yes ^= assignment replace exclusive or yes |= assignment replace or yes , comma yes left-to-right

Page 55: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 55

STATEMENTS AND BLOCKS

• An expression such as x = 0 or i++ or cout << endl becomes a statement when it is followed by a semicolon.

x = 0; i++; cout << endl; are now statements.

• Statements can be very long (use a \ at the end of the line to have the compiler ignore the carriage return if you don't want the white space), or statements can be of zero length (the null statement);;.

• Braces are used to group statements together into a block. Blocks are syntactically equivalent to a single statement and may be placed anywhere a statement is required or allowed.

• There are two popular formats for using braces to group statements after the while, for, do, if, else statements. Kernighan and Ritchie use the following format:

if (i == j) { k++; cout << "Yipes\n"; } Many C++ programmers, however, follow the standard adopted in

these notes: if (i == j) { k++; cout << "Yipes\n"; } The second method more readily allows braces to be matched up. It

also provides more white space in the source code in an attempt to further enhance readability.

Page 56: PART 2 Features of C++ - Hi

Part 2, Page 56 C++ Programming

IF, ELSE, AND ELSE-IF STATEMENTS

• The simplest form of decision control is of the form if (expression) statement The expression is evaluated; if it is "true" or non- zero, the statement is

executed.

• Since the if simply tests the numeric value of an expression, if (expression) is equivalent to writing if (expression != 0) Which one is clearer to understand depends on the context. If the

expression already is logical, the first form is preferred. If the expression is numeric, the second form is probably clearer.

• The more general form of the if statement is: if (expression) statement-1 else statement-2 In this form if the expression has a "true" or non-zero value, then

statement-1 is executed. Otherwise, if the expression has a "false" or zero value, then statement-2 is executed.

Page 57: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 57

IF, ELSE, and ELSE IF (continued)

• While not a special case, a series of tests is commonly performed in the following fashion:

if(expression) statement-1 else if(expression) statement-2 else if(expression) statement-3 else statement-4 Only one of the statements is executed. The first true condition causes

execution of the following statement. If none of the expressions is true, the statement after the final else is executed.

• If statements may be nested, but when there are several active if statements, the first else applies to the closest if. The UNIX command cb (C beautifier) will take a source program as input and produce an correctly indented program in K&R style that correctly shows the way a C compiler will interpret the nesting. The VAX/VMS C++ compiler program listings provide a nesting indicator in front of each line that shows how many indentations should appear in the source code.

Page 58: PART 2 Features of C++ - Hi

Part 2, Page 58 C++ Programming

switch1.cpp /* SWITCH1.CPP: Illustrates the switch statement */ #include <iostream> using namespace std; int test (int); main() { cout << test(3) << endl << endl; cout << test(4) << endl << endl; cout << test(2) << endl << endl; cout << test(17) << endl << endl; return 0; } int test(int c) { int x; switch(c) { case 3: cout << "in case 3\n"; x = 10; break; case 4: cout << "in case 4\n"; case 2: cout << "in case 2\n"; x = 20; break; default: cout << "in default case\n"; x = 30; break; } return(x); }

Page 59: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 59

SWITCH STATEMENTS

• The switch statement is a special multi-way decision making structure. In effect, it is a series of if ... else if ... else if ... else statements that test the same variable against a set of constants.

• The general construction is of the form switch (expression) { case constant-1: statement-1; statement-1a; case constant-2: case constant-3: statement-23; break; default: statement-n; }

• The expression must evaluate to an integer at execution.

• The constants, constant-1, constant-2, etc., must be constant expressions known at compile time.

Page 60: PART 2 Features of C++ - Hi

Part 2, Page 60 C++ Programming

switch2.cpp /* SWITCH2.CPP: Count the digits, white space and other characters in terminal input using the switch statement From KR, page 55 */ #include <iostream> using namespace std; main() { char c; int i, nwhite = 0, nother = 0, ndigit[10]; for (i = 0; i < 10; i++) ndigit[i] = 0; while ( cin.get(c) ) switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': ndigit[c-'0']++; break; case ' ' : case '\n': case '\t': nwhite++; break; default: nother++; break; } cout << "digits ="; for (i = 0; i < 10; i++) cout << " " << ndigit[i]; cout << "\nwhite space = " << nwhite << ", other = " << nother << endl; return 0; }

Page 61: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 61

calc.cpp // CALC.CPP: A Simple Calculator #include <iostream> #include <stdlib> using namespace std; main() { float a, b; char opr; float result; const char prompt = ':'; while(cout << prompt, cin >> a >> opr >> b) { switch (opr) { case '+': result = a + b; break; case '-': result = a - b; break; case '*': result = a * b; break; case '/': result = a / b; break; default: cerr << "ERROR ** illegal operator\n"; exit(1); } cout << "result is " << result << endl; } return(0); }

Page 62: PART 2 Features of C++ - Hi

Part 2, Page 62 C++ Programming

Lab 3 for Part 2

1. Write a C++ program that initializes a character array with a long (more than 136 characters) message. Have the program print the message on the screen.

2. (Optional, Mathematical) (K&R Exercise 2-3) Write a function int htoi(char s[]), which converts a string of hexadecimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f, and A through F.

Page 63: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 63

JUMPS

• A principal problem in writing good source code is in maintaining discipline over the flow of control within the program. Undisciplined use of GO TO statements in most languages and the lack of alternative control structures render most languages unsuitable for large software development projects. C++ takes a middle ground, providing adequate control structures, and controlled jumps, but still possessing a GO TO statement.

• The break statement causes termination of the smallest enclosing while, do, for, or switch statement. Control passes outside the control structure to the following statement.

• The continue statement causes control to pass to the loop continuation portion of the smallest enclosing while, do, or for statement. Control remains within the control structure as long as the terminating condition has not been met.

• The return statement causes control to pass back to the calling function.

• The goto statement causes control to pass to a labeled statement. Generally, its use should be relegated to catastrophic error recovery while embedded in many control structures.

• The exit function (declared in stdlib.h) causes control to return to _main (essentially, back to the operating system). exit(0) is considered a successful termination.

Page 64: PART 2 Features of C++ - Hi

Part 2, Page 64 C++ Programming

addup1.cpp // ADDUP1.CPP: demonstrate use of defaults #include <iostream> using namespace std; int addup(int x, int y, int z = 0); //default must appear here or c = addup(a,b) will fail main() { int a, b, c; a = 12; b = 25; c = 6; cout << "a = " << a << " b = " << b << " c = " << c << "\n"; c = addup(a, b, 10); cout << "a = " << a << " b = " << b << " c = " << c << "\n"; c = addup(a, b); cout << "a = " << a << " b = " << b << " c = " << c << "\n"; return 0; } int addup(int x, int y, int z) // default cannot be replicated here, even if the same { return x + y + z; }

Page 65: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 65

DEFAULT PARAMETERS • You do not need to specify an argument for every parameter defined

for the called function if the function is written to handle default values.

• C++ allows the use of default values for parameters when they are omitted from the parameter list in the calling function.

• The function addup allows either two or three integers to be passed to it. If three parameters are passed, all three are added (the z=0 is ignored and z receives the third parameter). If two parameters are passed, the first two are added to the default value for the third (z=0).

• If only one parameter is to be optionally omitted, it must be the last parameter in the parameter list. If two parameters may be omitted, it must be the last two, and the next-to-the-last cannot be omitted unless the last is also omitted.

Page 66: PART 2 Features of C++ - Hi

Part 2, Page 66 C++ Programming

Page 67: PART 2 Features of C++ - Hi

Features of C++ Part 2, Page 67

Lab 4 for Part 2

1. Implement a "function" to calculate the minimum of two numbers as a macro. Use the conditional expression operator. Test the macro using expressions as well as simple constants and variables. Now remove the macro and replace it by an appropriate function. Run the revised implementation through the same tests using the same driving code.

2. Modify the programs written in lab 2 for part 1 and lab 2 for part 2 so that the squaring and cubing of numbers is implemented via a macro.

3. (Tricky) (K&R Exercise 4-14, page 91) Define a macro swap(t, x, y) that interchanges two arguments of type t.

Page 68: PART 2 Features of C++ - Hi

Part 2, Page 68 C++ Programming

Supplemental Exercises for Part 2

1. Write a C++ program of your choice with main in one file, and with a function that main calls in another file. The function in the second file that main calls should in turn call a helping function also located in the second file. Apply an extern declaration on the function main calls, but apply a static declaration on the helping function in the second file. Compile and test the program. After the program is running, attempt to also call the helping function from main, observing the error messages. (If you need a hint, look in the program static2.cpp.)

2. Write a function expand(s,t) which, in the process of copying string s to string t, converts newlines and tabs into visible escape sequences like \n and \t as it copies the string s to the string t. Use a switch. Test the function with an appropriate main driving function. See K&R, page 60, exercise 3-2.

3. Modify the program calc.cpp to accept a fifth operator, P, as the power operator. For example, 3P4 would be 3 to the fourth power, or 81. Use the pow function in the math library.