95
PART 2 Features of C++ · Compiler options and error checking · Constants and variables · Data types and operations · Expressions and assignment · Control structures and looping · Type casting

Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

  • Upload
    vutram

  • View
    217

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

PART 2

Features of C++

· Compiler options and error checking· Constants and variables· Data types and operations· Expressions and assignment· Control structures and looping· Type casting· Default parameters

Page 2: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

Error Checking in Borland C++ 4.0 for Windows

1. Select options from main menu

2. Select project from options menu

3. Double click on messages (if preceded by a +)3.a. This allows viewing the 8 message categories

4. Click on each message category in turn4.a. This allows viewing of 3 to 13 check boxes

5. Click on each unchecked item to check it

6. Click on OK after completion of 8 message categories

OR

1. Select options from main menu

2. Select project from options menu

3. Click on messages

4. Click on ALL diamond to enable all messages (does not change selected messages in each category - messages not checked in each category will be disabled when the SELECTED diamond is clicked)

Part 2, Page 2 C++ Programming

Page 3: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

PROGRAM ERROR CHECKING

· Borland C++ uses compiler switches or options to control the extent of error checking.

· The sequence on the opposing page will make the Borland C++ compiler as error sensitive as possible.

· Not all programming errors, of course, can be found during compile time. Be sure to watch for compiler, linking, and execution errors.

· Thus, you should do separate compilation, linking, and running (Alt-F9, followed by F9, or Alt-F9 followed by Ctrl-F9).

· To enable checking for stack overflow:1. Select options from main menu2. Select project from options menu3. Click on compiler until compiler options expanded4. Click on debugging until debugging options expanded4. Click on TEST STACK OVERFLOW box until box is checked.

· Be sure to watch for messages at the end of execution. If you have "left something behind" that is discovered at the end of execution, this is a very serious error and must be fixed.

· Be particularly wary of any program that gives a “null pointer assignment” error message at the end of execution or warns of possible “memory leakage.”

Features of C++ Part 2, Page 3

Page 4: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

Borland C++ 4.0 for Windows Error Options

The Borland C and C++ compilers have 51 to 56 independent error checking options that can be enabled or disabled. Borland C++ for Windows has 56 options divided into 8 categories.

PortabilityNon-portable pointer conversionNon-portable pointer comparisonConstant out of range in comparisonConstant is longConversion may lose significant digitsMixing pointers to different ‘char’ types

ANSI violationsVoid functions may not return a valueBoth return and return with a value usedSuspicious pointer conversionUndefined structure structureRedefinition of macro is not identicalHexadecimal value contains more than three digitsBit fields must be signed or unsigned intIdentifier is declared as both external and staticDeclare type prior to use in prototypeDivision by zeroInitializing identifier with identifierInitialization is only partially bracketedNon-ANSI keyword used: word

Obsolete C++Base initialization without a class name is now obsoleteStyle of function definition is now obsoleteOverloaded prefix operator used as a postfix operator

Inefficient C++ CodingFunctions containing identifier are not expanded inlineTemporary used to initialize identifierTemporary used for parameter in call to identifier

Part 2, Page 4 C++ Programming

Page 5: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

Borland C++ 4.0 for Windows Error Options (Continued)

Potential C++ errorsConstant member identifier is not initializedAssigning type to enumerationFunction1 hides virtual function function2Non-const function function called for const objectBase class base1 is also a base class of base2Array size for ‘delete’ ignoredUse qualified name to access nested type typeHandler for xxx is hidden by previous handler for yyyConversion to type will fail for members of virtual base baseMaximum precision used for member pointer type typeUse ‘> >‘ for nested templates instead of ‘>>‘Non-volatile function function called for volatile object

Potential ErrorsPossibly incorrect assignmentPossible use of identifier before definitionNo declaration for function functionCall to function with no prototypeFunction should return a valueAmbiguous operators need parenthesesCondition is always true/false

Inefficient CodingIdentifier is assigned a value that is never usedParameter identifier is never usedIdentifier is declared but never usedStructure passed by valueUnreachable codeCode has no effect

