 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 - C Legacy Code Topics Outline 20.1 Introduction 20.2 Redirecting Input/Output on UNIX and.

Slides:



Advertisements
Similar presentations
 2000 Prentice Hall, Inc. All rights reserved. Chapter 14 - Advanced C Topics Outline 14.1Introduction 14.2Redirecting Input/Output on UNIX and DOS Systems.
Advertisements

Chapter 7: User-Defined Functions II
 2000 Prentice Hall, Inc. All rights reserved. Chapter 14 - Advanced C Topics Outline 14.1Introduction 14.2Redirecting Input/Output on UNIX and DOS Systems.
1 Lecture13: Other C Topics 12/17/2012. Topics Variable-length argument lists Pointers to functions Command-line arguments Suffixes for integer and floating-point.
Chapter 14 - Advanced C Topics Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 14 - Advanced C Topics Outline 14.1Introduction.
Chapter 13 & 14 C Preprocessor and Other C Topics Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 18 - C Legacy Code Topics Outline 18.1Introduction 18.2Redirecting Input/Output on UNIX and.
Kernighan/Ritchie: Kelley/Pohl:
 2003 Prentice Hall, Inc. All rights reserved. 1 Recursion Recursive functions –Functions that call themselves –Can only solve a base case If not base.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
 2003 Prentice Hall, Inc. All rights reserved Introduction Arrays –Structures of related data items –Static entity (same size throughout program)
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions and Recursion Outline Function Templates Recursion Example Using Recursion: The Fibonacci Series.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 14 - Advanced C Topics Outline 14.1Introduction 14.2Redirecting Input/Output on UNIX and DOS Systems.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Examples Using Arrays Passing arrays to functions Class GradeBook: store student grades.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
Loop.  While Loop  Do-while Loop  For Loop Continue Statement Conclusion Loop Loop.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 15 - C++ As A "Better C" Outline 15.1Introduction 15.2C A Simple Program: Adding Two Integers.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 6 - Functions.
 2003 Prentice Hall, Inc. All rights reserved. Outline 1 fig02_07.cpp (1 of 2) 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 12 - Templates Outline 12.1Introduction 12.2Function Templates 12.3Overloading Template Functions.
 2000 Deitel & Associates, Inc. All rights reserved Introduction Pointers –Powerful, but difficult to master –Simulate call-by-reference –Close.
1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing Arrays to Functions 4.6Sorting Arrays 4.7Case.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays.
1 Lecture 14 Functions Functions with Empty Parameter Lists Empty parameter lists  void or leave parameter list empty  Indicates function takes.
 2003 Prentice Hall, Inc. All rights reserved. 1 Vectors.
 2003 Prentice Hall, Inc. All rights reserved. 1 Pointers and Strings Outline Introduction Pointer Variable Declarations and Initialization Pointer Operators.
Exception Handling Outline 23.1 Introduction
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
 2003 Prentice Hall, Inc. All rights reserved. 5.11Function Pointers Pointers to functions –Contain address of function –Similar to how array name is.
 2003 Prentice Hall, Inc. All rights reserved. 11 Fundamentals of Characters and Strings Character constant –Integer value of a character –Single quotes.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
1 Advanced Topics in Functions Lecture Unitary Scope Resolution Operator Unary scope resolution operator ( :: )  Access global variable if.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Functions Outline 3.15Functions with Empty Parameter Lists 3.16Inline Functions 3.17References.
 2003 Prentice Hall, Inc. All rights reserved Storage Classes Variables have attributes –Have seen name, type, size, value –Storage class How long.
 2003 Prentice Hall, Inc. All rights reserved. 1 Lecture 5: Pointer Outline Chapter 5 Pointer continue Call by reference Pointer arithmatic Debugging.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Arrays Outline 4.1Introduction 4.2Arrays 4.3Declaring Arrays 4.4Examples Using Arrays 4.5Passing.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