GeneralUnknown assembler instructionIll-formed pragmaArray variable variable is nearSuperfluous & with functionIdentifier is obsoleteCannot create precompiled header: header

Features of C++ Part 2, Page 5

Page 6: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.h>

/* all functions invoked should be declared externaland 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 sizeint len, // current line length

max = 0; // maximum length seen so farchar 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 lengthcopy(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;

}

Part 2, Page 6 C++ Programming

Page 7: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Features of C++ Part 2, Page 7

Page 8: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

getline.cpp/* GETLINE.CPP this routine fetches a line - the file needs a define for input */#include <iostream.h>

/* the file needs no external statements */

int getline(char s[], int lim)/* Get input line into array s. Check isperformed to avoid overflowing the array. Thefunction getline returns the length of the inputline, including a newline character, if present.The array s is terminated with an ascii null */

{char c; // input characterint 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);

}

Part 2, Page 8 C++ Programming

Page 9: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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 enoughvoid copy(char to[], char from[]){

int i = 0; // string position counter

while( (to[i] = from[i]) != '\0' ) // move & check++i;

}

Features of C++ Part 2, Page 9

Page 10: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

Compiling Separate Files

VMS

cxx getlinecxx copycxx maxlinelink maxline, getline, copyrun maxline

Turbo C++

tcc -c getlinetcc -c copytcc maxline getline.obj copy.objmaxline

Borland C++

bcc -c getlinebcc -c copybcc maxline getline.obj copy.objmaxline

Part 2, Page 10 C++ Programming

Page 11: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

· 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.

· 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.

· In Borland C++ 4.0 for Windows you should first exit windows to run these commands from the DOS prompt. The resulting .exe file runs from the DOS prompt. If you want the program to run under Windows, add the -W compiler switch.

· In Borland C++ 4.0 for Windows if you wish to the DOS compile from a DOS window you must first create a PIF file for the DOS window that specifies -1 (infinite) for extended memory (XMS) limit (KB Limit).SEPARATE COMPILATION

· In VMS, the three compile lines may be replaced by the single line:cxx maxline, getline, copy

In this case, three separate object files are created.· In addition, source files in VMS may be treated as if they were

contained in a single file by using the single command line:cxx maxline + getline + copy

In the above case, only the object file maxline.obj would be generated. (The first name is used.)

Features of C++ Part 2, Page 11

Page 12: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

maxline2.cpp/* MAXLINE2.CPP: Find & print the longest line from input. Uses global variables, no parameters passed */#include <iostream.h>

const int maxline = 1000; // maximum input line sizeint max = 0; // maximum length seen so farchar line[maxline]; // current input linechar 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 lengthcopy(); // 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;

}

Part 2, Page 12 C++ Programming

Page 13: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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;

Features of C++ Part 2, Page 13

Page 14: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

maxline2.cpp (continued)/* Get input line into array line. The function getlinereturns the length of the input line, including a newlinecharacter, if present. The array line is terminated withan ascii null; specialized version */int getline(void){

char c; // input characterint 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;

}

Part 2, Page 14 C++ Programming

Page 15: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Features of C++ Part 2, Page 15

Page 16: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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

Part 2, Page 16 C++ Programming

Page 17: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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

Features of C++ Part 2, Page 17

Page 18: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.h>

/* 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.h> // 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;}

Part 2, Page 18 C++ Programming

Page 19: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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)

Features of C++ Part 2, Page 19

Page 20: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

size.cpp/* SIZE.CPP: Find out how much storage (in bytes) is allocated for variables of each type */#include <iostream.h>

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;}

Part 2, Page 20 C++ Programming

Page 21: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

Lab 1 for Part 2

1. Try compiling and executing declar.c five different times:a. with the preferred #include <math.h> statementb. with the complete declaration:

extern double sqrt(double), log(double);statementc. with a pre-ANSI declaration:

extern double sqrt(), log();d. with no declaration statemente. 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

Features of C++ Part 2, Page 21

Page 22: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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)

Part 2, Page 22 C++ Programming

Page 23: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

NUMERIC CONSTANTS

· Integer constants:123 decimal integers0173 leading zero indicates octal integers (=123 decimal)0X7B leading 0X indicates hexadecimal integers (=123 decimal)· Long integer constants:123L trailing L indicates long integer0173L long integer expressed in octal0X7BL long integer expressed in hexadecimal· Unsigned integer constants:123U trailing U indicates unsigned integer0173U unsigned integer expressed in octal0X7BU unsigned integer expressed in hexadecimal· Unsigned long integer constants123UL trailing UL indicates both unsigned and long0173UL unsigned, long, in octal0X7BUL 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 appear12300e-2 number may be in standard or scientific notation· Floating point (single precision) constants:123.0F trailing F indicates float1230E-1F type float in scientific notation· Extended double precision constants:123.L trailing L with decimal point or e or E

Features of C++ Part 2, Page 23

Page 24: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

strlen.cpp/* STRLEN.CPP: Return length of s: K&R, page 39 */#include <iostream.h>

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;

}

Part 2, Page 24 C++ Programming

Page 25: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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

Features of C++ Part 2, Page 25

Page 26: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

decdef.cpp/* DECDEF.CPP: Demonstrate differences between definitions (DEF) and declarations (dec) */#include <iostream.h> /* 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;

}

Part 2, Page 26 C++ Programming

Page 27: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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 */

Features of C++ Part 2, Page 27

Page 28: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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

Part 2, Page 28 C++ Programming

Page 29: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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

Features of C++ Part 2, Page 29

Page 30: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

scope1.cpp/* SCOPE1.CPP: Check the scope of variables */#include <iostream.h>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 blockcout << "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;

}

Part 2, Page 30 C++ Programming

Page 31: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Features of C++ Part 2, Page 31

Page 32: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

storage1.cpp/* STORAGE1.CPP: Illustrates static and automatic storage class for variables. */#include <iostream.h>

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;

}

Part 2, Page 32 C++ Programming

Page 33: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Features of C++ Part 2, Page 33

Page 34: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

array1.cpp/* ARRAY1.CPP: program to demonstrate initialization of arrays */#include <iostream.h>

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;

}

Part 2, Page 34 C++ Programming

Page 35: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

INITIALIZATION OF ARRAYS

· Arrays can also be initialized.· The syntax is:

static type name[] = {iv, iv, iv, ... , iv};orextern type name[] = {iv, iv, iv, ... , iv};ortype 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};

orstatic 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 zeroint y[5] = {2, 3}; // Array contains 2,3,0,0,0

Features of C++ Part 2, Page 35

Page 36: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

static.cpp/* STATIC.CPP: Program to demonstrate static function */#include <iostream.h>

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;

}

Part 2, Page 36 C++ Programming

Page 37: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.)

Features of C++ Part 2, Page 37

Page 38: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

math.cpp/* MATH.CPP: Program to illustrate associative problems with addition */#include <iostream.h>

main(){

double a, b, c, x, y, z;

x = 1.2e+30;y = -1.2e+30;z = 2.3;

a = x + y; // should be zerob = x + z; // 1.2e+30 to 28 sig. digitsc = 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 guaranteescout << ((x+y)+z) << ' ' << (x+(y+z)) << ' '

<< ((x+z)+y) << endl; // OKreturn 0;

}

Part 2, Page 38 C++ Programming

Page 39: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Features of C++ Part 2, Page 39

Page 40: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

getline.cpp/* GETLINE.CPP this routine fetches a line - the file needs a define for input */#include <iostream.h>

/* the file needs no external statements */

int getline(char s[], int lim)/* Get input line into array s. Check isperformed to avoid overflowing the array. Thefunction getline returns the length of the inputline, including a newline character, if present.The array s is terminated with an ascii null */

{char c; // input characterint 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);

}

Part 2, Page 40 C++ Programming

Page 41: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Features of C++ Part 2, Page 41

Page 42: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Part 2, Page 42 C++ Programming

Page 43: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Features of C++ Part 2, Page 43

Page 44: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