CHAPTER 4 FUNCTIONS Dr. Shady Yehia Elmashad. Outline 1.Introduction 2.Program Components in C++ 3.Math Library Functions 4.Functions 5.Function Definitions.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
 2000 Prentice Hall, Inc. All rights reserved Arrays Array –Consecutive group of memory locations –Same name and type To refer to an element, specify.
4.1Introduction Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based arrays (C-like) –Arrays.
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Chapter 1.2 Introduction to C++ Programming
Arrays Outline 1 Introduction 2 Arrays 3 Declaring Arrays
Programmazione I a.a. 2017/2018.
Chapter 14 - Advanced C Topics
Arrays Kingdom of Saudi Arabia
Variables have attributes
Chapter 15 - C++ As A "Better C"
Capitolo 4 - Arrays Outline 4.1 Introduction 4.2 Arrays
Arrays Arrays A few types Structures of related data items
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 20 - C Legacy Code Topics Outline 20.1 Introduction 20.2 Redirecting Input/Output on UNIX and DOS Systems 20.3 Variable-Length Argument Lists 20.4 Using Command-Line Arguments 20.5 Notes on Compiling Multiple-Source-File Programs 20.6 Program Termination with exit and atexit 20.7 The volatile Type Qualifier 20.8 Suffixes for Integer and Floating-Point Constants 20.9 Signal Handling Dynamic Memory Allocation with calloc and realloc The Unconditional Branch: goto Unions Linkage Specifications

 2003 Prentice Hall, Inc. All rights reserved Introduction Several advanced topics in chapter Many capabilities specific to OS –Especially UNIX and/or DOS Chapter for C++ programmers working with C legacy code

 2003 Prentice Hall, Inc. All rights reserved Redirecting Input/Output on UNIX and DOS Systems Standard I/O –Keyboard (input) and screen (output) –Can redirect I/O Inputs can come from a file, output can go to a file Redirect symbol ( < ) –Operating system feature (not C++ feature!) UNIX and DOS –$ myProgram < input myProgram is an executable file input is a data file $ is the command-line prompt –Input to program now comes from file input, not the keyboard

 2003 Prentice Hall, Inc. All rights reserved Redirecting Input/Output on UNIX and DOS Systems Pipe command ( | ) –Output of one program becomes input of another –$ firstProgram | secondProgram –Output of firstProgram goes to secondProgram Redirect output ( > ) –Output of program goes to a file –$ myProgram > myFile Output goes to myFile (erases previous contents)

 2003 Prentice Hall, Inc. All rights reserved Redirecting Input/Output on UNIX and DOS Systems Append output ( >> ) –Output of program appends to end of file –$ myProgram >> myFile Output goes to end of myFile

 2003 Prentice Hall, Inc. All rights reserved Variable-Length Argument Lists In C++, we use function overloading –Variable-length arguments for programmers working with C –Create functions with unspecified number of arguments Function format –Include –Use ellipsis ( … ) at end of parameter list Must be last item in parameter list Must be one named parameter before ellipsis –double myFunction(int i, …);

 2003 Prentice Hall, Inc. All rights reserved Variable-Length Argument Lists Usage (inside function) –Declare object of type va_list Holds data needed by other macros va_list myList; –Run macro va_start First argument is va_list object Second is last parameter before ellipsis starts va_start( myList, i );

 2003 Prentice Hall, Inc. All rights reserved Variable-Length Argument Lists Usage –Access arguments with macro va_arg First argument is va_list Second is the expected type of variable Returns the value myArg = va_arg( myList, double ); –Can use different data types for different arguments –Run macro va_end va_end( myList );

 2003 Prentice Hall, Inc. All rights reserved. Outline 9 fig20_02.cpp (1 of 3) 1 // Fig. 20.2: fig20_02.cpp 2 // Using variable-length argument lists. 3 #include 4 5 using std::cout; 6 using std::endl; 7 using std::ios; 8 9 #include using std::setw; 12 using std::setprecision; 13 using std::setiosflags; 14 using std::fixed; #include double average( int,... ); int main() 21 { 22 double double1 = 37.5; 23 double double2 = 22.5; 24 double double3 = 1.7; 25 double double4 = 10.2; 26 Note use of ellipsis in the prototype, and one defined argument before it.

 2003 Prentice Hall, Inc. All rights reserved. Outline 10 fig20_02.cpp (2 of 3) 27 cout << fixed << setprecision( 1 ) << "double1 = " 28 << double1 << "\ndouble2 = " << double2 << "\ndouble3 = " 29 << double3 << "\ndouble4 = " << double4 << endl 30 << setprecision( 3 ) 31 << "\nThe average of double1 and double2 is " 32 << average( 2, double1, double2 ) 33 << "\nThe average of double1, double2, and double3 is " 34 << average( 3, double1, double2, double3 ) 35 << "\nThe average of double1, double2, double3" 36 << " and double4 is " 37 << average( 4, double1, double2, double3, double4 ) 38 << endl; return 0; } // end main 43 Call function with a variable number of arguments (passing the number of arguments as a parameter).

 2003 Prentice Hall, Inc. All rights reserved. Outline 11 fig20_02.cpp (3 of 3) 44 // calculate average 45 double average( int count,... ) 46 { 47 double total = 0; 48 va_list list; // for storing information needed by va_start va_start( list, count ); // process variable length argument list 53 for ( int i = 1; i <= count; i++ ) 54 total += va_arg( list, double ); // end the va_start 57 va_end( list ); return total / count; } // end function average Create a va_list object and call macro va_start. count is the parameter before the ellipsis. Extract each argument from list, treat as a double. End the macros, helps with a normal function return.

 2003 Prentice Hall, Inc. All rights reserved. Outline 12 fig20_02.cpp output (1 of 1) double1 = 37.5 double2 = 22.5 double3 = 1.7 double4 = 10.2 The average of double1 and double2 is The average of double1, double2, and double3 is The average of double1, double2, double3 and double4 is

 2003 Prentice Hall, Inc. All rights reserved Using Command-Line Arguments Can pass arguments to main in UNIX/DOS –Include parameters in main int main( int argc, char *argv[] ) –int argc Number of arguments –char *argv[] Array of strings that contains command-line arguments –Example: $ copy input output argc: 3 argv[0]: "copy" argv[1]: "input" argv[2]: "output"

 2003 Prentice Hall, Inc. All rights reserved Using Command-Line Arguments Upcoming example –Program to copy input file to output file –copy input output –Read a character from file input and write to file output Stop when no more characters to read (EOF)

 2003 Prentice Hall, Inc. All rights reserved. Outline 15 fig20_03.cpp (1 of 2) 1 // Fig. 20.3: fig20_03.cpp 2 // Using command-line arguments 3 #include 4 5 using std::cout; 6 using std::endl; 7 using std::ios; 8 9 #include using std::ifstream; 12 using std::ofstream; int main( int argc, char *argv[] ) 15 { 16 // check number of command-line arguments 17 if ( argc != 3 ) 18 cout << "Usage: copyFile infile_name outfile_name" << endl; else { 21 ifstream inFile( argv[ 1 ], ios::in ); // input file could not be opened 24 if ( !inFile ) { 25 cout << argv[ 1 ] << " could not be opened" << endl; 26 return -1; } // end if argv[1] is the input file -- open for reading. Notice parameters in main.

 2003 Prentice Hall, Inc. All rights reserved. Outline 16 fig20_03.cpp (2 of 2) ofstream outFile( argv[ 2 ], ios::out ); // output file could not be opened 33 if ( !outFile ) { 34 cout << argv[ 2 ] << " could not be opened" << endl; 35 inFile.close(); 36 return -2; } // end if char c = inFile.get(); // read first character while ( inFile ) { 43 outFile.put( c ); // output character 44 c = inFile.get(); // read next character } // end while 47 } // end else return 0; } // end main argv[2] is the output file -- open for writing. Read a character from inFile, and write to outFile. Loop stops when EOF reached.

 2003 Prentice Hall, Inc. All rights reserved Notes on Compiling Multiple-Source- File Programs Program with multiple source files –Function definition must be entirely in one file Cannot be split up into multiple files –Global variables accessible to functions in same file Must be defined in every file they are used Use extern to access global variable in another file –Indicates variable defined later in file or in another file –Example int myGlobal; (defined in file1 ) extern int myGlobal; (appears in file2 )

 2003 Prentice Hall, Inc. All rights reserved Notes on Compiling Multiple-Source- File Programs Function prototypes –Can be used in other files, extern not needed –Include prototype in each file function used Compile files together –Prototype indicates function defined later in same file, or in another file –Example: loading header files #include Contains prototypes of functions We do not need to know where definitions are

 2003 Prentice Hall, Inc. All rights reserved Notes on Compiling Multiple-Source- File Programs Keyword static –In context of global variables/functions –Can only be used by functions in same file Internal linkage Globals/functions have external linkage by default –Used with utility functions called only in one file –For functions If defined before used, include static in definition Otherwise, use with prototype Makefiles –make - utility to aid compilation and linking –Saves effort of constantly recompiling for minor changes

 2003 Prentice Hall, Inc. All rights reserved Program Termination with exit and atexit Function exit –Forces program to end –Usually takes EXIT_SUCCESS or EXIT_FAILURE Symbolic constants ( #define ) exit(EXIT_SUCCESS); –Returns value to environment, indicating success or failure Exact value varies with system

 2003 Prentice Hall, Inc. All rights reserved Program Termination with exit and atexit Function atexit –Takes pointer to function (function name) atexit( myFunction ) Functions must take void, return void –Registers function to run when program ends successfully When exit called, or when main terminates atexit does not terminate the program –Can register up to 32 functions Use multiple atexit calls Called in reverse order of registration

 2003 Prentice Hall, Inc. All rights reserved. Outline 22 fig20_04.cpp (1 of 2) 1 // Fig. 20.4: fig20_04.cpp 2 // Using the exit and atexit functions 3 #include 4 5 using std::cout; 6 using std::endl; 7 using std::cin; 8 9 #include void print(); int main() 14 { 15 atexit( print ); // register function print cout << "Enter 1 to terminate program with function exit" 18 << "\nEnter 2 to terminate program normally\n"; int answer; 21 cin >> answer; 22 Register print to be called when the program terminates. print must return void and take no arguments. print will be called if the program ends successfully.

 2003 Prentice Hall, Inc. All rights reserved. Outline 23 fig20_04.cpp (2 of 2) 23 // exit if answer is 1 24 if ( answer == 1 ) { 25 cout << "\nTerminating program with function exit\n"; 26 exit( EXIT_SUCCESS ); } // end if cout << "\nTerminating program by reaching the end of main" 31 << endl; return 0; } // end main // display message before termination 38 void print() 39 { 40 cout << "Executing function print at program termination\n" 41 << "Program terminated" << endl; } // end function print Call function exit, passing a symbolic constant.

 2003 Prentice Hall, Inc. All rights reserved. Outline 24 fig20_04.cpp output (1 of 1) Enter 1 to terminate program with function exit Enter 2 to terminate program normally 2 Terminating program by reaching the end of main Executing function print at program termination Program terminated Enter 1 to terminate program with function exit Enter 2 to terminate program normally 1 Terminating program with function exit Executing function print at program termination Program terminated

 2003 Prentice Hall, Inc. All rights reserved The volatile Type Qualifier volatile qualifier –Indicates variable may be altered outside of program –Variable not under control of program Compiler cannot perform certain optimizations

 2003 Prentice Hall, Inc. All rights reserved Suffixes for Integer and Floating-Point Constants C++ has suffixes for constants –Integer suffixes u or U ( unsigned ) l or L ( long ) ul or UL ( unsigned long ) Without suffix, uses smallest type that can hold number Examples: 174u, 1322L, 7364ul –Floating point suffixes f or F ( float ) l or L ( long double ) Without suffix, double Examples: L, 1.28f –Incorrect suffix is compiler error

 2003 Prentice Hall, Inc. All rights reserved Signal Handling Signal –Unexpected event, can terminate program Interrupts (ctrl-c) Illegal instructions Floating-point exceptions (division by zero) Function signal traps unexpected signals – –Takes signal number (symbolic constants defined) –Takes pointer to function (function name) Signal handler passed signal number –May be required to call signal again inside handler Depends on system Reinitialize handler after it handles signal

 2003 Prentice Hall, Inc. All rights reserved Signal Handling

 2003 Prentice Hall, Inc. All rights reserved Signal Handling Function raise –Takes signal number –Creates signal

 2003 Prentice Hall, Inc. All rights reserved. Outline 30 fig20_06.cpp (1 of 3) 1 // Fig. 20.6: fig20_06.cpp 2 // Using signal handling 3 #include 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 #include using std::setw; #include 14 #include 15 #include void signalHandler( int ); int main() 20 { 21 signal( SIGINT, signalHandler ); 22 srand( time( 0 ) ); 23 Register signalHandler to deal with SIGINT events.

 2003 Prentice Hall, Inc. All rights reserved. Outline 31 fig20_06.cpp (2 of 3) 24 // create and output random numbers 25 for ( int i = 1; i <= 100; i++ ) { 26 int x = 1 + rand() % 50; // raise SIGINT when x is if ( x == 25 ) 30 raise( SIGINT ); cout << setw( 4 ) << i; // output endl when i is a multiple of if ( i % 10 == 0 ) 36 cout << endl; } // end for return 0; } // end main 43 Note call to function raise.

 2003 Prentice Hall, Inc. All rights reserved. Outline 32 fig20_06.cpp (3 of 3) 44 // handles signal 45 void signalHandler( int signalValue ) 46 { 47 cout << "\nInterrupt signal (" << signalValue 48 << ") received.\n" 49 << "Do you wish to continue (1 = yes or 2 = no)? "; int response; cin >> response; // check for invalid responses 56 while ( response != 1 && response != 2 ) { 57 cout << "(1 = yes or 2 = no)? "; 58 cin >> response; } // end while // determine if it is time to exit 63 if ( response != 1 ) 64 exit( EXIT_SUCCESS ); // call signal and pass it SIGINT and address of signalHandler 67 signal( SIGINT, signalHandler ); } // end function signalHandler May be required to reinitialize.

 2003 Prentice Hall, Inc. All rights reserved. Outline 33 fig20_06.cpp output (1 of 1) Interrupt signal (2) received. Do you wish to continue (1 = yes or 2 = no)? Interrupt signal (2) received. Do you wish to continue (1 = yes or 2 = no)? 2

 2003 Prentice Hall, Inc. All rights reserved Dynamic Memory Allocation with calloc and realloc Dynamic memory allocation –Can create dynamic arrays Function calloc –void *calloc(size_t nelmt, size_t size) nelmt - number of elements in array size - size of each element –Returns pointer to dynamic array Elements initialized to 0

 2003 Prentice Hall, Inc. All rights reserved Dynamic Memory Allocation with calloc and realloc Function realloc –Resizes dynamic object Data not modified if size increased If shrunk, beginning the same –void *realloc(void *ptr, size_t newSize) ptr - pointer to object being reallocated newSize - new size of the object If ptr == 0, acts like malloc If newSize == 0 and ptr != 0, memory freed –Returns pointer to reallocated memory ( NULL if no space)

 2003 Prentice Hall, Inc. All rights reserved The Unconditional Branch: goto Unstructured programming –Use when performance crucial Using break to exit loop –goto statement goto label; Program jumps to first statement after label Label is an identifier and colon ( start: ) –Quick escape from deeply nested loop goto start;

 2003 Prentice Hall, Inc. All rights reserved. Outline 37 fig20_07.cpp (1 of 2) 1 // Fig. 20.7: fig20_07.cpp 2 // Using goto. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 #include 9 10 using std::left; 11 using std::setw; int main() 14 { 15 int count = 1; start: // label // goto end when count exceeds if ( count > 10 ) 21 goto end; cout << setw( 2 ) << left << count; 24 ++count; // goto start on line goto start; Notice declaration of label start Note the format of the goto statement.

 2003 Prentice Hall, Inc. All rights reserved. Outline 38 fig20_07.cpp (2 of 2) fig20_07.cpp output (1 of 1) end: // label cout << endl; return 0; } // end main

 2003 Prentice Hall, Inc. All rights reserved Unions Union –Memory that contains a variety of objects Data members share space Only contains one data member at a time –Conserves storage –Only the last data member defined can be accessed –Declaration same as class or struct union Number { int x; float y; } ; Union myObject;

 2003 Prentice Hall, Inc. All rights reserved Unions Union operations –Assignment to union of same type: = –Taking address: & –Accessing union members:. –Accessing members using pointers: ->

 2003 Prentice Hall, Inc. All rights reserved Unions Anonymous unions –No type name –Does not create a type; creates an unnamed object Contains only public data members –Data members accessed like normal variables Use name, no. or -> required –If declared globally, must be static –Example union { int integer1; double double1; char *charPtr; }; // end anonymous union integer1 = 3;

 2003 Prentice Hall, Inc. All rights reserved. Outline 42 fig20_08.cpp (1 of 2) 1 // Fig. 20.8: fig20_08.cpp 2 // An example of a union. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 // define union Number 9 union Number { 10 int integer1; 11 double double1; }; // end union Number int main() 16 { 17 Number value; // union variable value.integer1 = 100; // assign 100 to member integer cout << "Put a value in the integer member\n" 22 << "and print both members.\nint: " 23 << value.integer1 << "\ndouble: " << value.double1 24 << endl; 25 Create a named union with two data members. They share the same memory. This will print the integer 100 as a double. The program output is implementation dependent, but will show how int s and double s are represented differently.

 2003 Prentice Hall, Inc. All rights reserved. Outline 43 fig20_08.cpp (2 of 2) fig20_08.cpp output (1 of 1) 26 value.double1 = 100.0; // assign to member double cout << "Put a value in the floating member\n" 29 << "and print both members.\nint: " 30 << value.integer1 << "\ndouble: " << value.double1 31 << endl; return 0; } // end main Put a value in the integer member and print both members. int: 100 double: e+061 Put a value in the floating member and print both members. int: 0 double: 100

 2003 Prentice Hall, Inc. All rights reserved. Outline 44 fig20_09.cpp (1 of 2) 1 // Fig. 20.9: fig20_09.cpp 2 // Using an anonymous union. 3 #include 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 // declare an anonymous union 11 // members integer1, double1 and charPtr share the same space 12 union { 13 int integer1; 14 double double1; 15 char *charPtr; }; // end anonymous union // declare local variables 20 int integer2 = 1; 21 double double2 = 3.3; 22 char *char2Ptr = "Anonymous"; 23 Create an anonymous union. The data members can be accessed without using a union name.

 2003 Prentice Hall, Inc. All rights reserved. Outline 45 fig20_09.cpp (2 of 2) fig20_09.cpp output (1 of 1) 24 // assign value to each union member 25 // successively and print each 26 cout << integer2 << ' '; 27 integer1 = 2; 28 cout << integer1 << endl; cout << double2 << ' '; 31 double1 = 4.4; 32 cout << double1 << endl; cout << char2Ptr << ' '; 35 charPtr = "union"; 36 cout << charPtr << endl; return 0; } // end main Anonymous union

 2003 Prentice Hall, Inc. All rights reserved Linkage Specifications Can call compiled C functions from C++ program –However, C does not encode function names like C++ –Leads to problems linking Linkage specifications –To link properly, tell compiler that function compiled in C –For single functions extern "C" function prototype –For multiple functions extern "C" { function prototypes }