cast.cpp/* CAST.CPP: Program illustrates the use of a cast to coerce a function argument to be of the correct form.*/#include <iostream.h>#include <math.h>/* The above include is present so that the return type ofthe sqrt math function is properly declared, and the valuepassed is converted, if necessary, to the correct type.The function sqrt takes one double argument and returns adouble. 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; // betterreturn 0;

}

Part 2, Page 44 C++ Programming

Page 45: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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 doubleinvokes 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

Features of C++ Part 2, Page 45

Page 46: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

array4.cpp

// ARRAY4.CPP: test arrays, casts, const, sizeof#include <iostream.h>

main(){

const int maxsize = 100; // instead of #definefloat 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;}

Part 2, Page 46 C++ Programming

Page 47: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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

Features of C++ Part 2, Page 47

Page 48: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

plusplus.cpp// PLUSPLUS.CPP: Test ++ and -- operators#include <iostream.h>

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;}

Part 2, Page 48 C++ Programming

Page 49: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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, butint 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.

Features of C++ Part 2, Page 49

Page 50: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

getbits.cpp/* GETBITS.CPP: Function to extract bits *//* Extract n bits

from xstarting at bit position pwhere least significant bit is numbered bit 0 */

unsigned getbits(unsigned x, unsigned p, unsigned n){

return((x >> (p+1-n)) & ~(~0 << n));}

Part 2, Page 50 C++ Programming

Page 51: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Features of C++ Part 2, Page 51

Page 52: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

assign.cpp/* ASSIGN.CPP: Program to illustrate the assignment operator */#include <iostream.h>

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 =

Part 2, Page 52 C++ Programming

Page 53: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

ASSIGNMENT OPERATORS

· Expressions such asi = 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, thene1 op= e2

is equivalent toe1 = e1 op e2

· For example,x /= 2

is equivalent tox = x/2

Features of C++ Part 2, Page 53

Page 54: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

condit1.cpp// CONDIT1.CPP: Example of the conditional operator.#include <iostream.h>

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.h>

#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;

}

Part 2, Page 54 C++ Programming

Page 55: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Features of C++ Part 2, Page 55

Page 56: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

condit3.cpp/* CONDIT3.CPP: Beware of possible side effects when using macros */#include <iostream.h>

#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.CPPx = y =

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

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

Part 2, Page 56 C++ Programming

Page 57: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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

Features of C++ Part 2, Page 57

Page 58: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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 yessizeof size in bytes yesnew 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

Part 2, Page 58 C++ Programming

Page 59: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Features of C++ Part 2, Page 59

Page 60: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

IF, ELSE, AND ELSE-IF STATEMENTS

· The simplest form of decision control is of the formif (expression)

statementThe 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 writingif (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-1else

statement-2In 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.

Part 2, Page 60 C++ Programming

Page 61: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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

elsestatement-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.

Features of C++ Part 2, Page 61

Page 62: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

switch1.cpp/* SWITCH1.CPP: Illustrates the switch statement */#include <iostream.h>

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);

}

Part 2, Page 62 C++ Programming

Page 63: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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 formswitch (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.

Features of C++ Part 2, Page 63

Page 64: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.h>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;

}

Part 2, Page 64 C++ Programming

Page 65: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

calc.cpp// CALC.CPP: A Simple Calculator#include <iostream.h>#include <stdlib.h>

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);

}

Features of C++ Part 2, Page 65

Page 66: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Part 2, Page 66 C++ Programming

Page 67: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Features of C++ Part 2, Page 67

Page 68: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

addup1.cpp// ADDUP1.CPP: demonstrate use of defaults#include <iostream.h>

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;}

Part 2, Page 68 C++ Programming

Page 69: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Features of C++ Part 2, Page 69

Page 70: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

Part 2, Page 70 C++ Programming

Page 71: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Features of C++ Part 2, Page 71

Page 72: Chapter 2courseweb.stthomas.edu/tpsturm/private/notes/cplusplus/... · Web viewPART 2 Features of C++ Compiler options and error checking Constants and variables Data types and operations

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.

Part 2, Page 72 C++ Programming