home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft_Programmers_Library.7z / MPL / msc / qc4you.txt < prev    next >
Encoding:
Text File  |  2013-11-08  |  745.3 KB  |  20,690 lines

  1.  Microsoft QuickC Compiler - C FOR YOURSELF
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  ────────────────────────────────────────────────────────────────────────────
  11.                Microsoft(R) QuickC(R) Compiler - C FOR YOURSELF
  12.  
  13.                                  VERSION 2.5
  14.  ────────────────────────────────────────────────────────────────────────────
  15.  
  16.  
  17.                             MICROSOFT CORPORATION
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  Information in this document is subject to change without notice and does
  27.  not represent a commitment on the part of Microsoft Corporation. The
  28.  software described in this document is furnished under a license agreement
  29.  or nondisclosure agreement. The software may be used or copied only in
  30.  accordance with the terms of the agreement. It is against the law to copy
  31.  the software on any medium except as specifically allowed in the license or
  32.  nondisclosure agreement. No part of this manual may be reproduced or
  33.  transmitted in any form or by any means, electronic or mechanical, including
  34.  photocopying and recording, for any purpose without the express written
  35.  permission of Microsoft.
  36.  (C) Copyright Microsoft Corporation, 1988, 1990. All rights reserved.
  37.  
  38.  
  39.  Printed and bound in the United States of America.
  40.  
  41.  
  42.  Microsoft, MS, MS-DOS, CodeView, QuickC, and XENIX are
  43.  registered trademarks and Windows is a trademark of Microsoft Corporation.
  44.  
  45.  AT&T is a registered trademark of American Telephone
  46.  and Telegraph Company.
  47.  
  48.  IBM and PS/2 are registered trademarks of International
  49.  Business Machines Corporation.
  50.  
  51.  Hercules is a registered trademark and InColor is a trademark
  52.  of Hercules Computer Technology.
  53.  
  54.  Intel is a registered trademark of Intel Corporation.
  55.  
  56.  Olivetti is a registered trademark of Ing. C. Olivetti.
  57.  
  58.  VAX is a registered trademark of Digital Equipment Corporation.
  59.  
  60.  
  61.  
  62.  Document No. SY10423-0290
  63.   OEM D703-2Z
  64.  
  65.  10 9 8 7 6 5 4 3 2 1
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  Table of Contents
  73.  ────────────────────────────────────────────────────────────────────────────
  74.  
  75.  
  76.  
  77.  Introduction
  78.       About This Book
  79.       Using the Example Programs
  80.       Programming Style Used in This Manual
  81.       Key to Document Conventions
  82.       Other Books on C Programming
  83.  
  84.  
  85.  PART I  Learning C
  86.  ────────────────────────────────────────────────────────────────────────────
  87.  
  88.  
  89.  Chapter 1  Anatomy of a C Program
  90.  
  91.       A Typical C Program
  92.       Comments
  93.       Statements
  94.       Keywords and Names
  95.       Preprocessor Directives
  96.       Functions
  97.       Calling Functions
  98.       Declaring and Initializing Variables
  99.       External and Local Variables
  100.       Function Prototypes
  101.       A Few Words about printf
  102.  
  103.  Chapter 2  Functions
  104.  
  105.       Functions and Structured Programming
  106.       The main Function
  107.       Placement and Visibility of Functions
  108.       Function Definitions and Prototypes
  109.       Calling a Function
  110.       Passing Arguments to a Function
  111.       Arguments Versus Parameters
  112.       Assigning Parameters
  113.       Passing by Value
  114.       Returning Values from Functions
  115.       Using Return Values
  116.       Declaring a Function's Return Type
  117.       Function Prototypes
  118.              Prototyping Functions without Parameters
  119.              Prototyping Functions with Variable Parameters
  120.       Old-Style Function Declarations and Definitions
  121.  
  122.  Chapter 3  Flow Control
  123.  
  124.       Loops: while, do, and for
  125.              The while Statement
  126.              The do Statement
  127.              The for Statement
  128.       Decision-Making Statements: if, else, switch, break, continue,
  129.         and goto
  130.              The if Statement
  131.              The else Clause
  132.              The switch Statement
  133.              The break Statement
  134.              The continue Statement
  135.              The goto Statement
  136.  
  137.  Chapter 4  Data Types
  138.  
  139.       Basic Data Types
  140.              Specifying Basic Types
  141.              Specifying Variables
  142.              Specifying Constants
  143.       Aggregate Data Types
  144.              Arrays
  145.              Structures
  146.              Unions
  147.  
  148.  Chapter 5  Advanced Data Types
  149.  
  150.       Visibility
  151.              Local Variables
  152.              External Variables
  153.              Visibility in Multiple Source Files
  154.              Visibility of Functions
  155.       Lifetime
  156.              Extending the Lives of Local Variables
  157.       Converting Data Types
  158.              Ranking of Data Types
  159.              Promotions and Demotions
  160.              Automatic Type Conversions
  161.              Manual Type Conversions through Casting
  162.       Register Variables
  163.       Renaming Existing Types with typedef
  164.       The Enumeration Type
  165.  
  166.  Chapter 6  Operators
  167.  
  168.       Introducing C's Operators
  169.              Arithmetic Operators
  170.              Relational Operators
  171.              Assignment Operators
  172.       C's Unique Operators
  173.              Increment and Decrement Operators
  174.              Bitwise Operators
  175.              Logical Operators
  176.              Address Operators
  177.              Conditional Operator
  178.              The sizeof Operator
  179.              Comma Operator
  180.              Base Operator
  181.       Operator Precedence
  182.  
  183.  Chapter 7  Preprocessor Directives
  184.  
  185.       The #include Directive
  186.              Specifying Include Files
  187.       The #define and #undef Directives
  188.              Simple Text Replacement
  189.              Function-Like Macros
  190.              The #undef Directive
  191.       Conditional Directives
  192.              The defined Operator
  193.       Pragmas
  194.  
  195.  Chapter 8  Pointers
  196.  
  197.       Using Pointers in C
  198.       Pointers to Simple Variables
  199.              Declaring a Pointer Variable
  200.              How Pointers Are Stored
  201.              Initializing a Pointer Variable
  202.              Using a Pointer Variable
  203.              Summary of Pointer Basics
  204.       Pointers to Arrays
  205.              Arrays and Pointer Arithmetic
  206.              Comparing Pointers
  207.              PARRAY.C Revisited
  208.       Pointers and Strings
  209.       Passing Pointers to Functions
  210.              Passing Address Constants Versus Passing Pointer Variables
  211.       Arrays of Pointers
  212.       A Pause for Reflection
  213.  
  214.  Chapter 9  Advanced Pointers
  215.  
  216.       Pointers to Pointers
  217.              Equivalence of Array and Pointer Notation
  218.              Getting Command-Line Arguments
  219.              Null Pointers
  220.       Pointers to Structures
  221.       Pointers to Functions
  222.              Passing Function Pointers as Arguments
  223.       A Parting Word on Pointers
  224.  
  225.  Chapter 10  Programming Pitfalls
  226.  
  227.       Operator Problems
  228.              Confusing Assignment and Equality Operators
  229.              Confusing Operator Precedence
  230.              Confusing Structure-Member Operators
  231.       Array Problems
  232.              Array Indexing Errors
  233.              Omitting an Array Subscript in Multidimensional Arrays
  234.              Overrunning Array Boundaries
  235.       String Problems
  236.              Confusing Character Constants and Character Strings
  237.              Forgetting the Null Character That Terminates Strings
  238.              Forgetting to Allocate Memory for a String
  239.       Pointer Problems
  240.              Using the Wrong Address Operator to Initialize a Pointer
  241.              Declaring a Pointer with the Wrong Type
  242.              Using Dangling Pointers
  243.       Library-Function Problems
  244.              Failing to Check Return Values from Library Functions
  245.              Duplicating Library-Function Names
  246.              Forgetting to Include Header Files for Library Functions
  247.              Omitting the Address-Of Operator When Calling scanf
  248.       Macro Problems
  249.              Omitting Parentheses from Macro Arguments
  250.              Using Increment and Decrement Operators in Macro Arguments
  251.       Miscellaneous Problems
  252.              Mismatching if and else Statements
  253.              Misplacing Semicolons
  254.              Omitting Double Backslashes in DOS Path Specifications
  255.              Omitting break Statements from a switch Statement
  256.              Mixing Signed and Unsigned Values
  257.  
  258.  
  259.  PART II  Using C
  260.  ────────────────────────────────────────────────────────────────────────────
  261.  
  262.  
  263.  Chapter 11  Input and Output
  264.  
  265.       Input and Output Streams
  266.       Screen and Keyboard I/O
  267.              Manipulating and Printing Strings
  268.              Printing Numeric Values
  269.              Using scanf for Keyboard Input
  270.       Standard Disk I/O
  271.              Creating and Writing to a Text File
  272.              Reading a Text File in Binary Mode
  273.              Binary and Text Files
  274.              Text Format for Numeric Variables
  275.              Using Binary Format
  276.       Low-Level Input and Output
  277.              Low-Level Reading and Writing
  278.  
  279.  Chapter 12  Dynamic Memory Allocation
  280.  
  281.       Why Allocate?
  282.       Memory Allocation Basics
  283.              Preparing to Allocate Memory
  284.              Specifying the Size of the Allocated Block
  285.              A Graphic Illustration
  286.              Assigning the Address that malloc Returns
  287.              Checking the Return from malloc
  288.              Accessing an Allocated Memory Block
  289.              Allocating Memory for Different Data Types
  290.              Deallocating Memory with the free Function
  291.       Specialized Memory-Allocating Functions
  292.              The calloc Function
  293.              The realloc Function
  294.       Keeping Out of Trouble
  295.  
  296.  Chapter 13  Graphics
  297.  
  298.       Graphics Mode
  299.              Checking the Current Video Mode
  300.              Setting the Video Mode
  301.              Writing a Graphics Program
  302.              Using Color Graphics Modes
  303.              Using the Color Video Text Modes
  304.       Text Coordinates
  305.       Graphics Coordinates
  306.              The Physical Screen
  307.              Viewport Coordinates
  308.              Real Coordinates in a Window
  309.  
  310.  Chapter 14  Presentation Graphics
  311.  
  312.       Terminology
  313.       Presentation Graphics Program Structure
  314.       Five Example Chart Programs
  315.       Palettes
  316.              Color Pool
  317.              Style Pool
  318.              Pattern Pool
  319.              Character Pool
  320.       Customizing Presentation Graphics
  321.              Chart Environment
  322.              titletype
  323.              axistype
  324.              windowtype
  325.              legendtype
  326.              chartenv
  327.       An Overview of the Presentation Graphics Functions
  328.  
  329.  Chapter 15  Fonts
  330.  
  331.       QuickC Fonts
  332.       Using QuickC's Font Library
  333.              Register Fonts
  334.              Set Current Font
  335.              Display Text
  336.       An Example Program
  337.       A Few Hints
  338.  
  339.  Chapter 16  In-Line Assembly
  340.  
  341.       Advantages of In-Line Assembly
  342.       The _asm Keyword
  343.       Using Assembly Language in _asm Blocks
  344.              Instruction Set
  345.              Expressions
  346.              Data Directives and Operators
  347.              EVEN and ALIGN Directives
  348.              Macros
  349.              Segment References
  350.              Type and Variable Sizes
  351.       Using C in _asm Blocks
  352.              Using Operators
  353.              Using C Symbols
  354.              Accessing C Data
  355.              Writing Functions
  356.       Using and Preserving Registers
  357.       Jumping to Labels
  358.       Calling C Functions
  359.       Defining _asm Blocks as C Macros
  360.       Optimizing
  361.       References and Books on Assembly Language
  362.  
  363.  Appendix A  C Language Guide
  364.  
  365.       General Syntax
  366.              User-Defined Names
  367.              Keywords
  368.       Functions
  369.       Flow Control
  370.              The break Statement
  371.              The continue Statement
  372.              The do Statement
  373.              The for Statement
  374.              The goto Statement
  375.              The if Statement
  376.              The return Statement
  377.              The switch Statement
  378.              The while Statement
  379.       Data Types
  380.              Basic Data Types
  381.              Aggregate Data Types
  382.       Advanced Data Types
  383.              Visibility
  384.              Lifetime
  385.              Type Conversions
  386.              User-Defined Types
  387.              Enumerated Types
  388.       Operators
  389.       Preprocessor Directives
  390.       Pointers
  391.  
  392.  Appendix B  C Library Guide
  393.  
  394.       Overview of the C Run-Time Library
  395.       Buffer-Manipulation Routines
  396.       Character Classification and Conversion Routines
  397.       Data Conversion Routines
  398.       Error Message Routines
  399.       Graphics 1: Low-Level Graphics Routines
  400.       Graphics 2: Presentation Graphics Routines
  401.       Graphics 3: Font Display Routines
  402.       Input and Output Routines
  403.       Math Routines
  404.       Memory-Allocation Routines
  405.       Process-Control Routines
  406.       Searching and Sorting Routines
  407.       String-Manipulation Routines
  408.       Time Routines
  409.  
  410.  Glossary
  411.  
  412.  
  413.  
  414.  Introduction
  415.  ────────────────────────────────────────────────────────────────────────────
  416.  
  417.  Ever since Microsoft introduced the QuickC(R) Compiler, version 1.0 in 1987,
  418.  QuickC users have asked for more information on the C programming language.
  419.  C for Yourself answers that need, particularly for those who have some
  420.  programming experience but are new to the C language.
  421.  
  422.  
  423.  About This Book
  424.  
  425.  C for Yourself assumes you have programmed before but are not familiar with
  426.  C. Thus, it doesn't explain basic programming ideas such as why program
  427.  loops are useful. It assumes that you already know about loops in general
  428.  and now want to learn how to write them in the C language. The following
  429.  list summarizes the book's contents:
  430.  
  431.  
  432.    ■   Part 1, "Learning C," covers basic C language topics such as functions
  433.        and data types. The chapters in this section are designed to be read
  434.        in order, from beginning to end.
  435.  
  436.    ■   Part 2, "Using C," covers practical programming topics such as
  437.        input/output and graphics. This section is organized topically, so you
  438.        don't have to read the chapters in any particular order.
  439.  
  440.    ■   Appendix A, "C Language Guide," summarizes the QuickC implementation
  441.        of the C language. You can use this appendix as a quick reference once
  442.        you have read Part 1 and have some familiarity with C.
  443.  
  444.    ■   Appendix B, "C Library Guide," summarizes the most commonly used
  445.        functions in the QuickC run-time library. This appendix is designed
  446.        mainly for browsing when you're not using QuickC. When you are in the
  447.        QuickC environment, use the Microsoft(R) QuickC Advisor (online help)
  448.        to get information about C language features and run-time library
  449.        functions.
  450.  
  451.  ────────────────────────────────────────────────────────────────────────────
  452.  NOTE
  453.  
  454.  The pages that follow use the term "OS/2" to refer to the OS/2 systems─
  455.  Microsoft (R) Operating System/2 (MS (R) OS/2) and IBM (R) OS/2. Similarly,
  456.  the term "DOS" refers to both the MS-DOS (R) and IBM (R) Personal Computer
  457.  DOS operating systems. The name of a specific operating system is used when
  458.  it is necessary to note features that are unique to that system.
  459.  ────────────────────────────────────────────────────────────────────────────
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  Using the Example Programs
  466.  
  467.  The example programs in this book are available through online help. This
  468.  feature allows you to load, run, and experiment with example programs as you
  469.  read.
  470.  
  471.   You can use online  help to load and run  example programs.
  472.  
  473.  You must be using the QuickC environment to load an example. To load the
  474.  program, select Contents from the Help menu, then select the title of this
  475.  book. Find the desired program in Help, then copy it into the editor using
  476.  QuickC's Copy and Paste functions.
  477.  
  478.  After you copy a sample program into the QuickC Editor, you can treat it as
  479.  you would any C source program. You can compile or edit the program, save it
  480.  on disk, and so on.
  481.  
  482.  QuickC online help includes all the significant examples in this book (it
  483.  doesn't include code fragments and some very short programs). Every program
  484.  that is in online help begins with a line in this general form:
  485.  
  486.    /* POINTER.C: Demonstrate pointer basics. */
  487.  
  488.  The line contains the program's name and a brief description of what it
  489.  does. The program containing the above line is listed as POINTER.C in online
  490.  help.
  491.  
  492.  All the examples available in online help compile without errors at Warning
  493.  Level 3, in which QuickC does the most stringent error-checking. At this
  494.  Warning Level, some examples will generate the following harmless warnings:
  495.  
  496.  
  497.    C4103: 'main' : function definition used as prototype
  498.    C4035: 'main' : no return value
  499.    C4051: data conversion
  500.  
  501.  You can eliminate these warnings by compiling at a lower Warning Level.
  502.  
  503.  
  504.  Programming Style Used in This Manual
  505.  
  506.  The C language allows considerable flexibility in formatting source code.
  507.  The style used in this book is recommended for program readability, but you
  508.  do not have to use it when writing your programs. Below is a list of style
  509.  guidelines used in this book for example programs:
  510.  
  511.  
  512.    ■   Each example program begins with a comment that names the program and
  513.        states what it does.
  514.  
  515.    ■   Each statement or function is listed on its own line.
  516.  
  517.    ■   Variable and function names are in lowercase. The names of symbolic
  518.        constants, such as TRUE or FALSE, are in uppercase.
  519.  
  520.    ■   If a function doesn't take any arguments, an opening and a closing
  521.        parenthesis follow the function name with no extra space:
  522.  
  523.        getch();
  524.  
  525.  
  526.    ■   If a function takes arguments, a space appears after the opening
  527.        parenthesis and before the closing parenthesis:
  528.  
  529.        printf( "Number = %i", num_penguins );
  530.  
  531.  
  532.    ■   Binary operators such as addition and subtraction are preceded and
  533.        followed by a space:
  534.  
  535.        3 + 5
  536.  
  537.  
  538.    ■   If parentheses are used to control operator precedence, no extra
  539.        spaces are included:
  540.  
  541.        (3 + 5) * 2
  542.  
  543.  
  544.    ■   Opening and closing braces are aligned under the first character of
  545.        the controlling keyword. The block underneath is indented 3 spaces:
  546.  
  547.        if( a == b )
  548.        {
  549.           c = 50;
  550.           printf( "%i\n", a );
  551.        }
  552.  
  553.  
  554.  
  555.  
  556.  Key to Document Conventions
  557.  
  558.  This book uses the following document conventions:
  559.  
  560.  Example                           Description
  561.  ────────────────────────────────────────────────────────────────────────────
  562.  COPY TEST.OBJ C:                  Uppercase letters represent DOS commands
  563.                                    and file names.
  564.  
  565.  printf                            Boldface letters indicate standard
  566.                                    features of the C language: keywords,
  567.                                    operators, and standard library
  568.                                    functions.
  569.  
  570.  expression                        Words in italics indicate placeholders
  571.                                    for information you must supply, such as
  572.                                    a file name. Italics are also
  573.                                    occasionally used for emphasis in the
  574.                                    text.
  575.  
  576.  main()                            This typeface is used for example
  577.  {                                 programs, program fragments, and the
  578.  }                                 names of user-defined functions and
  579.                                    variables. It also indicates user input
  580.                                    and screen output.
  581.  
  582.  CL options «files...»             A horizontal ellipsis following an item
  583.                                    indicates that more items having the
  584.                                    same form may follow.
  585.  
  586.  while( )                          A vertical ellipsis tells you that part
  587.  {                                 of the example program has been
  588.     .                              intentionally omitted.
  589.     .
  590.     .
  591.  }
  592.  
  593.  SHIFT                             Small capital letters denote names of
  594.                                    keys on the keyboard. A plus sign ( + )
  595.                                    indicates a combination of keys. For
  596.                                    example, SHIFT+F5 tells you to hold down
  597.                                    the SHIFT key while pressing the F5 key.
  598.  
  599.  "array pointer"                   The first time a new term is defined, it
  600.                                    is enclosed in quotation marks. Since
  601.                                    some knowledge of programming is assumed,
  602.                                    common terms such as memory or branch
  603.                                    are not defined.
  604.  
  605.  American National Standards       The first time an acronym appears, it is
  606.  Institute (ANSI)                  spelled out.
  607.  
  608.  
  609.  Other Books on C Programming
  610.  
  611.  This book provides an introduction to the C language and some practical
  612.  programming topics. It does not attempt to teach you basic computer
  613.  programming or advanced C programming techniques. The following books cover
  614.  a variety of topics that you may find useful. They are listed only for your
  615.  convenience. With the exception of its own publications, Microsoft does not
  616.  endorse these books or recommend them over others on the same subject.
  617.  
  618.  Feibel, Werner. Advanced QuickC,
  619.      2d ed. Berkeley, California: Osborne McGraw-Hill, 1989.
  620.  
  621.      An intermediate-level C programming guide using QuickC. It includes data
  622.      structures, parsing, simulations, and the DOS interface.
  623.  
  624.  Hancock, Les, and Morris Krieger. The C Primer,
  625.      2d ed. New York: McGraw-Hill, 1986.
  626.  
  627.      A beginner's guide to C programming.
  628.  
  629.  Hansen, Augie. Proficient C.
  630.      Redmond, Washington: Microsoft Press, 1987.
  631.  
  632.      An intermediate-level guide to C programming.
  633.  
  634.  Harbison, Samuel P., and Guy L. Steele. C: A Reference Manual,
  635.      2d ed. Englewood Cliffs, New Jersey: Prentice-Hall, 1987.
  636.  
  637.      A comprehensive guide to the C language and the standard library.
  638.  
  639.  Hergert, Douglas. The ABC's of QuickC.
  640.      Alameda, California: SYBEX, Inc., 1989.
  641.  
  642.      A beginner's guide to QuickC programming.
  643.  
  644.  Kernighan, Brian W., and Dennis M. Ritchie. The C Programming Language,
  645.       2d ed. Englewood Cliffs, New Jersey: Prentice Hall, 1988.
  646.  
  647.      The first edition of this book is the classic definition of the C
  648.      language. The second edition includes new information on the proposed
  649.      ANSI C standard.
  650.  
  651.  Lafore, Robert. Microsoft C Programming for the IBM.
  652.      Indianapolis, Indiana: Howard W. Sams & Company, 1987.
  653.  
  654.      The first half of the book teaches C. The second half concentrates on
  655.      specifics of the PC environment, such as BIOS calls, memory, and video
  656.      displays.
  657.  
  658.  Plum, Thomas. Learning to Program in C.
  659.      Hasbrouck Heights, New Jersey: Hayden Book Company, 1983.
  660.  
  661.      A widely used introductory college text on computer programming in C.
  662.  
  663.  Schustack, Steve. Variations in C.
  664.      Redmond, Washington: Microsoft Press, 1985.
  665.  
  666.      An intermediate-level guide to developing business applications in C.
  667.  
  668.  Waite, Mitchell, Stephen Prate, Bryan Costales, and Harry Henderson (The
  669.  Waite Group). Microsoft QuickC Programming.
  670.      Redmond, Washington: Microsoft Press, 1988.
  671.  
  672.      Beginning- to intermediate-level C programming, with special emphasis on
  673.      the QuickC Compiler.
  674.  
  675.  Ward, Robert. Debugging C.
  676.      Indianapolis, Indiana: Que Corporation, 1986.
  677.  
  678.      An advanced guide to the theory and practice of debugging C programs.
  679.  
  680.  Wilton, Richard. Programmer's Guide to PC and PS/2 Video Systems.
  681.      Redmond, Washington: Microsoft Press, 1987.
  682.  
  683.      An advanced guide to all the PC and PS/2(R) video modes.
  684.  
  685.  
  686.  
  687.  
  688.  
  689.  
  690.  PART I  Learning C
  691.  ────────────────────────────────────────────────────────────────────────────
  692.  
  693.  The C language has steadily increased in popularity since it was created in
  694.  the early 1970s. C is currently the language of choice for many professional
  695.  software developers and is becoming quite popular among nonprofessional
  696.  programmers, as well.
  697.  
  698.  C for Yourself  is divided into two parts. Part 1 is called "Learning C" and
  699.  discusses the C language itself. This part assumes you know the fundamentals
  700.  of computer programming but do not know C. Experienced C programmers may
  701.  only want to skim these chapters. Part 2, "Using C," discusses practical
  702.  programming capabilities, such as graphics, which are provided in the QuickC
  703.  run-time library. It should be read after you have finished Part 1 and have
  704.  some familiarity with the C language.
  705.  
  706.  Part 1 begins with basic topics such as data types and functions, and it
  707.  progresses to more advanced subjects such as pointers. This part of the book
  708.  closes with a discussion of common C programming pitfalls.
  709.  
  710.  
  711.  
  712.  
  713.  
  714.  
  715.  Chapter 1  Anatomy of a C Program
  716.  ────────────────────────────────────────────────────────────────────────────
  717.  
  718.  As a knowledgeable programmer, you'll probably be tempted to immerse
  719.  yourself in C immediately. But before taking that plunge, you should know
  720.  the basic model for all C programs. This chapter sketches the anatomy of a C
  721.  program without getting bogged down in formal definitions or exceptions to
  722.  the rules. (You'll find plenty of rules in the chapters that follow.)
  723.  
  724.  The discussion revolves around a short, reasonably typical C program named
  725.  VOLUME.C. To get comfortable with the look of C programs, as well as the
  726.  basic ideas that shape them, refer to VOLUME.C frequently as you read.
  727.  
  728.  
  729.  A Typical C Program
  730.  
  731.  VOLUME.C is a simple program that calculates the volume of a sphere and
  732.  prints the following result on the screen:
  733.  
  734.    Volume: 113.040001
  735.  
  736.  Like all of the sample programs in this book, you'll find VOLUME.C in
  737.  QuickC's online help. The "Introduction" explains how to load sample
  738.  programs. Figure 1.1 illustrates the VOLUME.C program.
  739.  
  740.  (This figure may be found in the printed book.)
  741.  
  742.  
  743.  Comments
  744.  
  745.  The first line in VOLUME.C is a comment:
  746.  
  747.    /* VOLUME.C: Calculate sphere's volume. */
  748.  
  749.   Comments make a program more readable.
  750.  
  751.  In C, a comment begins with a slash-asterisk (/*) and ends with an
  752.  asterisk-slash (*/ ). Because C is a compact language with very few
  753.  keywords, comments play an important role in making your programs readable.
  754.  
  755.  
  756.  You can't nest comments (put one comment inside another). The following line
  757.  creates a syntax error:
  758.  
  759.    /* Error! /* You can't */ nest comments in C. */
  760.  
  761.  
  762.  Statements
  763.  
  764.  C statements always end with semicolons. Here is a statement from the
  765.  VOLUME.C program:
  766.  
  767.    result = 4 * PI * result;
  768.  
  769.   Statement blocks are enclosed in braces.
  770.  
  771.  You can also enclose a group of statements in braces, making a "statement
  772.  block." Statement blocks contain related statements, such as the statements
  773.  in the body of a function.
  774.  
  775.  The C language ignores white space (tabs, blanks, and line breaks) in your
  776.  source program, so you can arrange your program in almost any style.
  777.  However, a few de facto rules help promote readability. A typical C program
  778.  is written with one statement per line. Braces align vertically, and
  779.  statements inside braces are indented. The "Introduction" describes the
  780.  programming style used in this book.
  781.  
  782.  
  783.  Keywords and Names
  784.  
  785.  C is a case-sensitive language (it distinguishes between uppercase and
  786.  lowercase letters). All of C's keywords are spelled completely in lowercase;
  787.  online help contains a complete list of C keywords.
  788.  
  789.  You can declare names in any combination of either case, but many
  790.  programmers prefer to use lowercase for variable and function names, saving
  791.  uppercase for declaring symbolic constants. (A "symbolic constant" is a
  792.  descriptive name that represents a constant value. In VOLUME.C,  PI  is a
  793.  symbolic constant.)
  794.  
  795.  
  796.  Preprocessor Directives
  797.  
  798.   A preprocessor  directive is a command to the QuickC compiler.
  799.  
  800.  Not every line in a C program is an executable statement. Programs can also
  801.  contain "preprocessor directives"─ commands for the QuickC compiler. A
  802.  directive begins with a number sign (#) and does not end with a semicolon.
  803.  
  804.  The second and third lines of VOLUME.C contain preprocessor directives. The
  805.  #include directive in the second line tells QuickC to insert the file
  806.  STDIO.H when it compiles VOLUME.C:
  807.  
  808.    #include <stdio.h>
  809.  
  810.  STDIO.H is one of the many "header files" supplied with QuickC. Header files
  811.  contain declarations and definitions required by C library functions.
  812.  ("Library functions" are supplied with QuickC rather than written by you.)
  813.  In the VOLUME.C program, the printf library function requires information
  814.  from the STDIO.H header file.
  815.  
  816.  The #define directive in the third line defines a symbolic constant named
  817.  PI:
  818.  
  819.    #define PI 3.14
  820.  
  821.  Wherever  PI  appears later in the source program, QuickC substitutes the
  822.  text  3.14. The text can be any combination of letters, digits, or other
  823.  characters. The effect is much like a search and replace operation in a word
  824.  processor.
  825.  
  826.  
  827.  Functions
  828.  
  829.   A function performs a specific task and can also return a value.
  830.  
  831.  Functions are the building blocks of C. Every C program has at least one
  832.  function, and every executable C statement appears inside some function or
  833.  another. In plain English, a "function" is a group of statements that
  834.  performs a specific task and often returns a value to the statement that
  835.  calls it.
  836.  
  837.  C functions serve the same purposes as QuickPascal procedures and functions
  838.  or BASIC SUB and FUNCTION procedures. They allow you to write wellorganized
  839.  programs that perform different tasks in separate parts.
  840.  
  841.   The C language has no input/output statements.
  842.  
  843.  C also uses functions to perform all input and output (I/O). Unlike other
  844.  high-level languages, C has no I/O statements such as PRINT or READ.
  845.  Instead, all I/O is done by calling C library functions such as printf.
  846.  
  847.   Every C program has a function named main.
  848.  
  849.  The VOLUME.C program contains two functions, named main and sphere (see
  850.  Figure 1.1). The main execution section of every C program is itself a
  851.  function named main, which marks where execution starts and ends. When you
  852.  run VOLUME.C, execution starts at the beginning of the main function and
  853.  stops at the end of main.
  854.  
  855.  
  856.  Calling Functions
  857.  
  858.  Functions can be called (executed) from anywhere in a program, and they can
  859.  receive values as well as return them. A value that you pass (send) to a
  860.  function is called an "argument."
  861.  
  862.  Calling a C function is a simple matter. You state the name of the function
  863.  and supply in parentheses any arguments you want to pass to it. You must
  864.  place a comma between arguments.
  865.  
  866.  The VOLUME.C program contains two function calls, one to the printf library
  867.  function and the other to the  sphere  function, which is defined in the
  868.  program. The following statement calls the printf function:
  869.  
  870.    printf( "Volume: %f\n", volume );
  871.  
  872.  The statement passes two arguments to printf. The first, "Volume: %f\n",
  873.  supplies text and some formatting information. The second,  volume, supplies
  874.  a numeric value. See "A Few Words about printf," below, for more
  875.  information.
  876.  
  877.  In C, a function does not necessarily have to return a value. It can either
  878.  return a value (like a QuickPascal function) or return nothing (like a
  879.  QuickPascal  procedure).
  880.  
  881.  When a function returns a value, the value is often assigned to a variable.
  882.  The following statement from VOLUME.C calls the  sphere  function and
  883.  assigns its return value to the variable  volume:
  884.  
  885.    volume = sphere( radius );
  886.  
  887.  A function uses the return keyword to return a value. In VOLUME.C, the last
  888.  statement in the  sphere  function returns the value of the variable  result
  889.   to the statement that calls  sphere:
  890.  
  891.    return result;
  892.  
  893.  
  894.  Declaring and Initializing Variables
  895.  
  896.  You must "declare" every variable in a C program by stating its name and
  897.  type. If you refer to an undeclared variable, QuickC displays an error
  898.  message when you compile the program.
  899.  
  900.  The following statement from VOLUME.C declares a float (floating-point) type
  901.  variable named  volume:
  902.  
  903.    float volume;
  904.  
  905.  After declaring a variable, you should "initialize" it─give it an initial
  906.  value─before using it. Uninitialized variables might have any value, so they
  907.  are dangerous to use. The VOLUME.C program initializes the variable  volume
  908.  by as- signing it the return value from a function call:
  909.  
  910.    volume = sphere( radius );
  911.  
  912.  You can also initialize a variable when it is declared, a convenient and
  913.  common practice. The following statement from VOLUME.C declares the variable
  914.   radius  as an int (integer) variable and initializes it with the value 3:
  915.  
  916.    int radius = 3;
  917.  
  918.  
  919.  External and Local Variables
  920.  
  921.  The place where you declare a variable controls where it is visible. A
  922.  variable declared outside any function is "external": you can refer to it
  923.  anywhere within the program. (External variables are called "global" in some
  924.  other languages.)
  925.  
  926.  A variable declared inside the braces of a function is "local." You can
  927.  refer to it inside the function but nowhere else. In VOLUME.C, the  result
  928.  variable is declared inside the  sphere  function:
  929.  
  930.    float sphere( int rad )
  931.    {
  932.       float result;
  933.       .
  934.       .
  935.       .
  936.    }
  937.  
  938.   Use external variables only when necessary.
  939.  
  940.  Because it is local to the  sphere  function, the  result  variable cannot
  941.  be used elsewhere in VOLUME.C. Making variables local whenever possible
  942.  minimizes the risk that a variable's value will be changed accidentally in
  943.  some other part of the program.
  944.  
  945.  When a function receives arguments, the arguments become local variables
  946.  within the function. The  sphere  function requires one argument, which it
  947.  names  rad. Within the function,  rad  is a local variable.
  948.  
  949.  
  950.  Function Prototypes
  951.  
  952.   Function prototypes allow QuickC to check every function reference for
  953.  accuracy.
  954.  
  955.  A function can be declared in much the same way as a variable. Function
  956.  declarations, often called "prototypes," allow QuickC to do "type checking."
  957.  Given the information in the prototype, QuickC can check every subsequent
  958.  use of the function to make sure you pass the right number and type of
  959.  arguments and use the correct return type.
  960.  
  961.  A function prototype gives the following information:
  962.  
  963.  
  964.    ■   The function's name
  965.  
  966.    ■   The type of value the function returns
  967.  
  968.    ■   A list of arguments the function requires
  969.  
  970.  
  971.  The VOLUME.C program contains one function prototype, for the  sphere
  972.  function:
  973.  
  974.    float sphere( int rad );
  975.  
  976.  The prototype states that the  sphere  function returns a float
  977.  (floating-point) value and requires one int (integer) argument.
  978.  
  979.  
  980.  A Few Words about printf
  981.  
  982.  The VOLUME.C program, like most examples in this book, uses the printf
  983.  library function to display text. You won't need to know all of the details
  984.  of printf to read the rest of this book, but the examples will be easier to
  985.  follow if you know a few basic concepts.
  986.  
  987.  The printf function works like the QuickBASIC PRINT USING statement or the
  988.  QuickPascal Writeln procedure. It can display string and numeric data in
  989.  various formats, and it normally prints to the screen.
  990.  
  991.  You can print a simple message by passing printf a string (characters in
  992.  double quotes) as an argument:
  993.  
  994.    printf( "Hi, Mom!" );
  995.  
  996.  The statement prints
  997.  
  998.    Hi, Mom!
  999.  
  1000.  The printf function doesn't automatically add a newline character at the end
  1001.  of a line. The statements
  1002.  
  1003.    printf( "Le Nozze di Figaro" );
  1004.    printf( " by W. A. Mozart" );
  1005.  
  1006.  print the following message on one line:
  1007.  
  1008.    Le Nozze di Figaro by W. A. Mozart
  1009.  
  1010.  To start a new line, use the escape sequence \n as follows:
  1011.  
  1012.    printf( "Hi,\nMom!" );
  1013.  
  1014.  The statement prints two words on separate lines:
  1015.  
  1016.    Hi,
  1017.    Mom!
  1018.  
  1019.  The f in printf stands for formatting. To print the values of variables and
  1020.  other items, you supply printf with format codes that tell printf the proper
  1021.  format for each item. The codes are placed in the first argument, which is
  1022.  enclosed in double quotes.
  1023.  
  1024.  The following statement uses the %x code to print the integer 553 in
  1025.  hexadecimal format. It passes two arguments to printf:
  1026.  
  1027.    printf( "%x", 553 );
  1028.  
  1029.  The first argument ("%x") contains the format code and the second argument
  1030.  (553) contains the item to be formatted. The line displays the following:
  1031.  
  1032.    229
  1033.  
  1034.  The printf function accepts several other format codes. For instance, the
  1035.  VOLUME.C program uses %f to print a floating-point number. Some programs in
  1036.  later chapters use %d to print integers or %ld to print long integers.
  1037.  
  1038.  The first argument passed to printf can contain any combination of
  1039.  characters and format codes. The other arguments contain the items that you
  1040.  want printf to format. The statement
  1041.  
  1042.    printf( "%d times %d = %d\n", 2, 128, 2 * 128 );
  1043.  
  1044.  prints the line:
  1045.  
  1046.    2 times 128 = 256
  1047.  
  1048.  The printf function matches the format codes to the items you want to
  1049.  format, in left-to-right order. In the code above, the first %d formats the
  1050.  number 2, the second formats the 128, and the third formats the expression 2
  1051.  * 128 (which evaluates to the number 256).
  1052.  
  1053.  There's much more to say about printf and other I/O functions, but the rest
  1054.  can wait until you reach Chapter 11, "Input and Output," which describes I/O
  1055.  in detail.
  1056.  
  1057.  Now that you've glimpsed the big picture, we can take a closer look at some
  1058.  specifics of C programming, beginning with Chapter 2, "Functions."
  1059.  
  1060.  
  1061.  
  1062.  
  1063.  
  1064.  
  1065.  Chapter 2  Functions
  1066.  ────────────────────────────────────────────────────────────────────────────
  1067.  
  1068.  Chapter 1, "Anatomy of a C Program," introduced functions, the building
  1069.  blocks of C programs. In this chapter, you'll learn how to use functions in
  1070.  C programs.
  1071.  
  1072.  We begin by discussing some function basics, including the role of the main
  1073.  function. We then show you how to call functions, pass data to them, return
  1074.  data from them, and declare them. The chapter concludes with a brief look at
  1075.  old-style function declarations, which you may encounter in some programs.
  1076.  
  1077.  
  1078.  Functions and Structured Programming
  1079.  
  1080.  As we mentioned in Chapter 1, a C function is a collection of statements,
  1081.  enclosed in braces ({ }), which performs a particular task. It can receive
  1082.  arguments (data) and also return a value.
  1083.  
  1084.  Functions allow you to program with a "divide and conquer" strategy. Rather
  1085.  than try to solve a large problem all at once, you break the problem into
  1086.  several parts and attack each one separately. This approach, known as
  1087.  "structured programming," allows you to write clear, reliable programs that
  1088.  perform separate tasks in discrete, logically contained modules. In the C
  1089.  language, these modules are called functions.
  1090.  
  1091.  Functions offer several advantages. They can
  1092.  
  1093.  
  1094.    ■   Make programs easier to write and read. All of the statements related
  1095.        to a task are located in one place.
  1096.  
  1097.    ■   Prevent unexpected side effects by using private (local) variables
  1098.        that are not visible to other parts of the program.
  1099.  
  1100.    ■   Eliminate unnecessary repetition of code for frequently performed
  1101.        tasks.
  1102.  
  1103.    ■   Simplify debugging. Once the function works reliably, you can use it
  1104.        with confidence in many different situations.
  1105.  
  1106.  
  1107.  If you know QuickPascal or QuickBASIC, you will see many similarities in the
  1108.  C language. A C function serves the same basic purpose as a QuickPascal
  1109.  function or procedure or a QuickBASIC FUNCTION or SUB procedure. In later
  1110.  sections, we'll note some differences between C and these languages.
  1111.  
  1112.  
  1113.  The main Function
  1114.  
  1115.   Every C program must  have one and only  one main function.
  1116.  
  1117.  Every C program must have a function named main, which tells where program
  1118.  execution begins and ends. Although main is not a C keyword, it has only one
  1119.  use: naming the main function. A program must have only one main function,
  1120.  and you shouldn't use the name anywhere else.
  1121.  
  1122.  Below is the simplest possible C program:
  1123.  
  1124.    main()
  1125.    {
  1126.    }
  1127.  
  1128.  The braces ({ }) mark the main function's beginning and end, as they do in
  1129.  every function. This program doesn't contain any executable statements; it
  1130.  simply begins and ends.
  1131.  
  1132.  Most functions have executable statements, of course, and these appear
  1133.  within the function's braces. The following program contains a statement
  1134.  which prints  Hello, world!  on the screen:
  1135.  
  1136.    main()
  1137.    {
  1138.       printf( "Hello, world!\n" );
  1139.    }
  1140.  
  1141.  The main function is called by the operating system when it runs your
  1142.  program. While it's possible to call the main function in a program, you
  1143.  should never do so, just as you wouldn't write a QuickBASIC program
  1144.  containing the line
  1145.  
  1146.    10 GOSUB 10
  1147.  
  1148.  A program that calls main will start again and again in an endless loop that
  1149.  eventually triggers a run-time error.
  1150.  
  1151.  Like all functions, main can accept arguments and return a value. Through
  1152.  this mechanism, your program can receive command-line arguments from DOS
  1153.  when it begins execution and return a value to DOS when it ends. Chapter 9,
  1154.  "Advanced Pointers," describes how to receive command-line arguments via
  1155.  main.
  1156.  
  1157.  
  1158.  Placement and Visibility of Functions
  1159.  
  1160.   A function is normally visible everywhere in the program.
  1161.  
  1162.  Every C function is normally "visible" to all other functions in the same
  1163.  program. That is, it can call and be called by any other function. C
  1164.  functions can even call themselves, a process known as "recursion."
  1165.  
  1166.  In the program below, the functions  whiz  and  bang  are visible to main
  1167.  and to each other. The main  function can call both  whiz  and  bang. In
  1168.  addition,  whiz  can call  bang, and vice versa.
  1169.  
  1170.    main()
  1171.    {
  1172.    }
  1173.  
  1174.    whiz()
  1175.    {
  1176.    }
  1177.  
  1178.    bang()
  1179.    {
  1180.    }
  1181.  
  1182.  Functions can appear in any order and at almost any place in your program.
  1183.  Since main starts and ends the program's execution, this function often
  1184.  begins the program. But this is a readability convention, not a language
  1185.  requirement.
  1186.  
  1187.   C functions can't be nested.
  1188.  
  1189.  One place where you can't put a function is inside another function. The C
  1190.  language doesn't allow you to nest functions. Here C differs from
  1191.  QuickPascal, in which one procedure can contain other "hidden" functions or
  1192.  procedures. The following program causes a syntax error because the  bang
  1193.  function appears within the  whiz  function:
  1194.  
  1195.    main()
  1196.    {
  1197.    }
  1198.  
  1199.    whiz()
  1200.    {
  1201.       /* Error! Incorrect function placement */
  1202.       bang()
  1203.       {
  1204.       }
  1205.    }
  1206.  
  1207.  
  1208.  Function Definitions and Prototypes
  1209.  
  1210.  Now that you understand some function basics, we can look at functions in
  1211.  more detail. A function, or more precisely, "function definition," contains
  1212.  several parts. Figure 2.1 shows the parts of the  sphere  function
  1213.  definition from the VOLUME.C example in Chapter 1, "Anatomy of a C Program."
  1214.  
  1215.  
  1216.  (This figure may be found in the printed book.)
  1217.  
  1218.  The function "header" specifies the type of value a function returns and the
  1219.  function's name. The header also contains an argument list, which specifies
  1220.  the arguments the function requires. The rest of the function
  1221.  definition─everything inside the braces─is the function "body."
  1222.  
  1223.  The ANSI C standard, which QuickC follows, recommends that you supply a
  1224.  function "prototype" (declaration) for every function definition in your
  1225.  program. The prototype is identical to the function header except that it
  1226.  ends with a semicolon. Figure 2.2 shows the  sphere  function prototype from
  1227.  VOLUME.C.
  1228.  
  1229.  (This figure may be found in the printed book.)
  1230.  
  1231.  The function prototype normally appears near the beginning of the program
  1232.  and serves a purpose similar to a variable declaration. It provides advance
  1233.  information about the function, which QuickC can use to check the accuracy
  1234.  of subsequent calls to the function. We'll examine prototypes in detail in
  1235.  "Function Prototypes," below.
  1236.  
  1237.  
  1238.  Calling a Function
  1239.  
  1240.  You call (execute) a function by stating its name. In the simplest case─when
  1241.  a function doesn't receive or return any data─the function call consists of
  1242.  the function's name, followed by an empty pair of parentheses and a
  1243.  semicolon. The BEEPER.C program, shown below, demonstrates this kind of
  1244.  function call.
  1245.  
  1246.    /* BEEPER.C: Demonstrate simple function. */
  1247.    #include <stdio.h>
  1248.  
  1249.    void beep( void );
  1250.  
  1251.    main()
  1252.    {
  1253.       printf( "Time to beep\n" );
  1254.       beep();
  1255.       printf( "All done\n" );
  1256.    }
  1257.  
  1258.    void beep( void )
  1259.    {
  1260.       printf( "Beep!\a\n" );
  1261.    }
  1262.  
  1263.  When you run BEEPER.C, the program prints:
  1264.  
  1265.    Time to beep
  1266.    Beep!
  1267.    All done
  1268.  
  1269.  As you may recall from Chapter 1, "Anatomy of a C Program," the \n sequence
  1270.  represents the newline character. The \a sequence is the "alert" character
  1271.  (ASCII 7) which makes an audible beep.
  1272.  
  1273.  In the main function of BEEPER.C, the statement
  1274.  
  1275.    beep();
  1276.  
  1277.  calls the  beep  function. Since  beep  takes no arguments, the parentheses
  1278.  of the function call are empty.
  1279.  
  1280.  The prototype and definition for the  beep  function use the void keyword
  1281.  twice, first to indicate that the function returns no value, and second to
  1282.  indicate that it receives no arguments. We'll return to these points later
  1283.  in this chapter.
  1284.  
  1285.  A function call transfers control to that function. The statements within
  1286.  the function's braces execute in order until the function ends. Then
  1287.  execution resumes where it left off.
  1288.  
  1289.  A function can end in one of two ways. The  beep  function above ends by
  1290.  "falling off" the closing brace of the function definition. A function can
  1291.  also end by executing a return statement, which we discuss later in the
  1292.  section "Returning Values from Functions."
  1293.  
  1294.  Figure 2.3 illustrates the flow of control in BEEPER.C.
  1295.  
  1296.  (This figure may be found in the printed book.)
  1297.  
  1298.  
  1299.  Passing Arguments to a Function
  1300.  
  1301.  If a function requires arguments, you list them in the parentheses of the
  1302.  function call. In the BEEPER1.C program below, we revise the  beep  function
  1303.  from BEEPER.C to take one argument.
  1304.  
  1305.    /* BEEPER1.C: Demonstrate passing arguments. */
  1306.    #include <stdio.h>
  1307.  
  1308.    void beep( int num_beep );
  1309.  
  1310.    main()
  1311.    {
  1312.       printf( "Time to beep\n" );
  1313.       beep( 5 );
  1314.       printf( "All done\n" );
  1315.    }
  1316.  
  1317.    void beep( int num_beep )
  1318.    {
  1319.       while( num_beep > 0  )
  1320.       {
  1321.          printf( "Beep!\a\n" );
  1322.          num_beep = num_beep - 1;
  1323.       }
  1324.    }
  1325.  
  1326.  The function definition states what kind of arguments the function expects.
  1327.  In the beep  function definition, the header,
  1328.  
  1329.    void beep( int num_beep )
  1330.  
  1331.  states that  beep  expects one int (integer) argument named  num_beep
  1332.  (number of beeps).
  1333.  
  1334.  The statement that calls  beep,
  1335.  
  1336.    beep( 5 );
  1337.  
  1338.  gives the value 5 in parentheses, passing that value as an argument. Figure
  1339.  2.4 shows argument passing in BEEPER1.C.
  1340.  
  1341.  (This figure may be found in the printed book.)
  1342.  
  1343.   Function arguments are assigned to local variables inside the function.
  1344.  
  1345.  When  beep  receives the value 5, the function automatically assigns the
  1346.  value to  num_beep, which the function can then treat as a local variable.
  1347.  In this case, the function uses  num_beep  as a loop counter to repeat the
  1348.  statement
  1349.  
  1350.    printf( "Beep!\a\n" );
  1351.  
  1352.  num_beep  times. (The C while loop is very similar to WHILE loops in
  1353.  QuickBASIC or QuickPascal. You don't need to know the details of loops for
  1354.  now; they're explained in Chapter 3, "Flow Control.")
  1355.  
  1356.  If a function expects more than one argument, you separate the arguments
  1357.  with commas. For instance, the statement
  1358.  
  1359.    printf( "%d times %d equals %d\n", 2, 16, 2 * 16 );
  1360.  
  1361.  passes four arguments to the printf function. The first argument is the
  1362.  string
  1363.  
  1364.    "%d times %d equals %d\n"
  1365.  
  1366.  The second and third arguments are constants (2  and  16). The fourth
  1367.  argument is an expression (2 * 16) that evaluates to a constant.
  1368.  
  1369.  
  1370.  Arguments Versus Parameters
  1371.  
  1372.  In the C language, a value passed to a function is called either an
  1373.  "argument" or a "parameter," depending on viewpoint. From the viewpoint of
  1374.  the statement that calls the function, the value is an argument. In the view
  1375.  of the function receiving it, the value is a parameter.
  1376.  
  1377.  Thus, in BEEPER1.C, the following function call passes an argument to the
  1378.  beep  function:
  1379.  
  1380.    beep( 5 );
  1381.  
  1382.  Looking at the same value from the receiving end, the header of the  beep
  1383.  function declares a parameter named  num_beep  as follows:
  1384.  
  1385.    void beep( int num_beep );
  1386.  
  1387.  The argument and parameter refer to the same value─in this case, the value
  1388.  5. The naming distinction is just a matter of viewpoint, similar to the way
  1389.  you call a letter outgoing mail if you're sending it, or incoming mail if
  1390.  you're receiving it.
  1391.  
  1392.  
  1393.  Assigning Parameters
  1394.  
  1395.  When you list a parameter in the function header, it becomes a local
  1396.  variable within the function. This process is easy to follow when it
  1397.  involves only one argument, as in the BEEPER1.C program above. The function
  1398.  call passes one value, which the function assigns to one variable. The
  1399.  variable can be treated like any other variable declared within the
  1400.  function.
  1401.  
  1402.   There is a one-to-one correspondence between arguments and parameters.
  1403.  
  1404.  If a function takes more than one argument, the values are passed in order.
  1405.  The first argument in the function call is assigned to the first variable,
  1406.  the second argument is assigned to the second variable, and so on.
  1407.  
  1408.  The SHOWME.C program below demonstrates this process. Its  showme  function
  1409.  takes three arguments. The main function defines three integer variables and
  1410.  passes their values to  showme, which prints the values that it receives.
  1411.  (You normally wouldn't write a function just to print one line, of course.
  1412.  We'll add more to SHOWME.C in a later revision.)
  1413.  
  1414.    /* SHOWME.C: Demonstrate passing by value. */
  1415.    #include <stdio.h>
  1416.  
  1417.    void showme( int a, int b, int c );
  1418.  
  1419.    main()
  1420.    {
  1421.       int x = 10, y = 20, z = 30;
  1422.       showme( z, y, x );
  1423.    }
  1424.  
  1425.    void showme( int a, int b, int c )
  1426.    {
  1427.       printf( "a=%d b=%d c=%d", a, b, c );
  1428.    }
  1429.  
  1430.  Here's the output from SHOWME.C:
  1431.  
  1432.    a=30 b=20 c=10
  1433.  
  1434.  The function call in SHOWME.C passes the values of  z,  y, and  x  in the
  1435.  order listed:
  1436.  
  1437.    showme( z, y, x );
  1438.  
  1439.   Functions receive parameters in the order they are passed.
  1440.  
  1441.  These values are assigned, in the same order, to the parameters listed in
  1442.  the  showme  function header:
  1443.  
  1444.    void showme( int a, int b, int c )
  1445.  
  1446.  The position of the parameters, not their names, controls which arguments
  1447.  the parameters receive. The first argument ( z ) listed in the function call
  1448.  is assigned to the first parameter ( a ) in the function header, the second
  1449.  argument ( y ) to the second parameter ( b ), and so on. Figure 2.5 shows
  1450.  this process.
  1451.  
  1452.  (This figure may be found in the printed book.)
  1453.  
  1454.  
  1455.  Passing by Value
  1456.  
  1457.   The C language passes copies of function arguments.
  1458.  
  1459.  In C, all function arguments (except arrays) are passed "by value" rather
  1460.  than "by reference." That is, a function receives a local copy of each
  1461.  argument, not the argument itself. These copies are local variables within
  1462.  the function. They are created and initialized automatically when the
  1463.  function begins, and they disappear when it ends. Like all local variables,
  1464.  their values can be changed without  affecting variables elsewhere in the
  1465.  program.
  1466.  
  1467.  We can clarify this point by adding a few statements to the SHOWME.C
  1468.  program. The new program, SHOWMORE.C, will change the values of the local
  1469.  variables in the  showme  function without changing the values of the
  1470.  original variables.
  1471.  
  1472.    /* SHOWMORE.C: Demonstrate passing by value. */
  1473.    #include <stdio.h>
  1474.  
  1475.    void showme( int any, int old, int name );
  1476.  
  1477.    main()
  1478.    {
  1479.       int x = 10, y = 20, z = 30;
  1480.       showme( z, y, x );
  1481.       printf( "  z=%d   y=%d    x=%d\n", z, y, x );
  1482.    }
  1483.  
  1484.    void showme( int any, int old, int name )
  1485.    {
  1486.       printf( "any=%d old=%d name=%d\n", any, old, name );
  1487.       any = 55;
  1488.       old = 66;
  1489.       name = 77;
  1490.       printf( "any=%d old=%d name=%d\n", any, old, name );
  1491.    }
  1492.  
  1493.  Here is the output from SHOWMORE.C:
  1494.  
  1495.    any=30 old=20 name=10
  1496.    any=55 old=66 name=77
  1497.      z=30   y=20    x=10
  1498.  
  1499.  First, note that the  showme  function in SHOWMORE.C uses new names ( any,
  1500.  old, and  name) when assigning the parameters it receives:
  1501.  
  1502.    void showme( int any, int old, int name )
  1503.  
  1504.   Function parameters can have any legal variable names.
  1505.  
  1506.  Because these variables are local to the function, they can have any legal
  1507.  names. (The rules for variable names are described in Chapter 4, "Data
  1508.  Types.") The  showme  function prints the values of its parameters
  1509.  immediately after assigning them:
  1510.  
  1511.    printf( "any=%d old=%d name=%d", any, old, name );
  1512.  
  1513.  Then the function assigns new values to the variables and prints them again:
  1514.  
  1515.  
  1516.    any = 55;
  1517.    old = 66;
  1518.    name = 77;
  1519.    printf( "any=%d old=%d name=%d", any, old, name );
  1520.  
  1521.   Local variables are private to the function containing them.
  1522.  
  1523.  Changing the local variables in the  showme  function doesn't affect the
  1524.  original variables in the main function. Remember, a variable defined inside
  1525.  a function is only visible inside that function. After control returns to
  1526.  main, SHOWMORE.C prints the values of the original variables:
  1527.  
  1528.    printf( "  z=%d   y=%d    x=%d\n", z, y, x );
  1529.  
  1530.  As the program output shows, the original values are unchanged:
  1531.  
  1532.    z=30   y=20    x=10
  1533.  
  1534.  We'll say more about the visibility of variables in Chapter 5, "Advanced
  1535.  Data Types." For now, just remember that when you pass a value to a
  1536.  function, the function makes a local copy of that value. The local copy can
  1537.  be manipulated without changing the original.
  1538.  
  1539.  ────────────────────────────────────────────────────────────────────────────
  1540.  NOTE
  1541.  
  1542.  In QuickPascal, you can pass either the value of an argument or the
  1543.  argument's address. In C, function arguments are only passed by value.
  1544.  However, that value can be an address. Chapter 8, "Pointers," explains how
  1545.  to pass addresses to functions.
  1546.  ────────────────────────────────────────────────────────────────────────────
  1547.  
  1548.  
  1549.  Returning Values from Functions
  1550.  
  1551.   The return keyword  ends a function and  can return one value.
  1552.  
  1553.  Most C functions return a value. This is done with the return statement,
  1554.  which also ends the function. The VOLUME.C program from Chapter 1, "Anatomy
  1555.  of a C Program," (see Figure 2.1) contains such a statement. In that
  1556.  program, the  sphere  function returns the value of the variable  result  as
  1557.  follows:
  1558.  
  1559.    return result;
  1560.  
  1561.  The following statement in the main function of VOLUME.C calls the  sphere
  1562.  function and assigns its return value to the variable  volume:
  1563.  
  1564.    volume = sphere( radius );
  1565.  
  1566.  Figure 2.6 shows the flow of control as the  sphere  function returns a
  1567.  value in VOLUME.C.
  1568.  
  1569.  (This figure may be found in the printed book.)
  1570.  
  1571.  A return statement can only return a single value. If a function needs to
  1572.  return multiple values, the normal method is to use pointers─a major topic
  1573.  that we'll discuss in Chapter 8, "Pointers."
  1574.  
  1575.  ────────────────────────────────────────────────────────────────────────────
  1576.  NOTE
  1577.  
  1578.  In QuickPascal, a function returns a value and a procedure does not. The
  1579.  same distinction applies to QuickBASIC FUNCTION and SUB procedures,
  1580.  respectively. In the C language, a function can do both. It can return a
  1581.  value or return nothing.
  1582.  ────────────────────────────────────────────────────────────────────────────
  1583.  
  1584.  A function can contain more than one return statement, as shown below:
  1585.  
  1586.    if( error == 0 )
  1587.      return 0;
  1588.    else
  1589.      return 1;
  1590.  
  1591.  The code returns a different value in different cases. It returns the value
  1592.  0 when the variable  error  is 0 and the value 1 when  error  is nonzero.
  1593.  (In C, the if and else statements work much like those in other languages.
  1594.  Chapter 3, "Flow Control," explains these statements.)
  1595.  
  1596.   A return statement can  appear anywhere and  need not return a value.
  1597.  
  1598.  You can place the return keyword anywhere within a function, and the
  1599.  statement need not necessarily return a value. In the following fragment,
  1600.  the naked return statement simply ends the function if the value of  count
  1601.  exceeds 500:
  1602.  
  1603.    if( count > 500 )
  1604.       return;
  1605.    else
  1606.       /* execute more statements... */
  1607.  
  1608.  A return statement ends the function immediately, no matter where it
  1609.  appears. In the function shown below, the statements following the return
  1610.  never execute:
  1611.  
  1612.    void do_nothing( void )
  1613.    {
  1614.       return;
  1615.       /* The following statements do not execute */
  1616.       printf( "This function " );
  1617.       printf( "prints nothing.\n" );
  1618.    }
  1619.  
  1620.  If a function doesn't return a value, and you want the function to end by
  1621.  falling off its closing brace, no return statement is needed. This method is
  1622.  used to end the  beep  function in BEEPER.C, discussed earlier in this
  1623.  chapter:
  1624.  
  1625.    void beep( void )
  1626.    {
  1627.       printf( "Beep!\a\n" );
  1628.    }
  1629.  
  1630.  You could add a return to the end of this function, but it's not necessary.
  1631.  The function ends automatically.
  1632.  
  1633.  
  1634.  Using Return Values
  1635.  
  1636.   Function return values are  often assigned to variables.
  1637.  
  1638.  A function's return value can be used in the same way you would use any
  1639.  value of its type. In the VOLUME.C program from Chapter 1, "Anatomy of a C
  1640.  Program," the statement that calls  sphere  assigns the function's return
  1641.  value to the variable  volume:
  1642.  
  1643.    volume = sphere( radius );
  1644.  
  1645.  If there's no need to save the return value, you can use it directly. You
  1646.  may have noticed that the variable  volume  isn't really needed in the
  1647.  VOLUME.C program, which simply prints the variable's value and ends. Most
  1648.  programmers would make the program more compact by replacing the two
  1649.  statements
  1650.  
  1651.    volume = sphere( radius );
  1652.    printf( "Volume: %f\n", volume );
  1653.  
  1654.  with this one:
  1655.  
  1656.    printf( "Volume: %f\n", sphere( radius ) );
  1657.  
  1658.  The second version puts the  sphere  function call right in the printf
  1659.  statement, eliminating the superfluous variable. Instead of assigning the
  1660.  return value to a variable and passing that variable's value to printf, the
  1661.  statement uses the value directly. (The  sphere  function is called first.
  1662.  Then the return value from  sphere  is passed as an argument to the printf
  1663.  function.)
  1664.  
  1665.  While this change streamlines the program, it also makes the code a little
  1666.  harder to follow. If you don't read carefully, you might overlook the fact
  1667.  that the printf function call contains another function call.
  1668.  
  1669.   Unused return values  are discarded.
  1670.  
  1671.  Occasionally, you may have no use for a function's return value. The printf
  1672.  function, for example, returns the number of characters it displayed, but
  1673.  few programs need this information. If you don't use a return value, it's
  1674.  discarded.
  1675.  
  1676.  You should never ignore the error codes that library functions return to
  1677.  show whether the function succeeded. See Chapter 10, "Programming Pitfalls,"
  1678.  for more information about library function return values.
  1679.  
  1680.  
  1681.  Declaring a Function's Return Type
  1682.  
  1683.  Thus far, we have explained how a function can return a value─and how the
  1684.  calling statement can use that value─without paying much attention to what
  1685.  type of value the function returns. (The C language supports various data
  1686.  types, such as int for integer values, and float for floating-point values.
  1687.  Chapter 4 describes data types in detail.)
  1688.  
  1689.  The return type is important because it controls what the function returns.
  1690.  If a function returns an integer when you expect a floating-point value,
  1691.  your program may not work correctly.
  1692.  
  1693.   A function's prototype and definition control what  type of value it
  1694.  returns.
  1695.  
  1696.  The function's return type is specified in its prototype and definition.
  1697.  Below are the prototype and definition of the  sphere  function from the
  1698.  VOLUME.C program in Chapter 1, "Anatomy of a C Program." They specify that
  1699.  the function returns a float value.
  1700.  
  1701.    float sphere( int rad );  /* function prototype */
  1702.  
  1703.    float sphere( int rad )   /* function header */
  1704.  
  1705.  The type name (here, float) in front of the function name shows what type of
  1706.  value the function returns. If the  sphere  function returned an int value,
  1707.  its prototype and header would look like this:
  1708.  
  1709.    int sphere( int rad ); /* function prototype */
  1710.  
  1711.    int sphere( int rad )  /* function header */
  1712.  
  1713.   Use the void type name  to show a function  returns no value.
  1714.  
  1715.  You should declare the return type for every function─even for functions
  1716.  that don't return a value. These functions are declared with the void type
  1717.  name. In the SHOWME.C program, shown above, the prototype of the  showme
  1718.  function follows this pattern:
  1719.  
  1720.    void showme( int a, int b, int c );
  1721.  
  1722.  The void that precedes the function name indicates that  showme  returns
  1723.  nothing.
  1724.  
  1725.  
  1726.  Function Prototypes
  1727.  
  1728.  Function prototyping is the major innovation of the ANSI standard for C. As
  1729.  we mentioned earlier, a function prototype gives the same information as the
  1730.  function's header: the name of the function, the type of value the function
  1731.  returns, and the number and type of parameters the function requires.
  1732.  
  1733.     Function prototypes allow QuickC to check function references for
  1734.  accuracy.
  1735.  
  1736.  Function prototypes normally appear near the start of the program, before
  1737.  the first function definition. Given the information in the prototype,
  1738.  QuickC can perform "type checking." It checks each reference to the
  1739.  function─its definition, as well as every function call─to make sure that
  1740.  the reference uses the right number and type of arguments and the correct
  1741.  return value. Without type checking, it's easy to create bugs by passing the
  1742.  wrong type of value to a function or assuming the wrong return type.
  1743.  
  1744.  C programs normally include one prototype for each function they define,
  1745.  except the main function. Most programmers don't bother to prototype main
  1746.  unless the program receives command-line arguments or returns a value to DOS
  1747.  when it ends. (Command-line arguments are discussed in Chapter 9, "Advanced
  1748.  Pointers.")
  1749.  
  1750.  Here is the function prototype for the  sphere  function in VOLUME.C:
  1751.  
  1752.    float sphere( int rad );
  1753.  
  1754.  You can see that  sphere  expects a single int-type parameter and returns a
  1755.  value of type float. On the other hand, the prototype for  showme  in
  1756.  SHOWME.C indicates that  showme  expects three int-type parameters and
  1757.  returns nothing:
  1758.  
  1759.    void showme( int a, int b, int c );
  1760.  
  1761.  It's common to use the same parameter names in both the function prototype
  1762.  and the function header. In SHOWME.C, for instance, the  showme  function
  1763.  prototype,
  1764.  
  1765.    void showme( int a, int b, int c );
  1766.  
  1767.  uses the names  a,  b, and  c, as does the header for that function,
  1768.  
  1769.    void showme( int a, int b, int c )
  1770.  
  1771.  Using the same names in both parameter lists makes the program more
  1772.  readable, but it's not a language requirement. The names in the prototype's
  1773.  parameter list are merely cosmetic. You can use any names you choose, or
  1774.  even omit the names completely. The prototype in SHOWME.C works just as well
  1775.  when written
  1776.  
  1777.    void showme( int, int, int );
  1778.  
  1779.  as when you supply the names  a,  b, and  c. Both versions fully specify the
  1780.  number (three) and type (int) of the parameters the function expects.
  1781.  
  1782.  
  1783.  Prototyping Functions without Parameters
  1784.  
  1785.  If a function doesn't expect any parameters, you might be tempted to leave
  1786.  its parameter list blank. But it's better to put void in its parameter list,
  1787.  as shown here:
  1788.  
  1789.    void beep( void );
  1790.  
  1791.  The void in parentheses specifies that the  beep  function requires no
  1792.  parameters. If you leave the parentheses empty, the compiler draws no
  1793.  conclusion about what parameters the function takes and won't be able to
  1794.  detect an error if you mistakenly pass an argument to the function.
  1795.  
  1796.  
  1797.  Prototyping Functions with Variable Parameters
  1798.  
  1799.  Some functions, such as the printf library function, can handle a variable
  1800.  number of parameters. This capability can make functions more flexible. As
  1801.  earlier examples have shown, the printf function can take one parameter or
  1802.  several, depending on how many values you need to print.
  1803.  
  1804.  To declare a function with a variable number of parameters, end the
  1805.  parameter list with a comma and an ellipsis (, . . .). The following
  1806.  prototype, for example, declares that the  sample  function expects at least
  1807.  one int-type parameter and zero or more additional parameters:
  1808.  
  1809.    void sample( int a,... );
  1810.  
  1811.  The ellipsis stands for an unspecified number of parameters with types that
  1812.  are also unspecified. The parameter list in the function header should
  1813.  follow the same pattern.
  1814.  
  1815.  Don't declare a variable number of parameters unless it's necessary. Giving
  1816.  this sort of prototype for a function that takes a fixed number of
  1817.  parameters defeats the prototype's main purpose. QuickC can't perform type
  1818.  checking for parameters you leave out of a prototype.
  1819.  
  1820.  
  1821.  Old-Style Function Declarations and Definitions
  1822.  
  1823.  This book explains how to declare and define functions under the ANSI
  1824.  standard for C, which is now the norm. The original C language used slightly
  1825.  different rules for function declarations and definitions. QuickC can
  1826.  compile these "oldstyle" programs, but the ANSI standard recommends you use
  1827.  the full function prototypes we just described.
  1828.  
  1829.  Still, you may encounter old-style function declarations and definitions in
  1830.  many existing C programs. So, you should be familiar with the style.
  1831.  
  1832.  We'll use the VOLUME.C program from Chapter 1, "Anatomy of a C Program," to
  1833.  demonstrate the old style. First, here's the ANSI-style program presented in
  1834.  Chapter 1:
  1835.  
  1836.    /* VOLUME.C: Calculate sphere's volume. */
  1837.    #include <stdio.h>
  1838.    #define PI 3.14
  1839.  
  1840.    float sphere( int rad );
  1841.  
  1842.    main()
  1843.    {
  1844.       float volume;
  1845.       int radius = 3;
  1846.       volume = sphere( radius );
  1847.       printf( "Volume: %f\n", volume );
  1848.    }
  1849.  
  1850.    float sphere( int rad )
  1851.    {
  1852.       float result;
  1853.       result = rad * rad * rad;
  1854.       result = 4 * PI * result;
  1855.       result = result / 3;
  1856.       return result;
  1857.    }
  1858.  
  1859.  The same program written in the old style would look something like this:
  1860.  
  1861.    /* OLDSTYLE.C: Old-style function. */
  1862.  
  1863.    #include <stdio.h>
  1864.    #define PI 3.14
  1865.  
  1866.    float sphere();
  1867.  
  1868.    main()
  1869.    {
  1870.       float volume;
  1871.       int radius = 3;
  1872.       volume = sphere( radius );
  1873.       printf( "Volume: %f\n", volume );
  1874.    }
  1875.  
  1876.    float sphere( rad )
  1877.    int rad;
  1878.    {
  1879.       float result;
  1880.       result = rad * rad * rad;
  1881.       result = 4 * PI * result;
  1882.       result = result / 3;
  1883.       return result;
  1884.    }
  1885.  
  1886.  You'll notice two distinct differences. First, the old style doesn't allow a
  1887.  parameter list in the function declaration. In the ANSI version, VOLUME.C,
  1888.  the declaration of the  sphere  function specifies that the function takes a
  1889.  single int parameter:
  1890.  
  1891.    float sphere( int rad );
  1892.  
  1893.  The corresponding declaration in OLDSTYLE.C omits the parameter list:
  1894.  
  1895.    float sphere();
  1896.  
  1897.  An old-style function declaration cannot provide any information about the
  1898.  function's parameters.
  1899.  
  1900.  The other change is in the way the function definition lists parameters. In
  1901.  VOLUME.C, the function header lists the same information as the function
  1902.  prototype, giving the type (int) and name ( rad ) of the function's
  1903.  parameter:
  1904.  
  1905.    float sphere( int rad )
  1906.    {
  1907.       .
  1908.       .
  1909.       .
  1910.    }
  1911.  
  1912.  In OLDSTYLE.C, the function header gives the parameter's name ( rad ), but
  1913.  not its type. The parameter's type is declared in a statement directly below
  1914.  the function header (and before the left brace that begins the function
  1915.  body):
  1916.  
  1917.    float sphere( rad )
  1918.    int rad;
  1919.    {
  1920.       .
  1921.       .
  1922.       .
  1923.    }
  1924.  
  1925.  The rest of OLDSTYLE.C is identical to VOLUME.C.
  1926.  
  1927.  Now that you understand the basics of functions, we can turn our attention
  1928.  to the C statements that a function can contain, beginning with flow-control
  1929.  statements, the subject of the next chapter.
  1930.  
  1931.  
  1932.  
  1933.  
  1934.  
  1935.  
  1936.  Chapter 3  Flow Control
  1937.  ────────────────────────────────────────────────────────────────────────────
  1938.  
  1939.  Flow control─diverting execution by looping and branching─is one area where
  1940.  C closely resembles other languages. If you know how to loop and branch in
  1941.  QuickBASIC or QuickPascal, learning the C equivalents is mainly a matter of
  1942.  adjusting to somewhat different syntax. Here, as elsewhere, C never uses two
  1943.  keywords when one will do. For instance, C has no "then" keyword. Instead,
  1944.  it uses simple punctuation.
  1945.  
  1946.  This chapter has two parts. The first part examines the looping statements:
  1947.  while, do, and for. The second part describes the decision-making
  1948.  statements: if, else, switch, break, continue, and goto.
  1949.  
  1950.  
  1951.  Loops: while, do, and for
  1952.  
  1953.  This section discusses the C statements that create loops: while, do, and
  1954.  for. These loops repeat while a condition is true or for a set number of
  1955.  times. We'll begin with the simplest loop, the while statement.
  1956.  
  1957.  
  1958.  The while Statement
  1959.  
  1960.      A while loop evaluates its test expression before executing the body of
  1961.  the loop.
  1962.  
  1963.  A while loop repeats as long as a given condition remains true. It consists
  1964.  of the while keyword followed by a test expression in parentheses and a loop
  1965.  body, as shown in Figure 3.1. The "test expression" can be any C expression
  1966.  and is evaluated before the loop body is executed. The loop body is a single
  1967.  statement or a statement block that executes once every time the loop is
  1968.  iterated. The distinguishing feature of a while loop is that it evaluates
  1969.  the test expression before it executes the loop body, unlike the do loop,
  1970.  which we'll examine next.
  1971.  
  1972.  (This figure may be found in the printed book.)
  1973.  
  1974.  We've incorporated the simple while loop from Figure 3.1 in the WHILE.C
  1975.  program, shown below.
  1976.  
  1977.    /* WHILE.C: Demonstrate while loop. */
  1978.  
  1979.    #include <stdio.h>
  1980.  
  1981.    main()
  1982.    {
  1983.       int test = 10;
  1984.  
  1985.       while( test > 0 )
  1986.       {
  1987.          printf( "test = %d\n", test );
  1988.          test = test - 2;
  1989.       }
  1990.    }
  1991.  
  1992.  Here is the output from WHILE.C:
  1993.  
  1994.    test = 10
  1995.    test = 8
  1996.    test = 6
  1997.    test = 4
  1998.    test = 2
  1999.  
  2000.  In WHILE.C, if the variable  test  is positive when the loop begins, the
  2001.  test expression evaluates as true and the loop executes. If  test  has a 0
  2002.  or negative value when the loop starts, the test expression is false; the
  2003.  loop body does not execute and the action falls through to the statement
  2004.  that follows the loop.
  2005.  
  2006.  (Chapter 6, "Operators," explains true and false values. For now, it's
  2007.  enough to know that an expression is evaluated as false if it equals 0. Any
  2008.  nonzero value is true.)
  2009.  
  2010.  The loop body in WHILE.C happens to be a statement block enclosed in braces.
  2011.  If the loop body is a single statement, as in the following code, no braces
  2012.  are needed.
  2013.  
  2014.    main()
  2015.    {
  2016.       int test = 10;
  2017.       while( test > 0 )
  2018.          test = test - 2;
  2019.    }
  2020.  
  2021.  Occasionally, you'll see a while loop with a test expression such as
  2022.  
  2023.    while( 1 )
  2024.  
  2025.  or
  2026.  
  2027.    #define TRUE 1
  2028.       .
  2029.       .
  2030.       .
  2031.    while( TRUE )
  2032.  
  2033.  The test expressions above are always true, creating an indefinite loop that
  2034.  never ends naturally. You can only terminate this kind of loop with some
  2035.  overt action, usually by executing a break statement. (See "The break
  2036.  Statement" later in this chapter.) You can use such a loop to repeat an
  2037.  action for an indefinite time period─until a certain key is pressed, for
  2038.  instance.
  2039.  
  2040.  
  2041.  The do Statement
  2042.  
  2043.  A do loop is simply a while loop turned on its head. First comes the loop
  2044.  body, then the test expression. Unlike a while loop, a do loop always
  2045.  executes its loop body at least once.
  2046.  
  2047.     A do loop always executes at least once.
  2048.  
  2049.  The difference is important. A while statement evaluates the test expression
  2050.  before it executes the loop body. If the test expression in a while
  2051.  statement is false, the loop body doesn't execute at all. A do statement, on
  2052.  the other hand, evaluates the test expression after executing the loop body.
  2053.  Thus, the body of a do statement always executes at least once, even if the
  2054.  test expression is false when the loop begins.
  2055.  
  2056.  Figure 3.2 contrasts the while loop from WHILE.C with a comparable do loop
  2057.  to emphasize this difference. You'll notice that the do keyword comes right
  2058.  before the loop body, which is followed by the while keyword and a test
  2059.  expression─the same test expression that WHILE.C uses. Notice the semicolon
  2060.  that ends the do loop. A do loop always ends with a semicolon; a while loop
  2061.  never does.
  2062.  
  2063.  (This figure may be found in the printed book.)
  2064.  
  2065.  The DO.C program below uses the do loop from Figure 3.2 to perform the same
  2066.  action that WHILE.C does.
  2067.  
  2068.    /* DO.C: Demonstrate do loop. */
  2069.  
  2070.    #include <stdio.h>
  2071.  
  2072.    main()
  2073.    {
  2074.       int test = 10;
  2075.       do
  2076.       {
  2077.          printf( "test = %d\n", test );
  2078.          test = test - 2;
  2079.       }  while( test > 0 );
  2080.    }
  2081.  
  2082.  DO.C gives the same output as WHILE.C:
  2083.  
  2084.    test = 10
  2085.    test = 8
  2086.    test = 6
  2087.    test = 4
  2088.    test = 2
  2089.  
  2090.  The programs do not give the same output if you modify them so that the
  2091.  value of  test  is 0 when the loop starts. In that case, the loop body in
  2092.  DO.C executes once, but the loop body in WHILE.C doesn't execute at all. You
  2093.  should only use a do loop when you always want the loop body to execute at
  2094.  least once.
  2095.  
  2096.  
  2097.  The for Statement
  2098.  
  2099.  As in QuickBASIC or QuickPascal, the for statement in C is often used to
  2100.  repeat a statement a set number of times. Let's begin with a simple example.
  2101.  The FORLOOP.C program, shown below, uses for to repeat a printf statement
  2102.  five times.
  2103.  
  2104.    /* FORLOOP.C: Demonstrate for loop. */
  2105.  
  2106.    #include <stdio.h>
  2107.  
  2108.    main()
  2109.    {
  2110.       int test;
  2111.       for( test = 10; test > 0; test = test - 2 )
  2112.          printf( "test = %d\n", test );
  2113.    }
  2114.  
  2115.  FORLOOP.C gives the same output as WHILE.C and DO.C:
  2116.  
  2117.    test = 10
  2118.    test = 8
  2119.    test = 6
  2120.    test = 4
  2121.    test = 2
  2122.  
  2123.  Figure 3.3 shows the parts of the for loop in FORLOOP.C.
  2124.  
  2125.  (This figure may be found in the printed book.)
  2126.  
  2127.  A for statement is more complex than a while or do statement. The part in
  2128.  parentheses can contain three expressions separated by semicolons:
  2129.  
  2130.  
  2131.    ■   An "initializing expression" that often initializes a loop counter
  2132.  
  2133.    ■   A "test expression" that states how long the loop continues
  2134.  
  2135.    ■   A "modifying expression" that often modifies a loop counter
  2136.  
  2137.  
  2138.  Like the test expression in a while statement, the test expression in a for
  2139.  statement causes the loop to continue as long as the test expression
  2140.  evaluates as true.
  2141.  
  2142.  All of the expressions in the parentheses of a for statement are optional.
  2143.  If you omit the test expression (the second one), the statement repeats
  2144.  indefinitely. In the following program, for instance, all of the expressions
  2145.  in the parentheses of the for loop are empty:
  2146.  
  2147.    main()
  2148.    {
  2149.       for( ; ; )
  2150.          printf( "Hi, Mom!\n" );
  2151.    }
  2152.  
  2153.  The loop above repeats indefinitely because it has no test expression that
  2154.  specifies when to end the loop. It has the same effect as the following
  2155.  while loop, whose test expression is always true:
  2156.  
  2157.    main()
  2158.    {
  2159.       while( 1 )
  2160.          printf( "Hi, Mom!\n" );
  2161.    }
  2162.  
  2163.  You can use multiple expressions for either the initializing expression or
  2164.  the modifying expression, as in FORLOOP1.C:
  2165.  
  2166.    /* FORLOOP1.C: Demonstrate multiple expressions. */
  2167.  
  2168.    #include <stdio.h>
  2169.  
  2170.    main()
  2171.    {
  2172.       int a, b;
  2173.       for( a = 256, b = 1; b < 512; a = a / 2, b = b * 2 )
  2174.          printf( "a = %d  b = %d\n", a, b );
  2175.    }
  2176.  
  2177.  The output from FORLOOP1.C appears below:
  2178.  
  2179.    a = 256  b = 1
  2180.    a = 128  b = 2
  2181.    a = 64  b = 4
  2182.    a = 32  b = 8
  2183.    a = 16  b = 16
  2184.    a = 8    b = 32
  2185.    a = 4    b = 64
  2186.    a = 2    b = 128
  2187.    a = 1    b = 256
  2188.  
  2189.  In the FORLOOP1.C program, the initializing expression of the for loop
  2190.  initializes two variables ( a  and  b ) instead of one. The modifying
  2191.  expression changes the values of the same two variables. Use commas to
  2192.  separate multiple expressions in cases such as this.
  2193.  
  2194.  Although for and while might seem quite different, they're interchangeable
  2195.  in most cases. The FORLOOP2.C program demonstrates this principle. Both
  2196.  loops, while constructed differently, produce the same effect─printing the
  2197.  numbers from 0 through 9.
  2198.  
  2199.    /* FORLOOP2.C: Demonstrate similarity of for and while. */
  2200.  
  2201.    #include <stdio.h>
  2202.  
  2203.    main()
  2204.    {
  2205.       int count;
  2206.  
  2207.       for( count = 0; count < 10; count = count + 1 )
  2208.          printf( "count = %d\n", count );
  2209.  
  2210.       count = 0;
  2211.       while( count < 10 )
  2212.       {
  2213.          printf( "count = %d\n", count );
  2214.          count = count +1;
  2215.       }
  2216.  
  2217.    }
  2218.  
  2219.  The two loops in FORLOOP2.C function identically. The for loop prints the
  2220.  numbers from 0 through 9:
  2221.  
  2222.    for( count = 0; count < 10; count = count + 1; )
  2223.       printf( "count = %d\n", count );
  2224.  
  2225.  as does the while loop:
  2226.  
  2227.    count = 0;
  2228.    while( count < 10 )
  2229.    {
  2230.       printf( "count = %d\n", count );
  2231.       count = count + 1;
  2232.    }
  2233.  
  2234.  Most programmers prefer for over while in a case like this, because for
  2235.  groups all the loop-control statements in one place. The for statement is
  2236.  also appropriate when you need to initialize one or more values at the
  2237.  beginning of the loop. The while and do statements are more appropriate for
  2238.  cases in which the value used in the test expression has already been
  2239.  initialized.
  2240.  
  2241.  
  2242.  Decision-Making Statements: if, else, switch, break, continue, and goto
  2243.  
  2244.  The C language provides six statements for decision making: if, else,
  2245.  switch, break, continue, and goto. Like their counterparts in other
  2246.  languages, these statements transfer control based on the outcome of a
  2247.  logical test.
  2248.  
  2249.  
  2250.  The if Statement
  2251.  
  2252.   The body of an if statement executes when its test expression is true.
  2253.  
  2254.  An if statement consists of the if keyword followed by a test expression in
  2255.  parentheses and a second statement. The second statement is executed if the
  2256.  test expression is true, or skipped if the expression is false.
  2257.  
  2258.  The IFF.C program contains a simple if test. It prints a prompt and waits
  2259.  for you to press a key.
  2260.  
  2261.    /* IFF.C: Demonstrate if statement. */
  2262.  
  2263.    #include <stdio.h>
  2264.    #include <conio.h>
  2265.  
  2266.    main()
  2267.    {
  2268.       char ch;
  2269.       printf( "Press the b key to hear a bell.\n" );
  2270.       ch = getch();
  2271.       if( ch == 'b' )
  2272.          printf( "Beep!\a\n" );
  2273.    }
  2274.  
  2275.  In the IFF.C program, the statement
  2276.  
  2277.    ch = getch();
  2278.  
  2279.  calls the getch library function to get a keypress from the keyboard and
  2280.  then assigns the result to the variable  ch. If you press the b key, the
  2281.  program prints
  2282.  
  2283.    Beep!
  2284.  
  2285.  and sounds a beep. (To simplify the code, IFF.C tests only for a lowercase b
  2286.  character. A program would normally use a library function such as tolower
  2287.  to test for both upper and lowercase.)
  2288.  
  2289.  Figure 3.4 illustrates the parts of the if statement in the IFF.C program.
  2290.  
  2291.  (This figure may be found in the printed book.)
  2292.  
  2293.  The test expression of the if statement
  2294.  
  2295.    ch == 'b'
  2296.  
  2297.   The equality operator (==) tests if values are equal.
  2298.  
  2299.  is true when the variable  ch  equals the letter b. In C the equality
  2300.  operator (==) tests if two values are equal. (Chapter 6 discusses
  2301.  operators.)
  2302.  
  2303.  The body of the if statement in IFF.C happens to be a single statement, but
  2304.  the body can also be a statement block, as in the following fragment:
  2305.  
  2306.    if( ch == 'b' )
  2307.    {
  2308.       printf( "Beep!\a\n" );
  2309.       printf( "You pressed the 'b' key\n" );
  2310.    }
  2311.  
  2312.  You can also nest if statements, as shown below:
  2313.  
  2314.    if( ch == 'b' )
  2315.    {
  2316.       printf( "Beep!\a\n" );
  2317.       beep_count = beepcount + 1;
  2318.       if( beep_count > 10 )
  2319.       {
  2320.          printf( "More than 10 beeps...\n" );
  2321.          if( beep_count > 100 )
  2322.      printf( "Don't wear out the 'b' key!\n" );
  2323.       }
  2324.    }
  2325.  
  2326.  The code nests three if statements. The first if tests whether  ch  equals
  2327.  the letter b; the second tests whether the variable  beep_count  is greater
  2328.  than 10. The third tests whether  beep_count  exceeds 100.
  2329.  
  2330.  
  2331.  The else Clause
  2332.  
  2333.   An else clause can follow an if statement.
  2334.  
  2335.  The else keyword is used with if to form an either-or construct that
  2336.  executes one statement when an expression is true and another when it's
  2337.  false. The ELSE.C program demonstrates else by adding an else clause to the
  2338.  code from IFF.C. It sounds a beep and prints  Beep!  if you type the letter
  2339.  b, or it prints  Bye bye  if you type any other letter.
  2340.  
  2341.    /* ELSE.C: Demonstrate else clause. */
  2342.  
  2343.    #include <stdio.h>
  2344.    #include <conio.h>
  2345.  
  2346.    main()
  2347.    {
  2348.       char ch;
  2349.       printf( "Press the b key to hear a bell.\n" );
  2350.       ch = getch();
  2351.       if( ch == 'b' )
  2352.          printf( "Beep!\a\n" );
  2353.       else
  2354.          printf( "Bye bye\n" );
  2355.    }
  2356.  
  2357.   To create an else-if construct, place an if statement after an else.
  2358.  
  2359.  The C language has no "elseif" keyword, but it's easy to create the same
  2360.  effect, because the statement that follows else can be any C
  2361.  statement─including another if statement. The ELSE1.C program uses if and
  2362.  else to test three conditions. It sounds a beep when you type the letter b,
  2363.  it prints  Enter  when you press the ENTER key, or it prints  Bye bye  when
  2364.  you press any other key.
  2365.  
  2366.    /* ELSE1.C: Demonstrate else-if construct. */
  2367.  
  2368.    #include <stdio.h>
  2369.    #include <conio.h>
  2370.  
  2371.    main()
  2372.    {
  2373.       char ch;
  2374.       printf( "Press the b key to hear a bell.\n" );
  2375.       ch = getch();
  2376.       if( ch == 'b' )
  2377.          printf( "Beep!\a\n" );
  2378.       else
  2379.          if( ch == '\r' )
  2380.             printf( "Enter\n" );
  2381.       else
  2382.          printf( "Bye bye\n" );
  2383.    }
  2384.  
  2385.  The else keyword is tied to the closest preceding if that's not already
  2386.  matched by an else. Keep this rule in mind when creating nested if-else
  2387.  constructs. (See the section "Mismatching if and else Statements" in Chapter
  2388.  10, "Programming Pitfalls.")
  2389.  
  2390.  
  2391.  The switch Statement
  2392.  
  2393.   The switch statement can perform multiple branches.
  2394.  
  2395.  The switch statement offers an elegant option in situations that require
  2396.  multiple branches. It tests a single expression that can have several
  2397.  values, providing a different action for each value.
  2398.  
  2399.  One disadvantage of if and else is that they only allow one branch per
  2400.  keyword. The program either executes the statement that follows the if or
  2401.  else, or it doesn't. To perform more complex tests, you have to pile on more
  2402.  if and else statements, as in the ELSE1.C program above.
  2403.  
  2404.  A program that handles keyboard input, for instance, may require several
  2405.  different responses to various keypresses. The ELSE1.C program above used
  2406.  combinations of if and else to process keyboard input. We've used a single
  2407.  switch statement in the SWITCH.C program below to do the same job:
  2408.  
  2409.    /* SWITCH.C: Demonstrate switch statement. */
  2410.  
  2411.    #include <stdio.h>
  2412.    #include <conio.h>
  2413.  
  2414.    main()
  2415.    {
  2416.       char ch;
  2417.       printf( "Press the b key to hear a bell.\n" );
  2418.       ch = getch();
  2419.       switch( ch )
  2420.       {
  2421.          case 'b':
  2422.             printf( "Beep!\a\n" );
  2423.             break;
  2424.          case '\r':
  2425.             printf( "Enter\n" );
  2426.             break;
  2427.          default:
  2428.             printf( "Bye bye" );
  2429.             break;
  2430.       }
  2431.    }
  2432.  
  2433.  The SWITCH.C program produces the same output as ELSE1.C. Figure 3.5
  2434.  illustrates the switch statement in SWITCH.C, comparing it with the if-else
  2435.  construct in ELSE1.C.
  2436.  
  2437.  (This figure may be found in the printed book.)
  2438.  
  2439.  As in other decision-making statements, the parentheses after the keyword
  2440.  contain the expression to test. This can be any expression that yields a
  2441.  constant value. The test expression in SWITCH.C evaluates the value of the
  2442.  variable  ch:
  2443.  
  2444.    switch( ch )
  2445.  
  2446.   The switch statement branches to one of several labeled alternatives.
  2447.  
  2448.  The test expression is followed by a statement block enclosed in curly
  2449.  braces. The block contains alternate sections of code that you want to
  2450.  execute under various circumstances. The program's action branches to one of
  2451.  the alternatives, depending on the value of the test expression.
  2452.  
  2453.  Each alternative in the statement block starts with a "case label," which
  2454.  consists of the case keyword, a constant or constant expression, and a
  2455.  colon. (The only other C statement that uses labels is goto, which we'll
  2456.  discuss later in this chapter.)
  2457.  
  2458.  Below is the first case label in SWITCH.C:
  2459.  
  2460.    case 'b':
  2461.  
  2462.  This case label lists the character constant  'b'. If the variable  ch
  2463.  equals  'b', the program's action branches to this label. If  ch  equals
  2464.  '\r', the program branches to the following label:
  2465.  
  2466.    case '\r':
  2467.  
  2468.  The basic effect of switch is similar to the SELECT CASE statement in
  2469.  QuickBASIC. The program can branch to many different alternatives, but only
  2470.  one at a time.
  2471.  
  2472.  A switch statement can have as many case alternatives as you need. Each
  2473.  alternative must be labeled with a constant value. (You can't use a variable
  2474.  in the label.)
  2475.  
  2476.  ────────────────────────────────────────────────────────────────────────────
  2477.  NOTE
  2478.  
  2479.  In previous versions of QuickC, the constant in a case label could only be a
  2480.  char or int value. In QuickC 2.5, the constant can be any integral type,
  2481.  including a long or unsigned long as well as a char or int.
  2482.  hapter 4, "Data Types," describes the char, int, and long types.
  2483.  ────────────────────────────────────────────────────────────────────────────
  2484.  
  2485.   The default keyword is used only in switch statements.
  2486.  
  2487.  SWITCH.C also shows how to use the default keyword in a switch statement.
  2488.  The statements after the default label execute if the value of the test
  2489.  expression doesn't equal any of the values listed in other labels. In
  2490.  SWITCH.C, the code following default executes when the variable  ch  equals
  2491.  anything other than  'b'  or  '\r'.
  2492.  
  2493.  Not every switch statement requires a default label. If no default is
  2494.  present, and the test expression doesn't match any of the values listed in
  2495.  the other case labels, no statements are executed.
  2496.  
  2497.   Use the break keyword to exit a switch statement.
  2498.  
  2499.  You normally place a break statement at the end of each alternative, as
  2500.  shown in SWITCH.C. The break statement exits the switch statement block
  2501.  immediately. If you don't put a break at the end of the alternative, the
  2502.  action falls through to the next statement.
  2503.  
  2504.  For instance, say that you remove all the break statements from SWITCH.C, as
  2505.  shown below:
  2506.  
  2507.    switch( ch )
  2508.    {
  2509.       case 'b':
  2510.          printf( "Beep!\a\n" );
  2511.       case '\r':
  2512.          printf( "Enter\n" );
  2513.       default:
  2514.          printf( "Bye bye" );
  2515.    }
  2516.  
  2517.  If you run the revised program and type the letter b, the program executes
  2518.  the first alternative, producing this output:
  2519.  
  2520.    Beep!
  2521.  
  2522.  then goes on to execute the statements that follow:
  2523.  
  2524.    Enter
  2525.    Bye bye
  2526.  
  2527.  Occasionally, you may want to fall through from one case alternative to
  2528.  another. But you should be careful not to omit break statements
  2529.  accidentally. (See the section "Omitting break Statements from a switch
  2530.  Statement" in Chapter 10, "Programming Pitfalls.")
  2531.  
  2532.  If you end each alternative with a break, as in SWITCH.C, the order of the
  2533.  alternatives isn't critical. The program branches to the label containing
  2534.  the correct value, no matter where that label appears in the switch
  2535.  statement block. For instance, you can reverse the order of the alternatives
  2536.  in SWITCH.C without changing the program's output. For readability's sake,
  2537.  many programmers put default at the end of a switch statement and arrange
  2538.  the other alternatives alphabetically or numerically.
  2539.  
  2540.  Sometimes you'll want to execute the same code for more than one case. This
  2541.  is done by grouping all the desired labels in front of one alternative. For
  2542.  instance, if you revise the second alternative in SWITCH.C to read
  2543.  
  2544.    case '\r':
  2545.    case '\t':
  2546.    case ' ':
  2547.      printf( "What a boring choice!\n" );
  2548.      break;
  2549.  
  2550.  the program will print
  2551.  
  2552.    What a boring choice!
  2553.  
  2554.  when you press the ENTER key, the TAB key, or the SPACEBAR.
  2555.  
  2556.  
  2557.  The break Statement
  2558.  
  2559.  The previous section explained how to use break to exit from a switch
  2560.  statement. You can also use break to end a loop immediately. The BREAKER.C
  2561.  program shows how to do this. The program prints a prompt, then displays
  2562.  characters as they are typed until the TAB key is pressed.
  2563.  
  2564.    /* BREAKER.C: Demonstrate break statement. */
  2565.  
  2566.    #include <stdio.h>
  2567.    #include <conio.h>
  2568.  
  2569.    main()
  2570.    {
  2571.       char ch;
  2572.       printf( "Press any key. Press Tab to quit.\n" );
  2573.       while( 1 )
  2574.       {
  2575.          ch = getche();
  2576.          if( ch == '\t' )
  2577.  
  2578.    {
  2579.      printf( "\a\nYou pressed Tab\n" );
  2580.      break;
  2581.          }
  2582.       }
  2583.    }
  2584.  
  2585.  The while statement in BREAKER.C creates an indefinite loop that calls the
  2586.  getche function again and again, assigning the function's return value to
  2587.  the variable  ch. The if statement in the loop body compares  ch  to the tab
  2588.  character. When TAB is pressed, BREAKER.C prints  You pressed Tab  and
  2589.  executes the break statement, which terminates the while loop and ends the
  2590.  program.
  2591.  
  2592.   A break statement exits only one loop.
  2593.  
  2594.  It's important to remember that the break statement only ends the loop in
  2595.  which it appears. If two loops are nested, executing a break in the inner
  2596.  loop exits that loop but not the outer loop. BREAKER1.C shows how break
  2597.  works within nested loops. The program's inner loop checks for the TAB key
  2598.  and the outer loop checks for the ENTER key.
  2599.  
  2600.    /* BREAKER1.C: Break only exits one loop. */
  2601.  
  2602.    #include <stdio.h>
  2603.    #include <conio.h>
  2604.  
  2605.    main()
  2606.    {
  2607.       char ch;
  2608.       printf( "Press any key. Press Enter to quit.\n" );
  2609.       do
  2610.       {
  2611.          while( ( ch = getche() ) != '\r' )
  2612.          {
  2613.             if( ch == '\t' )
  2614.             {
  2615.                printf( "\a\nYou pressed Tab\n" );
  2616.                break;
  2617.             }
  2618.          }
  2619.       } while( ch != '\r' );
  2620.       printf( "\nBye bye." );
  2621.    }
  2622.  
  2623.  The BREAKER1.C program includes a while loop nested within a do loop. Both
  2624.  loops test the same condition─whether the variable  ch  equals the ENTER key
  2625.  (\r). The while loop also calls the getche function, assigning the
  2626.  function's return value to  ch.
  2627.  
  2628.  When TAB is pressed, the program prints  You pressed Tab  and executes a
  2629.  break statement, which terminates the inner loop. The break does not end the
  2630.  outer loop, however. The program continues until ENTER is pressed, providing
  2631.  the condition that ends both loops.
  2632.  
  2633.  Note that break can only be used to exit a loop or switch statement. While
  2634.  you might be tempted to use break to jump out of complex if or else
  2635.  statements, the break statement cannot be used for this purpose. It has no
  2636.  effect on if and else.
  2637.  
  2638.  
  2639.  The continue Statement
  2640.  
  2641.   The continue statement skips remaining statements in the loop body where it
  2642.  appears.
  2643.  
  2644.  The continue statement, like break, interrupts the normal flow of execution
  2645.  in a loop body. But instead of ending the loop, continue skips all following
  2646.  statements in the loop body and triggers the next iteration of the loop.
  2647.  This effect can be useful within complex loops, in which you might wish to
  2648.  skip to the next loop iteration from various locations.
  2649.  
  2650.  The CONT.C program shows how continue works. It increments the  count
  2651.  variable, counting from 0 through 9, but stops printing the value of  count
  2652.  when that value exceeds 3.
  2653.  
  2654.    /* CONT.C: Demonstrate continue statement. */
  2655.  
  2656.    #include <stdio.h>
  2657.  
  2658.    main()
  2659.    {
  2660.       int count;
  2661.       for( count = 0; count < 10; count = count + 1 )
  2662.       {
  2663.          if( count > 3 )
  2664.             continue;
  2665.          printf( "count = %d\n", count );
  2666.       }
  2667.       printf( "Done!\n" );
  2668.    }
  2669.  
  2670.  Here's the output from CONT.C:
  2671.  
  2672.    count = 0
  2673.    count = 1
  2674.    count = 2
  2675.    count = 3
  2676.    Done!
  2677.  
  2678.  The continue statement occurs within the body of the for loop. When the
  2679.  value of  count  exceeds 3, the continue skips the rest of the loop body─a
  2680.  statement that calls printf─and causes the next iteration of the loop.
  2681.  
  2682.  
  2683.  The goto Statement
  2684.  
  2685.   The goto statement jumps from one part of the function to another.
  2686.  
  2687.  Similar to the GOTO statement in BASIC, goto in C performs an unconditional
  2688.  jump from one part of a function to any other part. The target of the goto
  2689.  statement is a label which you supply. The label must end with a colon, as
  2690.  do case labels, which we discussed earlier.
  2691.  
  2692.  Most C programmers avoid using the goto statement. It's a bit inconsistent
  2693.  with the overall philosophy of C, which encourages structured, modular
  2694.  programming. And, regardless of philosophy, it can be very difficult to read
  2695.  and debug a program that is littered with haphazard unconditional jumps.
  2696.  
  2697.  Nevertheless, goto has at least one sensible use. If a serious error occurs
  2698.  deep within a nested series of loops or conditional statements, goto offers
  2699.  the simplest escape. The following code has several levels of nesting, with
  2700.  a goto statement at the innermost level. If the value of  error_count
  2701.  exceeds 15, the goto statement executes, transferring control to the label
  2702.  bail_out.
  2703.  
  2704.    if( a == 1 )
  2705.    {
  2706.       while( b == 2 )
  2707.       {
  2708.          for( c = 0; c < 3; c = c + 1 )
  2709.          {
  2710.             if( d == 4 )
  2711.             {
  2712.                while( e == 6 )
  2713.                {
  2714.                   if( error_count > 15 )
  2715.                      goto bail_out;
  2716.                }
  2717.             }
  2718.          }
  2719.       }
  2720.    }
  2721.    bail_out:  /* The goto statement transfers control here. */
  2722.  
  2723.  To achieve the same effect without goto, you'd have to add extra conditional
  2724.  tests to this code, making the code more complex and perhaps less efficient.
  2725.  
  2726.  
  2727.  Names in goto labels are governed by the rules for variable names, which
  2728.  we'll discuss in the next two chapters. For now, just remember that a goto
  2729.  label is visible only in the function in which it appears. You can't execute
  2730.  a goto statement to jump from one function to another function.
  2731.  
  2732.  The next two chapters explain how to create and manipulate data─variables
  2733.  and constants─in C programs. Chapter 4, "Data Types," describes the basics,
  2734.  such as how to declare and initialize variables of different types. Chapter
  2735.  5, "Advanced Data Types," describes more advanced topics, such as the
  2736.  visibility of variables.
  2737.  
  2738.  
  2739.  
  2740.  
  2741.  
  2742.  
  2743.  Chapter 4  Data Types
  2744.  ────────────────────────────────────────────────────────────────────────────
  2745.  
  2746.  This chapter explains the C data types and shows how to declare and use C
  2747.  variables. The chapter begins by describing the basic data types from which
  2748.  all other data types are derived. We then discuss more complex data types,
  2749.  including arrays and structures. In Chapter 5, "Advanced Data Types," we'll
  2750.  explore more advanced data-handling topics, such as variable visibility and
  2751.  automatic type conversions.
  2752.  
  2753.  
  2754.  Basic Data Types
  2755.  
  2756.  All data in C programs is either a constant or variable, and each has an
  2757.  associated data type. The concept of types is common to all high-level
  2758.  languages. For instance, an integer (whole) number has the INTEGER type in
  2759.  QuickBASIC, the Integer type in QuickPascal, and the int type in C. This
  2760.  section describes the basic data types in C and explains how to specify
  2761.  variables and constants using these types.
  2762.  
  2763.  All of the basic data types contain a single value. Types that contain more
  2764.  than one value─arrays, structures, and unions─are called "aggregate types."
  2765.  We'll discuss aggregate types later in this chapter.
  2766.  
  2767.  
  2768.  Specifying Basic Types
  2769.  
  2770.  The C language has four basic data types, which are specified with the
  2771.  keywords char, int, float, and double. The char (character) type is used for
  2772.  text and the int type for integers. The float and double types express real
  2773.  (floating-point) values.
  2774.  
  2775.  The TYPES.C program creates variables of the four basic types and prints
  2776.  their values:
  2777.  
  2778.    /* TYPES.C: Illustrate basic data types. */
  2779.  
  2780.    #include <stdio.h>
  2781.  
  2782.    main()
  2783.    {
  2784.       char char_val       = 'a';
  2785.       int int_val         = 543;
  2786.       float float_val     = 11.1;
  2787.       double double_val   = 66.123456789;
  2788.       printf( "char_val   = %c\n", char_val );
  2789.       printf( "int_val    = %d\n", int_val );
  2790.       printf( "float_val  = %f\n", float_val );
  2791.       printf( "double_val = %2.9f\n", double_val );
  2792.    }
  2793.  
  2794.  Here is the output from TYPES.C:
  2795.  
  2796.    char_val   = a
  2797.    int_val    = 543
  2798.    float_val  = 11.100000
  2799.    double_val = 66.123456789
  2800.  
  2801.  Each basic data type requires a different amount of memory, as illustrated
  2802.  in Figure 4.1. In QuickC, a char contains one byte, an int has two bytes, a
  2803.  float has four bytes, and a double type has eight bytes.
  2804.  
  2805.  (This figure may be found in the printed book.)
  2806.  
  2807.  ────────────────────────────────────────────────────────────────────────────
  2808.  NOTE
  2809.  
  2810.  The C language is designed to run on many different computers, with machine
  2811.  architectures that may be quite different. To accommodate these differences,
  2812.  some C data types are "implementation dependent," meaning their sizes depend
  2813.  on which computer you're using. For instance, the int (integer) type
  2814.  contains two bytes on IBM PC computers and four bytes on VAX(R)
  2815.  minicomputers. These differences are important only if you're transporting a
  2816.  program from one operating system to another. Since QuickC runs only under
  2817.  one operating system (DOS), this book describes C data types in DOS.
  2818.  ────────────────────────────────────────────────────────────────────────────
  2819.  
  2820.  
  2821.  Special Type Specifiers
  2822.  
  2823.  The C language has four special type specifiers─signed, unsigned, long, and
  2824.  short. These act as "adjectives" to modify the range of values expressed by
  2825.  a basic data type.
  2826.  
  2827.   The char and int data types  are signed by default.
  2828.  
  2829.  The signed keyword signifies that a value can be either negative or
  2830.  nonnegative. If you don't specify, a char or int value is signed.
  2831.  
  2832.  You can preface a char or int with unsigned to extend the range of
  2833.  nonnegative values. An unsigned int can have a value in the range 0 through
  2834.  65,535, and an unsigned char can have a value of 0 through 255.
  2835.  
  2836.  The long keyword is used to increase the size of an int or double type. A
  2837.  long int value contains four bytes (twice as many as an int) and expresses
  2838.  an integer in the range -2,147,483,648 through 2,147,483,647. A long double
  2839.  value contains 10 bytes and can express a floating-point number with 19
  2840.  digits of precision.
  2841.  
  2842.  In QuickC, the short int type is identical to the int type. (This is not the
  2843.  case in some operating systems other than DOS.)
  2844.  
  2845.  Table 4.1 lists the basic data types and the range of values each can
  2846.  express.
  2847.  
  2848.  Table 4.1  Basic Data Types
  2849.  
  2850. ╓┌────────────────┌────────────────────────┌─────────────────────────────────╖
  2851.  Type Name        Other Names              Range of Values
  2852.  ────────────────────────────────────────────────────────────────────────────
  2853.  char             signed char              -128 to 127
  2854.  
  2855.  unsigned char    none                     0 to 255
  2856.  
  2857.  int              signed, signed int       -32,768 to 32,767
  2858.  Type Name        Other Names              Range of Values
  2859.  ────────────────────────────────────────────────────────────────────────────
  2860. int              signed, signed int       -32,768 to 32,767
  2861.  
  2862.  unsigned         unsigned int             0 to 65,535
  2863.  
  2864.  unsigned short   unsigned short int       0 to 65,535
  2865.  
  2866.  short            short int, signed short  -32,768 to 32,767
  2867.  
  2868.                   signed short int
  2869.  
  2870.  long             long int, signed long    -2,147,483,648 to
  2871.  
  2872.                   signed long int          2,147,483,647
  2873.  
  2874.  unsigned long    unsigned long int        0 to 4,294,967,295
  2875.  
  2876.  
  2877.  
  2878.  
  2879.  Type Name        Other Names              Range of Values
  2880.  ────────────────────────────────────────────────────────────────────────────
  2881. 
  2882.  float            none                     Approximately 1.2E-38 to 3.4E+38
  2883.                                            (7-digit
  2884.                                            precision)
  2885.  
  2886.  double           none                     Approximately 2.2E-308 to
  2887.                                            1.8E+308 (15-digit
  2888.                                            precision)
  2889.  
  2890.  long double      none                     Approximately 3.4E-4932 to
  2891.                                            1.2E+4932 (19-digit precision)
  2892.  
  2893.  ────────────────────────────────────────────────────────────────────────────
  2894.  
  2895.  
  2896.  
  2897.  Most programmers take advantage of type defaults. If a type qualifier
  2898.  appears alone, the type int is implied. By itself, short is a synonym for
  2899.  short int. Where long appears alone it is a synonym for long int, and where
  2900.  unsigned appears alone it is a synonym for unsigned int.
  2901.  
  2902.  
  2903.  Specifying Variables
  2904.  
  2905.  As we mentioned in Chapter 1, "Anatomy of a C Program," you must declare
  2906.  every variable in a C program by stating the variable's name and type.
  2907.  Variable names are governed by the following rules, which also apply to
  2908.  other userdefined names such as function names:
  2909.  
  2910.  
  2911.    ■   C is case-sensitive. For example,  myvar,  MyVar, and  MYVAR  are
  2912.        different names.
  2913.  
  2914.    ■   The name can't be a keyword (see online help for a list of keywords).
  2915.  
  2916.    ■   The first character must be a letter or underscore ( _ ). Many of
  2917.        QuickC's system-defined names, including some library-routine names,
  2918.        begin with underscores. To avoid conflicts with such names, don't
  2919.        create names that begin with underscores.
  2920.  
  2921.    ■   Other characters can be letters, digits, or underscores.
  2922.  
  2923.    ■   The first 31 characters of local variable names are significant. The
  2924.        name can contain more than 31 characters, but QuickC ignores
  2925.        everything beyond the thirty-first character. Global variable names
  2926.        are normally significant to 30 characters.
  2927.  
  2928.  
  2929.  All C keywords are lowercase, and it's common to use lowercase for variable
  2930.  names. Mixed case is becoming popular in some contexts, however. OS/2 and
  2931.  Microsoft Windows(tm) use mixed case for most system-defined names.
  2932.  
  2933.  
  2934.  Specifying Constants
  2935.  
  2936.  Constants─values that don't change during the life of the program─can be
  2937.  numbers, characters, or strings. Your program can also define "symbolic
  2938.  constants," which are names that represent constant values. This section
  2939.  describes how to specify C constants.
  2940.  
  2941.  
  2942.  Numeric Constants
  2943.  
  2944.  A numeric constant can have any basic data type, and can be specified in
  2945.  decimal, hexadecimal, or octal notation. Table 4.2 shows how to specify
  2946.  numeric constants.
  2947.  
  2948.  Table 4.2  Constant Specifications
  2949.  
  2950. ╓┌──────────────────┌────────────────────────────────────────────────────────╖
  2951.  Constant           Type
  2952.  ────────────────────────────────────────────────────────────────────────────
  2953.  255                decimal int
  2954.  0xFF               hexadecimal int (255)
  2955.  0377               octal int (255)
  2956.  255L               long int
  2957.  255U               unsigned int
  2958.  0xFFul             long unsigned hexadecimal int (255)
  2959.  15.75E2            floating point (1575)
  2960.  -.123              floating point
  2961.  .123               floating point
  2962.  3e0f               floating point
  2963.  Constant           Type
  2964.  ────────────────────────────────────────────────────────────────────────────
  2965. 3e0f               floating point
  2966.  ────────────────────────────────────────────────────────────────────────────
  2967.  
  2968.  
  2969.  A number without a suffix, such as 255, is treated as decimal. The  0x
  2970.  prefix specifies a hexadecimal number, and the  0  (zero) prefix specifies
  2971.  octal (base 8).
  2972.  
  2973.  If a number doesn't have a decimal point, it is an integer. Integers are
  2974.  signed by default; you can use the suffix  U  or  u  to specify an unsigned
  2975.  constant. To specify a long integer, place the suffix  L  or  l  after the
  2976.  number.
  2977.  
  2978.  A floating-point constant contains either a decimal point or an exponent
  2979.  preceded by  e  or  E . It can optionally include the suffix  F  or  f  to
  2980.  denote the float type or the suffix  L  or  l to denote the long double
  2981.  type.
  2982.  
  2983.  
  2984.  Character and String Constants
  2985.  
  2986.  The C language uses different notation for character and string constants. A
  2987.  single character enclosed in single quotes is a character constant:
  2988.  
  2989.    'a'
  2990.  
  2991.  A string constant is 0 or more characters enclosed in double quotes:
  2992.  
  2993.    "Hello"
  2994.  
  2995.  A string also ends with a null character (\0), as we'll see in the section
  2996.  "Strings."
  2997.  
  2998.  The difference between character and string constants is important when you
  2999.  perform comparisons. The character constant  'a'  contains 1 character, but
  3000.  the string constant  "a"  contains 2 characters: the letter  a  plus a null
  3001.  character. Because the two values have a different number of characters, any
  3002.  comparison of them is invalid. (See "String Problems" in Chapter 10,
  3003.  "Programming Pitfalls.")
  3004.  
  3005.  You can specify special characters, such as the tab and backspace, with a
  3006.  multi-character sequence that begins with a backslash ( \ ). These sequences
  3007.  are sometimes called "escape sequences." Table 4.3 shows the special
  3008.  character sequences.
  3009.  
  3010.  Table 4.3  Special Characters
  3011.  
  3012. ╓┌───────────────────────┌───────────────────────────────────────────────────╖
  3013.  Sequence                Character
  3014.  ────────────────────────────────────────────────────────────────────────────
  3015.  \a                      Alert (bell)
  3016.  \b                      Backspace
  3017.  \f                      Form feed
  3018.  \n                      Newline
  3019.  \r                      Carriage return
  3020.  \t                      Horizontal tab
  3021.  \v                      Vertical tab
  3022.  \'                      Single quote
  3023.  \"                      Double quote
  3024.  \\                      Backslash
  3025.  \ooo                    Octal notation
  3026.  Sequence                Character
  3027.  ────────────────────────────────────────────────────────────────────────────
  3028. \ooo                    Octal notation
  3029.  \xhh                    Hexadecimal notation
  3030.  \0                      Null
  3031.  ────────────────────────────────────────────────────────────────────────────
  3032.  
  3033.  
  3034.  Some unusual characters don't have a predefined sequence. You can specify
  3035.  these with a backslash ( \ ) followed by the hexadecimal or octal number
  3036.  representing the character's ASCII value. For instance, a telecommunications
  3037.  program might need to specify ASCII 21, the NAK ("not acknowledged")
  3038.  character. You can specify this character in either hexadecimal notation,
  3039.  '\x15', or octal notation, '\25'. Note that the hexadecimal number begins
  3040.  with  \x, while the octal number starts with a backslash alone.
  3041.  
  3042.  
  3043.  Symbolic Constants
  3044.  
  3045.  A "symbolic constant" is a user-defined name that represents a constant.
  3046.  Symbolic constants are usually typed in uppercase. For instance, the
  3047.  directive
  3048.  
  3049.    #define PI 3.14
  3050.  
  3051.  declares a symbolic constant named  PI. Wherever  PI  occurs in the program,
  3052.  the compiler substitutes  3.14. Chapter 7, "Preprocessor Directives,"
  3053.  discusses symbolic constants and the #define directive.
  3054.  
  3055.  
  3056.  Aggregate Data Types
  3057.  
  3058.  This section describes aggregate data types, which contain organized
  3059.  collections of data in a definite order. In C, the aggregate types are
  3060.  arrays, structures, and unions.
  3061.  
  3062.  An "array" is a collection of data items of the same type. Programs use
  3063.  arrays in cases where a standard data format is repeated many times. For
  3064.  example, you might use an array to store numbers representing the population
  3065.  of Minnesota for all the years from 1950 to 2000. C-language arrays are very
  3066.  similar to arrays in QuickPascal and QuickBASIC.
  3067.  
  3068.  A "structure" is a collection of data items of different types. Programs use
  3069.  structures in cases where a variety of data have a close association. For
  3070.  example, you might use a structure to store information about a given
  3071.  employee─name, months of employment, and hourly wage. Structures are similar
  3072.  to QuickPascal records or QuickBASIC user-defined types.
  3073.  
  3074.  A "union" allows you to use different data formats to access the same area
  3075.  of memory. It can hold different kinds of information at different times.
  3076.  Unions are similar to variant records in QuickPascal.
  3077.  
  3078.  
  3079.  Arrays
  3080.  
  3081.   An array is a group of  data items of the same  type under one name.
  3082.  
  3083.  The simplest aggregate data type is an array: a group of data items that
  3084.  share the same type and a common name. You can make an array from any data
  3085.  type, including basic types such as char and int and more complex types such
  3086.  as structures. This section shows how to declare, initialize, and access
  3087.  arrays, including arrays with more than one dimension. We'll begin with a
  3088.  simple example that creates a one-dimensional array.
  3089.  
  3090.  
  3091.  Creating a Simple Array
  3092.  
  3093.  The ARRAY.C program creates the array  i_array, which contains three
  3094.  integers.
  3095.  
  3096.    /* ARRAY.C: Demonstrate one-dimensional array. */
  3097.  
  3098.    #include <stdio.h>
  3099.  
  3100.    main()
  3101.    {
  3102.       int j;
  3103.       int i_array[3];
  3104.  
  3105.       i_array[0] = 176;
  3106.       i_array[1] = 4069;
  3107.       i_array[2] = 303;
  3108.  
  3109.       printf( "--- Values --------     --- Addresses -------\n\n" );
  3110.  
  3111.       for( j = 0; j < 3; j = j + 1 )
  3112.       {
  3113.          printf( "i_array[%d] = %d", j, i_array[j] );
  3114.          printf( "\t&i_array[%d] = %u\n", j, &i_array[j] );
  3115.       }
  3116.  
  3117.    }
  3118.  
  3119.  Here is the output from ARRAY.C:
  3120.  
  3121.    --- Values --------     --- Addresses -------
  3122.  
  3123.    i_array[0] = 176        &i_array[0] = 3506
  3124.    i_array[1] = 4069       &i_array[1] = 3508
  3125.    i_array[2] = 303        &i_array[2] = 3510
  3126.  
  3127.  As you can see, ARRAY.C prints the values in  i_array  and the memory
  3128.  address where each array element is stored. You usually don't have to worry
  3129.  about actual memory addresses in C, but it's useful to have some idea how
  3130.  array elements are stored in memory. Depending on factors such as the amount
  3131.  of memory in your system, you may see different addresses when you run
  3132.  ARRAY.C.
  3133.  
  3134.  (The second printf statement uses the "address-of" operator (&) to determine
  3135.  the address of each array element. Chapter 6, "Operators," explains this
  3136.  operator. For now, it's sufficient to recognize that the operator allows
  3137.  ARRAY.C to print addresses.)
  3138.  
  3139.  Figure 4.2 shows how  i_array  is stored in the addresses from the ARRAY.C
  3140.  output.
  3141.  
  3142.  (This figure may be found in the printed book.)
  3143.  
  3144.  
  3145.  Declaring the Array
  3146.  
  3147.  You declare an array variable by stating its type and its name, as you would
  3148.  a simple variable. You must also declare the size of the array, stating the
  3149.  number of elements with an integer constant in square brackets. For example,
  3150.  the line
  3151.  
  3152.    int i_array[3];
  3153.  
  3154.  from ARRAY.C declares a three-element integer (int) array named  i_array.
  3155.  
  3156.  Multidimensional arrays are declared the same way, except you must give the
  3157.  size of each dimension. The following statement, for instance, declares a
  3158.  twodimensional int array named  two_dim:
  3159.  
  3160.    int two_dim[2][3];
  3161.  
  3162.  We'll return to multidimensional arrays a little later in this chapter.
  3163.  
  3164.  
  3165.  Initializing the Array
  3166.  
  3167.  Arrays, like simple variables, should be initialized before use. ARRAY.C
  3168.  initializes  i_array  with these statements:
  3169.  
  3170.    i_array[0] = 176;
  3171.    i_array[1] = 4069;
  3172.    i_array[2] = 303;
  3173.  
  3174.   An array can be initialized  when it is declared.
  3175.  
  3176.  ARRAY.C declares an array in one statement and then initializes its elements
  3177.  one by one. You can also initialize an array when you declare it. The
  3178.  following statement does both jobs at once:
  3179.  
  3180.    int i_array[3] = { 176, 4069, 303 };
  3181.  
  3182.  Note the curly braces around the initializing values. The braces are
  3183.  mandatory in this kind of initialization.
  3184.  
  3185.  Under the ANSI C standard, which QuickC version 2.5 follows, you can
  3186.  simultaneously declare and initialize an array within a function. Pre-ANSI
  3187.  compilers, including QuickC version 1.0, don't allow this unless the static
  3188.  keyword precedes the array declaration. Chapter 5, "Advanced Data Types,"
  3189.  discusses static.
  3190.  
  3191.  When you declare and initialize an array at the same time, the initializing
  3192.  values are normally constants, as shown above. Occasionally, you may want to
  3193.  initialize an array as you declare it using variables instead of constants.
  3194.  QuickC version 2.5 allows this, but only within a function. The  sample
  3195.  array in the following example is initialized legally under QuickC version
  3196.  2.5 but illegally under QuickC version 1.0:
  3197.  
  3198.    func()
  3199.    {
  3200.       int val = 5;
  3201.       int sample[3] = { val, val, val };
  3202.    }
  3203.  
  3204.  If you initialize a local array in this way, you must include the size of
  3205.  the array within the square brackets following the array name. If the
  3206.  example initialized the  sample  array with the following line:
  3207.  
  3208.    int sample[ ] = {val, val, val};
  3209.  
  3210.  QuickC would issue an error because the size of the array (3) is not
  3211.  specified.
  3212.  
  3213.  
  3214.  Specifying Array Elements
  3215.  
  3216.   Array subscripts are enclosed in square brackets ( [ ] ).
  3217.  
  3218.  You specify an array element by giving its position, using an integer value
  3219.  called a "subscript." Square brackets ([ ]) enclose each subscript. In the
  3220.  ARRAY.C program above we specify the first element of  i_array  as
  3221.  
  3222.    i_array[0]
  3223.  
  3224.  Notice that the first element of a C array has the subscript 0, not 1.
  3225.  Unlike QuickPascal and QuickBASIC, the C language does not give you the
  3226.  option to start at an index number other than 0.
  3227.  
  3228.  Since array subscripts begin at 0, the subscript of the last array element
  3229.  is 1 less than the number used to declare that dimension of the array. In
  3230.  ARRAY.C, the last element of  i_array  is  i_array[2] , not  i_array[3].
  3231.  
  3232.   C doesn't check array subscripts.
  3233.  
  3234.  Unlike QuickBASIC and QuickPascal, C doesn't check the validity of array
  3235.  subscripts. If the ARRAY.C program included the expression
  3236.  
  3237.    i_array[55];
  3238.  
  3239.  it would refer to a nonexistent array element. (The expression refers to the
  3240.  element 55, but  i_array  contains only three elements.) This would not
  3241.  trigger a compiler error or run-time error, however. It's your job to
  3242.  remember the size of the array and avoid references that go outside the
  3243.  array's boundaries. This rule is also important when you're accessing arrays
  3244.  with pointers (see Chapter 8, "Pointers").
  3245.  
  3246.  
  3247.  Strings
  3248.  
  3249.   A string is an array  of characters.
  3250.  
  3251.  You may have wondered why we didn't mention strings in our earlier
  3252.  description of basic data types. The reason is that strings aren't a formal
  3253.  data type. In the C language, a string is simply an array of characters
  3254.  (char values).
  3255.  
  3256.  The STRING.C program below creates the string  c_array  and displays its
  3257.  contents in the same format as the previous example. The program prints the
  3258.  value of each array element and its address.
  3259.  
  3260.    /* STRING.C: Demonstrate string arrays. */
  3261.  
  3262.    #include <stdio.h>
  3263.  
  3264.    main()
  3265.    {
  3266.       int j;
  3267.       char c_array[] = "Hello";
  3268.  
  3269.       printf( "--- Values --------     --- Addresses -------\n\n" );
  3270.  
  3271.       for( j = 0; j < 6; j = j + 1 )
  3272.       {
  3273.          printf( "c_array[%d]   = %x %c", j, c_array[j], c_array[j] );
  3274.          printf( "\t&c_array[%d]    = %u\n", j, &c_array[j] );
  3275.       }
  3276.    }
  3277.  
  3278.  Here is the output from STRING.C:
  3279.  
  3280.    --- Values --------     --- Addresses -------
  3281.  
  3282.    c_array[0]   = 48 H     &c_array[0]    = 3522
  3283.    c_array[1]   = 65 e     &c_array[1]    = 3523
  3284.    c_array[2]   = 6c l     &c_array[2]    = 3524
  3285.    c_array[3]   = 6c l     &c_array[3]    = 3525
  3286.    c_array[4]   = 6f o     &c_array[4]    = 3526
  3287.    c_array[5]   = 0        &c_array[5]    = 3527
  3288.  
  3289.  Figure 4.3 shows how  c_array  is stored in memory. Again, the addresses in
  3290.  the output may differ depending on factors such as the amount of available
  3291.  memory.
  3292.  
  3293.  (This figure may be found in the printed book.)
  3294.  
  3295.   A string ends with  a null character.
  3296.  
  3297.  The figure illustrates another important feature of strings. Although
  3298.  c_array  has five printing characters ( Hello ), it actually contains six
  3299.  characters─five letters plus a null character (\0) that marks the end of the
  3300.  string. As noted earlier, the C language automatically adds a null character
  3301.  to every string enclosed in double quotes.
  3302.  
  3303.  STRING.C uses a shortcut when it initializes  c_array. You may have noticed
  3304.  that the array declaration
  3305.  
  3306.    char c_array[] = "Hello";
  3307.  
  3308.  doesn't declare the array's size (the square brackets are empty). When an
  3309.  array is initialized at the same time it's declared, QuickC can figure out
  3310.  how many elements the array has by counting the number of initializing
  3311.  values to the right of the equal sign.
  3312.  
  3313.  You can use this shortcut for any type of array, not just a char array. If
  3314.  the array has more than one dimension, however, you can only omit the size
  3315.  of the first dimension.
  3316.  
  3317.  
  3318.  Multidimensional Arrays
  3319.  
  3320.  A "multidimensional" array contains two or more array dimensions. The
  3321.  TWODIM.C program below creates a two-dimensional array named  i_array.
  3322.  
  3323.    /* TWODIM.C: Demonstrate multidimensional arrays. */
  3324.  
  3325.    #include <stdio.h>
  3326.  
  3327.    main()
  3328.    {
  3329.       int j, k;
  3330.       int i_array[2][3] = { { 176, 4069, 303 }, { 6, 55, 777 } };
  3331.  
  3332.       printf( "--- Values --------     --- Addresses -------\n\n" );
  3333.  
  3334.       for( j = 0; j < 2; j = j + 1 )
  3335.       {
  3336.          for( k = 0; k < 3; k = k + 1 )
  3337.          {
  3338.             printf( "i_array[%d][%d] = %d", j, k, i_array[j][k] );
  3339.             printf( "\t&i_array[%d][%d] = %u\n", j, k, &i_array[j][k] );
  3340.          }
  3341.          printf( "\n" );
  3342.       }
  3343.  
  3344.    }
  3345.  
  3346.  Here's the output from TWODIM.C:
  3347.  
  3348.    --- Values --------     --- Addresses -------
  3349.  
  3350.    i_array[0][0] = 176     &i_array[0][0] = 3498
  3351.    i_array[0][1] = 4069    &i_array[0][1] = 3500
  3352.    i_array[0][2] = 303     &i_array[0][2] = 3502
  3353.  
  3354.    i_array[1][0] = 6       &i_array[1][0] = 3504
  3355.    i_array[1][1] = 55      &i_array[1][1] = 3506
  3356.    i_array[1][2] = 777     &i_array[1][2] = 3508
  3357.  
  3358.  Each subscript of a multidimensional array appears in its own set of square
  3359.  brackets, as the TWODIM.C output shows. When you declare the array, the
  3360.  first subscript states the size of the first dimension, the second states
  3361.  the size of the second dimension, and so on. In TWODIM.C, the declaration of
  3362.   i_array,
  3363.  
  3364.    int i_array[2][3]
  3365.  
  3366.  states that  i_array  contains two rows of values, each row containing three
  3367.  integers. The statement that declares  i_array  also initializes the array,
  3368.  listing the initializing values in curly braces to the right of the equal
  3369.  sign:
  3370.  
  3371.    int i_array[2][3] = { { 176, 4069, 303 }, { 6, 5, 77 } };
  3372.  
  3373.  The braces clearly show that the array contains two groups of three values.
  3374.  
  3375.  
  3376.  Two-dimensional arrays are often pictured in rows and columns, as in Figure
  3377.  4.4. Of course, since computer memory is linear,  i_array  is actually
  3378.  stored with its rows end-for-end, as in Figure 4.5.
  3379.  
  3380.  (This figure may be found in the printed book.)
  3381.  
  3382.  You refer to a multidimensional array element the same way you would a
  3383.  onedimensional array element, except that you use one subscript for each
  3384.  dimension of the array. For instance, the statement
  3385.  
  3386.    printf( "%d\n", i_array[0][1] );
  3387.  
  3388.  specifies two subscripts. It prints the value stored in element 0, 1 of
  3389.  i_array, which is  4069.
  3390.  
  3391.  Figure 4.5 shows how to specify every element of  i_array  in TWODIM.C.
  3392.  
  3393.  (This figure may be found in the printed book.)
  3394.  
  3395.  
  3396.  Structures
  3397.  
  3398.   A structure is a group of related data items of different  types under one
  3399.  name.
  3400.  
  3401.  The second aggregate data type is the structure: a group of related data
  3402.  items under one name. While array elements are all the same type, the
  3403.  elements of a structure, known as its "members," can be of different types.
  3404.  
  3405.  
  3406.  Structures are equivalent to records in QuickPascal or user-defined types in
  3407.  QuickBASIC. As in those languages, the ability to group different types in
  3408.  the same construct provides powerful, very flexible data-handling
  3409.  capabilities.
  3410.  
  3411.  
  3412.  Creating a Simple Structure
  3413.  
  3414.  We'll write a simple program to demonstrate the basics of structures.
  3415.  Suppose you want to write a payroll program that records these facts about
  3416.  an employee:
  3417.  
  3418.  
  3419.    ■   Name
  3420.  
  3421.    ■   Number of months of service
  3422.  
  3423.    ■   Hourly wage
  3424.  
  3425.  
  3426.  Each of these data items requires a different data type. The name can be
  3427.  stored in a string (character array), while an integer will do for the
  3428.  months of service. The hourly wage may contain a fraction; we'll store it in
  3429.  a floating-point variable.
  3430.  
  3431.  Although each of these variables has a different type, we can group all of
  3432.  them in a single structure. The EMPLOYEE.C program below contains the
  3433.  structure.
  3434.  
  3435.    /* EMPLOYEE.C: Demonstrate structures. */
  3436.  
  3437.    #include <stdio.h>
  3438.    #include <string.h>
  3439.  
  3440.    struct employee
  3441.    {
  3442.       char name[10];
  3443.       int months;
  3444.       float wage;
  3445.    };
  3446.  
  3447.    void display( struct employee show );
  3448.  
  3449.    main()
  3450.    {
  3451.       struct employee jones;
  3452.  
  3453.       strcpy( jones.name, "Jones, J" );
  3454.       jones.months = 77;
  3455.       jones.wage = 13.68;
  3456.  
  3457.       display( jones );
  3458.    }
  3459.  
  3460.    void display( struct employee show )
  3461.    {
  3462.       printf( "Name: %s\n", show.name );
  3463.       printf( "Months of service: %d\n", show.months );
  3464.       printf( "Hourly wage: %6.2f\n", show.wage );
  3465.    }
  3466.  
  3467.  Here is the output of the EMPLOYEE.C program:
  3468.  
  3469.    Name: Jones, J
  3470.    Months of service: 77
  3471.    Hourly wage:  13.68
  3472.  
  3473.  
  3474.  Declaring a Structure Type
  3475.  
  3476.  Since a structure can (and normally does) contain different data types,
  3477.  creating it is a little more complicated than making an array or simple
  3478.  variable. Before you can create a structure variable, you must declare a
  3479.  structure type that tells the compiler how many members the structure
  3480.  contains and what types they are.
  3481.  
  3482.  A structure-type declaration starts with the keyword struct, which is
  3483.  followed by a list of the structure's members enclosed in braces. Between
  3484.  the struct and the list of members, you can also specify a "structure tag"─a
  3485.  name that other parts of the program can use to refer to the type.
  3486.  
  3487.  The structure declaration from EMPLOYEE.C,
  3488.  
  3489.    struct employee
  3490.    {
  3491.       char name[10];
  3492.       int months;
  3493.       float wage;
  3494.    };
  3495.  
  3496.   A structure declaration makes a template for variables  of the type it
  3497.  defines.
  3498.  
  3499.  creates a "template" for an  employee  structure that structure variables of
  3500.  this type can use. It's as if you created a brand new data type, tagging it
  3501.  employee. Figure 4.6 illustrates the  employee  structure type.
  3502.  
  3503.  (This figure may be found in the printed book.)
  3504.  
  3505.  
  3506.  Creating a Structure Variable
  3507.  
  3508.  Once you have declared a structure, you can create variables of that type
  3509.  using the structure tag. Each variable can contain values of the types
  3510.  defined in the structure type. In EMPLOYEE.C, the statement
  3511.  
  3512.    struct employee jones;
  3513.  
  3514.  declares a structure variable of the type  employee  named  jones. The
  3515.  struct states that the variable is a structure. The  employee  tag specifies
  3516.  the variable's structure type, and  jones  is the variable's name.
  3517.  
  3518.  You can also declare the variable in the same statement that declares the
  3519.  structure type. The following code declares the  employee  structure type
  3520.  and a variable of that type named  jones:
  3521.  
  3522.    struct employee
  3523.    {
  3524.       char name[10];
  3525.       int months;
  3526.       float wage;
  3527.    } jones;
  3528.  
  3529.  The variable name ( jones ) appears at the end of the declaration.
  3530.  
  3531.   Use the member-of operator (.) to specify structure members.
  3532.  
  3533.  You specify structure members by name, using the "member-of" operator (.) to
  3534.  separate the variable name and the member name. These are the names of the
  3535.  members of the  jones  structure variable in EMPLOYEE.C:
  3536.  
  3537.    jones.name
  3538.    jones.months
  3539.    jones.wage
  3540.  
  3541.  Like other variables, structure variables should be initialized before use.
  3542.  After  jones  is declared in EMPLOYEE.C, the statements
  3543.  
  3544.    strcpy( jones.name, "Jones, J" );
  3545.    jones.months = 77;
  3546.    jones.wage = 13.68;
  3547.  
  3548.  initialize the members of the  jones  variable. The first statement
  3549.  initializes the  jones.name  member by calling the strcpy ("string copy")
  3550.  library function; this function is described in Chapter 11, "Input and
  3551.  Output."
  3552.  
  3553.  Figure 4.7 shows how the  jones  structure is stored in memory. Again, since
  3554.  computer memory is linear, the members of the structure are laid out
  3555.  end-to-end.
  3556.  
  3557.  (This figure may be found in the printed book.)
  3558.  
  3559.  You can initialize a structure when you declare it. The following code would
  3560.  perform both operations in EMPLOYEE.C:
  3561.  
  3562.    struct employee jones =
  3563.    {
  3564.       "Jones, J",
  3565.       77,
  3566.       13.68
  3567.    };
  3568.  
  3569.  This code declares the  jones  structure variable and lists the initializing
  3570.  value for each of its members.
  3571.  
  3572.  
  3573.  Using Structure Variables
  3574.  
  3575.  A structure member can be treated like any other variable of its type. You
  3576.  can assign a value to it, change its value, and so on. For instance, the
  3577.  statement
  3578.  
  3579.    jones.months = 83;
  3580.  
  3581.  would change the value of the  jones.months  member in EMPLOYEE.C.
  3582.  
  3583.   Assigning one structure  to another copies  the entire structure.
  3584.  
  3585.  You can also assign an entire structure to another structure of the same
  3586.  type. This copies the entire contents of the first structure to the second.
  3587.  You might do this to save time when creating a new structure whose contents
  3588.  differ only slightly from those of an existing structure.
  3589.  
  3590.  To illustrate, let's modify the EMPLOYEE.C program. Say you have a second
  3591.  employee named Lavik whose wage rate and months of service are the same as
  3592.  those of Jones and you want to create a second structure. You could begin by
  3593.  declaring a second  employee  structure variable named  lavik  in this
  3594.  fashion:
  3595.  
  3596.    struct employee lavik = jones;
  3597.  
  3598.  Now the members of the  lavik  structure contain the same data as the
  3599.  members of the  jones  structure. The  lavik.name  member contains the
  3600.  string  Jones, J, the  lavik.months  member contains the value 77, and the
  3601.  lavik.wage  member contains the value 13.68. You could add the statement
  3602.  
  3603.    strcpy( lavik.name, "Lavik, B" );
  3604.  
  3605.  to place a new string in the  lavik.name  member.
  3606.  
  3607.   Structure variables can be passed as function arguments.
  3608.  
  3609.  When you pass a structure name to a function, the function creates a local
  3610.  structure variable of that type. Like all local variables, the new variable
  3611.  is private to the function that includes it.
  3612.  
  3613.  For example, if you add the statements
  3614.  
  3615.    strcpy( show.name, "King, M" );
  3616.    printf( "%s\n", show.name );
  3617.  
  3618.  to the end of the  display  function in EMPLOYEE.C, then a new string is
  3619.  copied into the  show.name  member of the function's structure variable. The
  3620.  printf statement in the second line prints
  3621.  
  3622.    King, M
  3623.  
  3624.  Since this structure is local to the  display  function, the change doesn't
  3625.  affect the structure defined in the main function. If you add the statement
  3626.  
  3627.  
  3628.    printf( "%s\n", jones.name );
  3629.  
  3630.  to the end of the main function, the program prints
  3631.  
  3632.    Jones, J
  3633.  
  3634.  The original structure is unchanged.
  3635.  
  3636.  While you can pass a structure name to a function as we did above, it's more
  3637.  common to pass the function a pointer to the structure. This not only
  3638.  permits the function to access a structure defined elsewhere in the program,
  3639.  but it conserves memory (since the function doesn't create a local copy of
  3640.  the structure). Chapter 9, "Advanced Pointers," explains how to access
  3641.  structures using pointers.
  3642.  
  3643.  
  3644.  Arrays of Structures
  3645.  
  3646.   An array of structures  is a group of structures  of the same type.
  3647.  
  3648.  Since it's rare for a company to have a single employee, a more practical
  3649.  version of the EMPLOYEE.C program would have an array of structures─one
  3650.  structure per employee. The concept may sound intimidating, but this is a
  3651.  common use of structures.
  3652.  
  3653.  The following statement declares a 50-element array named  payroll, with
  3654.  each element a structure of the type  employee :
  3655.  
  3656.    struct employee payroll[50];
  3657.  
  3658.  To specify members in such an array, you combine array notation and
  3659.  structure notation, giving the array name, a subscript, and a member name.
  3660.  For instance, the name
  3661.  
  3662.    payroll[0].months
  3663.  
  3664.  specifies the  months  member of the first structure in the  payroll  array.
  3665.  The first part of the name ( payroll[0] ) contains the array name and
  3666.  subscript that identify the structure. The second part ( months ) identifies
  3667.  the member within that structure.
  3668.  
  3669.  Figure 4.8 depicts the first three elements of the  payroll  array.
  3670.  
  3671.  (This figure may be found in the printed book.)
  3672.  
  3673.  Once you grasp the basic idea, it's easy to imagine practical uses for an
  3674.  array of structures. Many programs, from an address book to a library card
  3675.  catalog, might use a structure to store different types of information about
  3676.  an individual item, then store many such structures in an array.
  3677.  
  3678.  
  3679.  Structures of Structures
  3680.  
  3681.  As noted earlier, a structure can contain members of any data type─including
  3682.  other structures. So you can create a structure of structures: a structure
  3683.  whose members are structures.
  3684.  
  3685.  To illustrate, suppose you write a group of functions that draw various
  3686.  kinds of graphic windows and message boxes. You could define a small
  3687.  structure something like the following:
  3688.  
  3689.    struct title
  3690.    {
  3691.       char text[70];  /* Title text */
  3692.       int color;      /* Color of title text */
  3693.       short justify;  /* Left, center, or right */
  3694.    };
  3695.  
  3696.  to aid in drawing titles. The  title  structure's three members specify the
  3697.  title's text, its color, and how its text is justified.
  3698.  
  3699.  Once the  title  structure is defined, you can make it part of other, larger
  3700.  structures that use titles. If you define a  window  structure type to draw
  3701.  windows, for example, that structure could include a  title  along with
  3702.  other structure members:
  3703.  
  3704.    struct window
  3705.    {
  3706.       struct title wintitle; /* Window title */
  3707.       /* Other structure members go here... */
  3708.    };
  3709.  
  3710.  In this structure type, the  title  member is named  wintitle.
  3711.  
  3712.  You specify members of such structures using member-of operators and  the
  3713.  appropriate names. If you create a variable of the  window  type named
  3714.  mywindow, the name
  3715.  
  3716.    mywindow.wintitle.color
  3717.  
  3718.  specifies the  color  member of the  wintitle  member of the  mywindow
  3719.  structure.
  3720.  
  3721.  If you program using QuickC's Presentation Graphics library, you'll find it
  3722.  useful to understand the notation we just explained. Our fictitious  title
  3723.  structure is a simplified version of the Presentation Graphics titletype
  3724.  structure type (see Chapter 14, "Presentation Graphics").
  3725.  
  3726.  
  3727.  Bit Fields
  3728.  
  3729.  A "bit field" is a specialized structure that provides a way to manipulate
  3730.  individual bits or groups of bits. One use for this advanced feature is to
  3731.  access hardware addresses such as the computer's video memory.
  3732.  
  3733.   The members of a bit-field structure are groups of bits.
  3734.  
  3735.  You declare and use a bit-field structure much as you would any other
  3736.  structure. The difference is that every one of its members must be a bit or
  3737.  group of bits. You can't include other data types in a bit field.
  3738.  
  3739.  The following statement declares a bit-field structure type with the tag
  3740.  SCREEN:
  3741.  
  3742.    struct SCREEN
  3743.    {
  3744.      unsigned character : 8;
  3745.      unsigned fgcolor   : 3;
  3746.      unsigned intensity : 1;
  3747.      unsigned bgcolor   : 3;
  3748.      unsigned blink     : 1;
  3749.    } screenbuf[25][80];
  3750.  
  3751.  The colons in the declaration tell QuickC these are bit fields rather than
  3752.  normal structure members. The number following each colon tells how many
  3753.  bits the field contains. In the  SCREEN  type the  character  member has 8
  3754.  bits, intensity  has 1 bit, and so on. Figure 4.9 illustrates the  SCREEN
  3755.  type.
  3756.  
  3757.  (This figure may be found in the printed book.)
  3758.  
  3759.  Figure 4.10 illustrates memory allocation for the  SCREEN  type. The members
  3760.  of the  SCREEN  type mirror the arrangement of bits in screen memory.
  3761.  
  3762.  (This figure may be found in the printed book.)
  3763.  
  3764.  Take another look at the structure declaration. In addition to declaring a
  3765.  structure type, the statement declares a two-dimensional array variable
  3766.  screenbuf, of the same structure type. You could use this array as an
  3767.  alternate video buffer. Many graphics programs use a similar arrangement to
  3768.  switch between an alternate video buffer and the computer's video memory.
  3769.  
  3770.  The five members of the  SCREEN  type happen to take up a full int (two
  3771.  bytes, on DOS machines). A bit field need not fill up a byte or int; the bit
  3772.  field can contain as many bits as you need up to the maximum number of bits
  3773.  for the field's
  3774.  
  3775.  base type. The base type for each field in the example is unsigned (unsigned
  3776.  int), so each field can contain a maximum of 16 bits.
  3777.  
  3778.  The members of a bit-field structure are accessed with the structure-member
  3779.  operator─like other structure members. For instance, the name
  3780.  
  3781.    screenbuf[13][53].blink = 1;
  3782.  
  3783.  specifies the  blink  member of element 13, 53 of the  screenbuf  array.
  3784.  
  3785.  The range of values you can assign to a bit-field member depends on the
  3786.  member's size. Since the  blink  member of the  SCREEN  type contains one
  3787.  bit,  blink  is limited to the value 0 or 1. The  fgcolor  member contains
  3788.  three bits and can have any value from 0-7.
  3789.  
  3790.  
  3791.  Unions
  3792.  
  3793.   A union is a group of  variables of different types  that share storage
  3794.  space.
  3795.  
  3796.  A union is a variable that can hold any one of several data types at
  3797.  different times, using the same storage space. Unions are a rather advanced
  3798.  feature. One use of them is to access DOS registers, which you may sometimes
  3799.  need to access as bytes and at other times as words.
  3800.  
  3801.  As with a structure, you must start by declaring a union type to tell the
  3802.  compiler the number and types of the union's members. You include one of
  3803.  each type that you expect to use.
  3804.  
  3805.  The following code creates a union that can hold a char, int, or long value.
  3806.  It declares a union type with the tag  u_sample  and declares a variable of
  3807.  that type named  example.
  3808.  
  3809.    union u_sample
  3810.    {
  3811.      char c_val;
  3812.      int i_val;
  3813.      long l_val;
  3814.    }  example;
  3815.  
  3816.  When you declare a union, QuickC allocates as much storage as the largest
  3817.  data type in the union requires. Since the largest type in  u_sample  is
  3818.  long, this union contains four bytes.
  3819.  
  3820.  The elements of a union are called members and use the same notation as
  3821.  structure members. Thus, the members of the  example  union are named
  3822.  
  3823.    example.c_val
  3824.    example.i_val
  3825.    example.l_val
  3826.  
  3827.  The contents of a union depend on how you access it. For instance, the
  3828.  statement
  3829.  
  3830.    example.c_val = '\0';
  3831.  
  3832.  stores a char value in the  example  union. Since a char value takes one
  3833.  byte, the statement uses only one byte of the space in  example. The
  3834.  statement
  3835.  
  3836.    example.i_val = 77;
  3837.  
  3838.  uses two bytes of the union, because an int value requires two bytes of
  3839.  storage. Likewise, the statement
  3840.  
  3841.    example.l_val = 75621;
  3842.  
  3843.  stores long value in  example, taking up all four bytes of its storage
  3844.  space. Figure 4.11 shows memory allocation for the three members in the
  3845.  example  union.
  3846.  
  3847.  (This figure may be found in the printed book.)
  3848.  
  3849.  It's your job to keep track of what is stored in a union. If you store a
  3850.  long value in  example  and mistakenly treat that value as a char value
  3851.  later, the result may be nonsense. It's especially important not to confuse
  3852.  integer and floating-point types, which are stored in different internal
  3853.  formats.
  3854.  
  3855.  Now that you're familiar with the data types that C offers, you are ready to
  3856.  tackle more advanced data-handling concepts. The next chapter discusses
  3857.  several of these.
  3858.  
  3859.  
  3860.  
  3861.  
  3862.  
  3863.  
  3864.  Chapter 5  Advanced Data Types
  3865.  ────────────────────────────────────────────────────────────────────────────
  3866.  
  3867.  In Chapter 4, "Data Types," we described the basic C data types and showed
  3868.  how to declare and use different kinds of variables. This chapter examines
  3869.  more advanced data topics, including the visibility and lifetime of
  3870.  variables and the conversion of values from one data type to another.
  3871.  
  3872.  If you know QuickPascal or QuickBASIC, some of these topics, such as
  3873.  visibility, should be familiar. For example, a variable declared within a
  3874.  function is visible (accessible) only in that function. One area in which C
  3875.  differs notably from QuickPascal is type conversion. The C language gives
  3876.  programmers the freedom to convert a value from one type to another type,
  3877.  whereas QuickPascal does not.
  3878.  
  3879.  
  3880.  Visibility
  3881.  
  3882.  Every variable in a C program has a definite "visibility" that determines
  3883.  which parts of the program can "see," or access, the variable. Another term
  3884.  for visibility is "scope."
  3885.  
  3886.  As we mentioned in Chapter 1, "Anatomy of a C Program," there are two basic
  3887.  kinds of visibility: local and external. A "local" variable─one declared
  3888.  within a function─is visible only within that function. An "external"
  3889.  variable─one declared outside all functions─is visible to all functions that
  3890.  follow it in the program.
  3891.  
  3892.  This section begins by describing local and external visibility, then goes
  3893.  on to discuss visibility in multiple-file programs and the visibility of
  3894.  functions.
  3895.  
  3896.  ────────────────────────────────────────────────────────────────────────────
  3897.  NOTE
  3898.  
  3899.  While the examples in this section use simple int variables, visibility
  3900.  rules apply equally to aggregate types such as arrays and structures.
  3901.  ────────────────────────────────────────────────────────────────────────────
  3902.  
  3903.   Use external variables  only when necessary.
  3904.  
  3905.  C programmers normally limit the visibility of each variable to those parts
  3906.  of the program that need to access the variable. For instance, if a variable
  3907.  is needed only within one function, it should always be local to that
  3908.  function. By restricting a variable's visibility, you can prevent other
  3909.  parts of the program from accidentally changing the variable's value. Such
  3910.  haphazard side effects were common in older interpreted BASIC programs, in
  3911.  which every variable had unlimited  visibility.
  3912.  
  3913.  
  3914.  Local Variables
  3915.  
  3916.   Variables declared  within a function are  local to that function.
  3917.  
  3918.  As we noted in Chapter 1, "Anatomy of a C Program," and Chapter 2,
  3919.  "Functions," the place where you declare a variable controls where the
  3920.  variable is visible. Declaring a variable within a function makes the
  3921.  variable local to that function; the variable can be seen only within the
  3922.  function.
  3923.  
  3924.  The VISIBLE.C program below demonstrates local visibility. It contains a
  3925.  function named  be_bop  that tries to print the value of the local variable
  3926.  val.
  3927.  
  3928.    /* VISIBLE.C: Demonstrate local visibility. */
  3929.  
  3930.    #include <stdio.h>
  3931.    void be_bop( void );
  3932.  
  3933.    main()
  3934.    {
  3935.       int val = 10;
  3936.       be_bop();
  3937.    }
  3938.  
  3939.    void be_bop( void )
  3940.    {
  3941.       printf( "val = %d", val ); /* Error! */
  3942.    }
  3943.  
  3944.  Notice where the  val  variable is declared. The declaration
  3945.  
  3946.    int val = 10;
  3947.  
  3948.  occurs within the main function, so  val  is local to main. When you compile
  3949.  VISIBLE.C, QuickC stops, providing this error message:
  3950.  
  3951.    C2065: 'val' : undefined
  3952.  
  3953.  What happened? The printf statement in the  be_bop  function
  3954.  
  3955.    printf( "val = %d", val ); /* Error! */
  3956.  
  3957.  can't "see" the variable  val, which is declared locally within main.
  3958.  Outside the main function, in which  val  is declared, the variable doesn't
  3959.  exist.
  3960.  
  3961.  You could eliminate the error message by declaring  val  externally, but
  3962.  most programmers would avoid that solution. If a variable has external
  3963.  visibility, any part of the program might change its value accidentally. A
  3964.  better solution is to pass the value of  val  to  be_bop  as a function
  3965.  argument, as shown in the program VISIBLE1.C below.
  3966.  
  3967.    /* VISIBLE1.C: Demonstrate local visibility. */
  3968.  
  3969.    #include <stdio.h>
  3970.  
  3971.    void be_bop( int param );
  3972.  
  3973.    main()
  3974.    {
  3975.       int val = 10;
  3976.       be_bop( val );
  3977.    }
  3978.  
  3979.    void be_bop( int param )
  3980.    {
  3981.       printf( "%d\n", param );
  3982.    }
  3983.  
  3984.  The VISIBLE1.C program is identical to VISIBLE.C except for two changes. The
  3985.   be_bop  function now can accept an argument, and the statement that calls
  3986.  be_bop  passes the value of  val  as an argument. These changes allow the
  3987.  be_bop  function to print the value of  val  without the drawback of making
  3988.  val  external.
  3989.  
  3990.  Most local variables are declared at the beginning of the function and are
  3991.  visible throughout the function. If you declare the variable later in the
  3992.  function, it is visible only to statements that follow the declaration.
  3993.  
  3994.  The reason for this rule is simple: QuickC, like all language compilers,
  3995.  reads your program line by line, from beginning to end. Until the compiler
  3996.  sees the variable's declaration, it must treat the variable as undefined.
  3997.  This rule applies to all variables, including external variables, as we'll
  3998.  see in the next section.
  3999.  
  4000.  Although the practice isn't common, you can restrict a local variable's
  4001.  visibility even further by declaring it in a statement block inside a
  4002.  function. For instance, you might declare a variable within the body of the
  4003.  loop or conditional statement. In fact, any pair of curly braces limits the
  4004.  visibility of a variable declared within that pair.
  4005.  
  4006.  
  4007.  External Variables
  4008.  
  4009.  If you declare a variable outside all functions, the variable has external
  4010.  visibility; every function that follows the declaration can see the
  4011.  variable. External variables are called "global" in some other languages.
  4012.  
  4013.  Experienced C programmers use external variables only when necessary─for
  4014.  instance, when two or more functions need the ability to change the same
  4015.  variable or communicate with each other by changing a variable. Even in
  4016.  those cases, however, you may be able to avoid the dangers of external
  4017.  visibility by passing a pointer to the variable as a function argument. See
  4018.  the section "Passing Pointers to Functions" in Chapter 8 ("Pointers") for
  4019.  more information.
  4020.  
  4021.  Most external variables are declared near the beginning of the program,
  4022.  before any function definitions. In this way, you can make the variable
  4023.  visible to every function in the program. You could do this in VISIBLE1.C by
  4024.  placing the declaration of  val,
  4025.  
  4026.    int val = 10;
  4027.  
  4028.  immediately before the main function.
  4029.  
  4030.  If you declare the variable  val  later in the program, it is not visible to
  4031.  functions that precede the declaration. The VISIBLE2.C program below
  4032.  demonstrates this principle.
  4033.  
  4034.    /* VISIBLE2.C: Demonstrate external visibility. */
  4035.  
  4036.    #include <stdio.h>
  4037.  
  4038.    void be_bop( int param );
  4039.  
  4040.    main()
  4041.    {
  4042.       be_bop( val ); /* Error! */
  4043.    }
  4044.  
  4045.    int val = 10;
  4046.  
  4047.    void be_bop( int param )
  4048.    {
  4049.       printf( "val = %d\n", param );
  4050.    }
  4051.  
  4052.  The VISIBLE2.C program is identical to VISIBLE1.C except that  val  is
  4053.  declared externally
  4054.  
  4055.    int val = 10;
  4056.  
  4057.  following the main function, rather than locally within main.
  4058.  
  4059.  Because the declaration occurs outside all functions, the variable is
  4060.  external. However, because the declaration follows the main function, the
  4061.  variable is not visible within main. When the printf statement in the main
  4062.  function refers to  val, QuickC issues the error message:
  4063.  
  4064.    C2065: 'val' : undefined
  4065.  
  4066.  Remember, QuickC reads the program line by line, from start to finish. Since
  4067.  the compiler knows nothing about  val  when it reaches the reference in
  4068.  main, it must treat  val  as undefined. In this program, only the  be_bop
  4069.  function can refer to  val.
  4070.  
  4071.  
  4072.  Visibility in Multiple Source Files
  4073.  
  4074.  A "source file" is the file containing your program's text. Source files
  4075.  normally have the .C file extension, to distinguish them from other files
  4076.  such as executable (.EXE) files.
  4077.  
  4078.  Simple programs have only one source file, but large programs are often
  4079.  split into several source files. If you write a word-processing program, for
  4080.  instance, you might place all the program's screen-output functions in one
  4081.  file, all the file-handling functions in a second file, and so forth.
  4082.  
  4083.   Use the extern keyword to make an external variable visible in more than
  4084.  one source file.
  4085.  
  4086.  Normally, an external variable is visible only in the source file in which
  4087.  it is declared. In a multi-file program, however, a function in one file
  4088.  might need to access a variable in a second file. To make the variable
  4089.  visible in more than one source file, you must declare it with the extern
  4090.  keyword.
  4091.  
  4092.  Let's look at a short two-file program that shows how to use extern. The
  4093.  first source file, FILE1.C, declares two external variables,  chico  and
  4094.  harpo. The file contains one function (main) that calls a second function
  4095.  named  yonder.
  4096.  
  4097.    /* FILE1.C: Visibility in multiple source files. */
  4098.  
  4099.    int chico = 20, harpo = 30;
  4100.    extern void yonder( void );
  4101.  
  4102.    main()
  4103.    {
  4104.       yonder();
  4105.    }
  4106.  
  4107.  The second source file, FILE2.C, contains the  yonder  function that is
  4108.  called in FILE1.C. This file also declares the variables  chico  and  harpo,
  4109.   but it prefaces their declarations with extern to show that the variables
  4110.  are defined externally in some other file. Once this is done, any function
  4111.  in FILE2.C can refer to  chico  and  harpo  as if they are defined in the
  4112.  same file.
  4113.  
  4114.    /* FILE2.C: Visibility in multiple source files. */
  4115.  
  4116.    #include <stdio.h>
  4117.  
  4118.    void yonder( void )
  4119.    {
  4120.       extern int chico, harpo;
  4121.       printf( "chico = %d, harpo = %d\n", chico, harpo );
  4122.    }
  4123.  
  4124.  You can compile this program in one of two ways. In the QuickC environment,
  4125.  choose Set Program List from the Make menu and add FILE1.C and FILE2.C to
  4126.  the list. Then choose Build Program from the Make menu.
  4127.  
  4128.  You can also enter this command from the DOS command line:
  4129.  
  4130.    qcl FILE1.C FILE2.C
  4131.  
  4132.  In either case, the executable file is named FILE1.EXE. The program's
  4133.  output,
  4134.  
  4135.    chico = 20, harpo = 30
  4136.  
  4137.  shows that the  yonder  function in FILE2.C can access the variables defined
  4138.  in FILE1.C.
  4139.  
  4140.  Sometimes you may want an external variable to be visible only in the source
  4141.  file where it's declared. The variable can be shared by functions in one
  4142.  file, but it is hidden to all other files, thus minimizing the risk of
  4143.  naming conflicts.
  4144.  
  4145.   The static keyword  can limit a variable's visibility to one source file.
  4146.  
  4147.  To limit a variable's visibility to one file, precede the variable's
  4148.  declaration with the keyword static. For example, if FILE1.C declared the
  4149.  harpo  variable as static in this manner,
  4150.  
  4151.    static int harpo;
  4152.  
  4153.  it would prevent FILE2.C from accessing  harpo  at all, even though FILE2.C
  4154.  declares (with extern) that  harpo  is defined somewhere else.
  4155.  
  4156.  
  4157.  Visibility of Functions
  4158.  
  4159.   Functions are normally visible in multiple source files.
  4160.  
  4161.  Unlike variables, functions are external by default. That is, they are
  4162.  normally visible to every file in a multi-file program. You'll notice that
  4163.  in FILE1.C we declared the  yonder  function with the extern keyword. We did
  4164.  this merely to improve readability; the keyword shows clearly that the
  4165.  function is defined in some other file. If we removed the extern from the
  4166.  declaration of  yonder  in FILE1.C, the program would work just as well as
  4167.  before.
  4168.  
  4169.  At times you may want to restrict the visibility of a function in a
  4170.  multi-file program, making it visible in some files but not in others. By
  4171.  "hiding" a function from other parts of a program, you can reduce the danger
  4172.  of naming conflicts. For instance, if you write a library of functions to
  4173.  sell commercially, you probably would hide all of the library's local
  4174.  function names, to prevent conflicts with function names your customers
  4175.  might create.
  4176.  
  4177.   The static keyword can  limit a function's visibility.
  4178.  
  4179.  As with external variables, you limit a function's visibility using the
  4180.  static keyword. A function declared as static is visible only in the source
  4181.  file that declares it. If we add static to the header of the  yonder
  4182.  function, for example,
  4183.  
  4184.    static void yonder( void )
  4185.  
  4186.  the function could no longer be called from the FILE1.C file.
  4187.  
  4188.  
  4189.  Lifetime
  4190.  
  4191.  In addition to visibility, every variable also has a certain "lifetime"─that
  4192.  is, the period during the program's execution when the variable exists.
  4193.  
  4194.  External variables exist for the life of the program. Memory is allocated
  4195.  for them when the program begins and remains until the program ends.
  4196.  
  4197.   An automatic variable  disappears when the function ends.
  4198.  
  4199.  Local variables have shorter lifetimes. They come into being when the
  4200.  function begins and disappear when the function ends. For this reason, a
  4201.  local variable is said to be "automatic." The variable comes and goes
  4202.  automatically, each time the function is called.
  4203.  
  4204.  Automatic variables conserve memory in a couple of ways. First, since they
  4205.  evaporate when the function ends, automatic variables don't consume memory
  4206.  when not in use. Second, they are stored in the "stack" memory area, which
  4207.  the program allocates at run time. So, automatic variables don't enlarge the
  4208.  executable program.
  4209.  
  4210.  The C language provides the auto keyword for declaring automatic variables.
  4211.  However, this keyword is seldom used, since all local variables are
  4212.  automatic unless you specify otherwise. In the following function, both  val
  4213.   and  example  are automatic variables:
  4214.  
  4215.    void sample( void )
  4216.    {
  4217.       int val;
  4218.       auto int example;
  4219.    }
  4220.  
  4221.  The auto preceding the declaration of  example  has no practical effect. The
  4222.  variable  example  is automatic even if you remove the auto from its
  4223.  declaration.
  4224.  
  4225.  
  4226.  Extending the Lives of Local Variables
  4227.  
  4228.  Occasionally, you may want a local variable to retain its value between
  4229.  function calls. The static keyword, introduced earlier as a means of
  4230.  limiting the visibility of external variables, also performs this task.
  4231.  
  4232.   A static local variable  retains its value through  subsequent function
  4233.  calls.
  4234.  
  4235.  If you precede a local variable declaration with static, the variable exists
  4236.  for the life of the program─the same lifetime as an external variable. The
  4237.  variable still has local visibility, however.
  4238.  
  4239.  The STATIC.C program below shows how to create and use a static local
  4240.  variable. In STATIC.C, the value of the  methuselah  variable persists
  4241.  through all calls to the  add_val  function, which adds values to
  4242.  methuselah  and prints the variable's value.
  4243.  
  4244.    /* STATIC.C: Demonstrate static variables. */
  4245.  
  4246.    #include <stdio.h>
  4247.  
  4248.    void add_val( int value );
  4249.  
  4250.    main()
  4251.    {
  4252.       add_val( 1 );
  4253.       add_val( 5 );
  4254.       add_val( 20 );
  4255.    }
  4256.  
  4257.    void add_val( int value )
  4258.    {
  4259.       static int methuselah;
  4260.       if( value == 1 )
  4261.          methuselah = 0;
  4262.       methuselah = methuselah + value;
  4263.       printf( "methuselah = %d\n", methuselah );
  4264.    }
  4265.  
  4266.  The  add_val  function in STATIC.C accepts one parameter and also declares a
  4267.  static local variable named  methuselah. Each time  add_val  is called, it
  4268.  adds the passed value to  methuselah.
  4269.  
  4270.  The main function calls the  add_val  function three times, passing the
  4271.  values 1, 5, and 20 to  add_val  as arguments. The program's output
  4272.  
  4273.    methuselah = 1
  4274.    methuselah = 6
  4275.    methuselah = 26
  4276.  
  4277.  shows that the value of  methuselah  persists through all three function
  4278.  calls.
  4279.  
  4280.  If we remove the static keyword from the declaration of  methuselah, the
  4281.  variable's value is not preserved between function calls. The value of
  4282.  methuselah  is unpredictable the second and third times that  add_val  is
  4283.  called.
  4284.  
  4285.  Notice that extending a local variable's lifetime with static doesn't affect
  4286.  its visibility. The  methuselah  variable keeps its value between function
  4287.  calls, but you can't refer to the variable outside the  add_val  function.
  4288.  
  4289.  
  4290.  Converting Data Types
  4291.  
  4292.  It's usually best to avoid mixing data items of different types in the same
  4293.  expression. You wouldn't normally add a character variable to a
  4294.  floating-point variable, for instance. Some languages, such as QuickPascal,
  4295.  generally treat type mixing as an error. However, the C language gives you
  4296.  the freedom to mix data types when necessary.
  4297.  
  4298.  For example, since the char and int types both can store whole numbers,
  4299.  there may be times when you have a good reason to add a char value to an int
  4300.  value. When you mix types, QuickC does not issue an error message. Instead,
  4301.  the compiler converts both data items to the same type and then performs the
  4302.  requested operation.
  4303.  
  4304.  Type conversion can occur in one of two ways. The first way occurs
  4305.  automatically when you combine different types in an expression. You can
  4306.  also use special syntax to intentionally "cast" (convert) one type to
  4307.  another. We'll discuss both methods in the following sections.
  4308.  
  4309.  Knowing how C converts types will help you to find bugs that result from
  4310.  unintended type clashes and to minimize errors when you deliberately mix
  4311.  types.
  4312.  
  4313.  
  4314.  Ranking of Data Types
  4315.  
  4316.  For purposes of conversion, the C language ranks data types in the order
  4317.  shown in Figure 5.1.
  4318.  
  4319.  (This figure may be found in the printed book.)
  4320.  
  4321.  The ranking illustrated in Figure 5.1 generally reflects the amount of
  4322.  storage that each type requires. As you may remember from Chapter 4, "Data
  4323.  Types," larger data types require more storage than smaller types. Thus, an
  4324.  int, which requires two bytes of storage, outranks a char, which requires
  4325.  one byte.
  4326.  
  4327.  Within this ranking, an unsigned type outranks the corresponding signed
  4328.  type. An unsigned char value is of higher rank than a signed char, and so
  4329.  forth.
  4330.  
  4331.  
  4332.  Promotions and Demotions
  4333.  
  4334.   A promotion is usually harmless.
  4335.  
  4336.  A type conversion always involves two data items of different types.
  4337.  Whenever possible, QuickC converts the lower-ranking (smaller) data item to
  4338.  the higher-ranking (larger) type. This kind of conversion, called a
  4339.  "promotion," is normally harmless. For example, since a two-byte int has
  4340.  more than enough room to store a one-byte char, it's generally safe to
  4341.  promote a char value to an int.
  4342.  
  4343.   A demotion usually causes a loss of data.
  4344.  
  4345.  Sometimes, the compiler is forced to convert a higher-ranking value to a
  4346.  lower-ranking type. This kind of conversion, called a "demotion," usually
  4347.  causes loss of data. For example, the int value 32,000 is much too large to
  4348.  be stored in a char type, which can't hold a number larger than 255. If you
  4349.  assign the value 32,000 to a char variable, some data must be lost.
  4350.  
  4351.  A demotion of an integer type truncates the higher-ranking type, throwing
  4352.  away the data from high-order bytes that can't fit in the smaller-ranking
  4353.  value. Some demotions of floating-point types round off a value rather than
  4354.  truncate it.
  4355.  
  4356.  
  4357.  Automatic Type Conversions
  4358.  
  4359.   C does an automatic  type conversion when you  mix different data types.
  4360.  
  4361.  When a program statement mixes two different data types, QuickC performs an
  4362.  automatic type conversion. The following code, for instance, adds the char
  4363.  variable  a  to the int variable  b.
  4364.  
  4365.    char a = 5;
  4366.    int b = 32000;
  4367.    b = a + b;
  4368.  
  4369.  In the statement
  4370.  
  4371.    b = a + b;
  4372.  
  4373.  the addition operation to the right of the equal sign triggers an automatic
  4374.  type conversion. QuickC promotes the char value to an int and then adds the
  4375.  two int values.
  4376.  
  4377.  If you're not sure whether QuickC is doing an automatic type conversion, set
  4378.  Warning Level 2 or higher in the Compiler Flags dialog box. The compiler
  4379.  generates the warning message
  4380.  
  4381.    C4051: data conversion
  4382.  
  4383.  whenever an automatic conversion occurs. This monitoring helps you readily
  4384.  identify unwanted conversions.
  4385.  
  4386.  If you carelessly mix different types, you may create subtle errors. The
  4387.  CONVERT.C program below has a deliberate error that shows what can happen
  4388.  when types are mixed. It adds four variables and assigns their sum to a
  4389.  fifth variable, causing three promotions and one demotion.
  4390.  
  4391.    /* CONVERT.C: Demonstrate type conversions. */
  4392.  
  4393.    #include <stdio.h>
  4394.  
  4395.    main()
  4396.    {
  4397.       char c_val = 10;
  4398.       int i_val = 20;
  4399.       long l_val = 64000;
  4400.       float f_val = 3.1;
  4401.       int result;
  4402.  
  4403.       result = c_val + i_val + l_val + f_val;  /* Error! */
  4404.  
  4405.       printf( "%d\n", result );
  4406.    }
  4407.  
  4408.  The CONVERT.C program adds the numbers 10, 20, 64000, and 3.1. Instead of
  4409.  the correct result, 64033.10, the program prints
  4410.  
  4411.    -1503
  4412.  
  4413.  Something definitely went wrong. The problem lies somewhere in the line
  4414.  
  4415.    result = c_val + i_val + l_val + f_val;
  4416.  
  4417.  which triggers four automatic type conversions. We'll examine the
  4418.  conversions in order.
  4419.  
  4420.  The first conversion occurs when the char variable  c_val  is added to the
  4421.  int variable  i_val:
  4422.  
  4423.    c_val + i_val
  4424.  
  4425.  Since the variables are different types, QuickC automatically converts the
  4426.  lower-ranking char value to the higher-ranking int type before adding them.
  4427.  This promotion doesn't create any problems, since there's more than enough
  4428.  room to store the one-byte char value in the two-byte int. The sum of this
  4429.  addition is 30, another int value.
  4430.  
  4431.  The next operation adds that partial sum to the long value of  l_val  (to
  4432.  make the expression easier to read, we'll show the sum from the previous
  4433.  addition):
  4434.  
  4435.    30 + l_val
  4436.  
  4437.  This addition triggers another promotion. The compiler promotes the int
  4438.  result of the first addition to a long value before adding it to  l_val,
  4439.  which is long. Since the four-byte long type has more than enough room to
  4440.  store a two-byte int, this promotion is also harmless.
  4441.  
  4442.  Now the partial sum equals 64030. The last addition from CONVERT.C
  4443.  
  4444.    64030 + f_val
  4445.  
  4446.  triggers another harmless conversion: the compiler converts the long result
  4447.  of the previous addition to a float value before adding it to  f_val. Even
  4448.  though floating-point and integer values are stored in different internal
  4449.  formats, no data is lost when the long is converted to a float.
  4450.  
  4451.  The result of these additions and conversions is the float value 64033.10,
  4452.  which is correct. So where does the mistake occur?
  4453.  
  4454.  The problem arises when CONVERT.C assigns the final sum to the wrong type of
  4455.  variable. You'll recall that the line containing these operations begins
  4456.  with the assignment result =.
  4457.  
  4458.  Earlier in the program, we declared the variable  result  as an int. The
  4459.  twobyte int variable created to store the result of these additions is too
  4460.  small to contain the four-byte float sum that was finally produced.
  4461.  
  4462.  The assignment forces QuickC to demote the larger float value to the smaller
  4463.  int type. It's impossible to store such a large floating-point value in the
  4464.  two bytes of an int, so the final result is incorrect.
  4465.  
  4466.  Figure 5.2 shows the progression of automatic type conversions that the
  4467.  CONVERT.C program produces.
  4468.  
  4469.  (This figure may be found in the printed book.)
  4470.  
  4471.  We can fix the conversion error by declaring the variable  result  as a
  4472.  float, substituting
  4473.  
  4474.    float result;
  4475.  
  4476.  for the earlier declaration. We'll also need to change the format string in
  4477.  the printf function call to print a float value, as shown below:
  4478.  
  4479.    printf( "%6.2f\n", result );
  4480.  
  4481.  Now CONVERT.C prints the expected value of 64033.10.
  4482.  
  4483.  
  4484.  Manual Type Conversions through Casting
  4485.  
  4486.   A cast forces a value  to a particular type.
  4487.  
  4488.  The C language also allows you to force a type conversion that would not
  4489.  otherwise happen, a process known as "casting." Using casts, it is possible
  4490.  to convert a data item to any C data type.
  4491.  
  4492.  Sometimes you must use a cast to make the program work properly. When
  4493.  calling the malloc library function, for instance, you should perform a cast
  4494.  on the value that the function returns. (Chapter 12, "Dynamic Memory
  4495.  Allocation," explains malloc and other memory-allocating functions.)
  4496.  
  4497.  Casts can also make a program more readable. QuickC does most automatic type
  4498.  conversions silently. So if you write a tricky bit of code that relies on
  4499.  automatic conversions, you, or some other programmer, may not notice the
  4500.  conversions later. To make such code more readable─and easier to debug─you
  4501.  can add explicit type casts in places where silent conversions might go
  4502.  unnoticed.
  4503.  
  4504.  To cast a value to a different type, place the desired type name in
  4505.  parentheses in front of the value. For instance, the statement
  4506.  
  4507.    f_val = (float)any_val;
  4508.  
  4509.  casts the value of the variable  any_val  to type float before assigning it
  4510.  to  f_val. Here the type name in parentheses,
  4511.  
  4512.    (float)
  4513.  
  4514.  performs the cast. No matter what type  any_val  has, the cast converts that
  4515.  type to float before assigning it to  f_val.
  4516.  
  4517.  When you cast a variable, the cast affects the value the variable yields,
  4518.  but not the variable itself. Suppose that  any_val  is an int variable with
  4519.  the value 333. The above cast converts the value 333 to float format before
  4520.  assigning it to  f_val. But  any_val  remains an int variable after the
  4521.  cast.
  4522.  
  4523.  Remember, you can detect automatic type conversions by setting Warning Level
  4524.  2 or higher in QuickC and watching for the following warning:
  4525.  
  4526.    C4051: data conversion
  4527.  
  4528.  You can then add explicit casts to eliminate the warning where the
  4529.  conversions are desirable. (See "Automatic Type Conversions" above.)
  4530.  
  4531.  
  4532.  Register Variables
  4533.  
  4534.   Register variables are stored in processor registers instead of addressable
  4535.  memory.
  4536.  
  4537.  You can use the register keyword in variable declarations to request that a
  4538.  variable be stored in a processor register. Because processor registers can
  4539.  be accessed more quickly than addressable memory locations, this storage can
  4540.  make a program run faster. Programmers use register to speed access to
  4541.  heavily used variables, such as counter variables in loops.
  4542.  
  4543.  The register specifier is much less important than it used to be, now that
  4544.  most C compilers, including QuickC, can perform optimizations (improvements)
  4545.  during compilation. If you compile with the Optimizations option turned on,
  4546.  QuickC automatically stores variables in registers when needed. So you
  4547.  probably won't need to use register except in special cases.
  4548.  
  4549.  ────────────────────────────────────────────────────────────────────────────
  4550.  IMPORTANT
  4551.  
  4552.  If you compile with Optimizations on, an explicit register declaration can
  4553.  override register storage that QuickC would do automatically. Declaring one
  4554.  variable with register might prevent QuickC from storing some other variable
  4555.  in a register. In the worst case, this can make a program run slower.
  4556.  ────────────────────────────────────────────────────────────────────────────
  4557.  
  4558.  You can use register only with short integer types (char, int, and short
  4559.  int). Other types─including aggregate types such as arrays─are too large to
  4560.  fit in a register.
  4561.  
  4562.  Only two registers are available for variable storage at any given time.
  4563.  (They are DI and SI, for those who have programmed in assembly language.) If
  4564.  you request more registers than are available, QuickC stores the extra
  4565.  variables in addressable memory, as it does non-register variables.
  4566.  
  4567.  The following declaration uses register to ask the compiler to store the int
  4568.  variable  val  in a processor register:
  4569.  
  4570.    register int val;
  4571.  
  4572.  You can ask the compiler to store more than one variable in a register. For
  4573.  instance, the statement
  4574.  
  4575.    register int val, count;
  4576.  
  4577.  declares  val  and  count  as register variables.
  4578.  
  4579.  ────────────────────────────────────────────────────────────────────────────
  4580.  NOTE
  4581.  
  4582.  Since registers are not addressable, you can't use the address-of (&)
  4583.  operator to get the address of a variable declared with register. This rule
  4584.  applies whether or not QuickC is actually able to store the variable in a
  4585.  register. Thus, if you need to access a variable through a pointer, don't
  4586.  declare that variable with register. See the section "Initializing a Pointer
  4587.  Variable" in Chapter 8, "Pointers."
  4588.  ────────────────────────────────────────────────────────────────────────────
  4589.  
  4590.  
  4591.  Renaming Existing Types with typedef
  4592.  
  4593.  The typedef keyword creates a new name for an existing data type. This is a
  4594.  convenience feature that you can use to make programs more readable. For
  4595.  instance, the declaration
  4596.  
  4597.    typedef int integer;
  4598.  
  4599.  allows you to use  integer  as a synonym for int.
  4600.  
  4601.  One more practical use of typedef is to substitute a short, descriptive name
  4602.  for an aggregate type. For instance, the QuickC Presentation Graphics
  4603.  library uses typedef to create descriptive names such as windowtype and
  4604.  titletype for structures used in that library.
  4605.  
  4606.  ────────────────────────────────────────────────────────────────────────────
  4607.  NOTE
  4608.  
  4609.  The typedef keyword doesn't create a new data type. It merely allows you to
  4610.  use a different name for a type that already exists.
  4611.  ────────────────────────────────────────────────────────────────────────────
  4612.  
  4613.  You can also use typedef to minimize portability problems. By using typedef
  4614.  declarations for data types that are machine dependent, you need only change
  4615.  the typedef declaration if you move the program to a different operating
  4616.  system.
  4617.  
  4618.  
  4619.  The Enumeration Type
  4620.  
  4621.  The "enumeration type" specifies a set of named integer constants, similar
  4622.  to the enumerated type in QuickPascal. In the C language, enumeration types
  4623.  are declared with the enum keyword.
  4624.  
  4625.   Use enum to name a  set of integer constants.
  4626.  
  4627.  The enum type is useful mainly for improving a program's readability. With
  4628.  enum, you can use meaningful names for a set of constants whose purpose
  4629.  might not otherwise be apparent.
  4630.  
  4631.  Suppose you're writing a calendar program in which the constant 0 represents
  4632.  Saturday, 1 represents Sunday, and so on. You might begin by declaring the
  4633.  enumeration type  day  in the following manner:
  4634.  
  4635.    enum day
  4636.    {
  4637.       saturday, sunday, monday, tuesday,
  4638.       wednesday, thursday, friday
  4639.    };
  4640.  
  4641.  Notice this declaration's similarity to a structure declaration. As with
  4642.  structures, the type declaration creates a template that you can use to
  4643.  declare variables of this type. (See the section "Declaring a Structure
  4644.  Type" in Chapter 4, "Data Types.")
  4645.  
  4646.  Unless you specify otherwise, the first value in an enumeration type equals
  4647.  0 and others are numbered sequentially. In the enum type shown above,
  4648.  saturday  equals 0,  sunday  equals 1, and so forth.
  4649.  
  4650.  The values in an enumeration type need not be sequential, however. If you
  4651.  want some other order, you can declare explicit values for each member of
  4652.  the type. The following declaration, for example, assigns the names  zero,
  4653.  freeze, and boil  to the constants 0, 32, and 220, respectively.
  4654.  
  4655.    enum temps
  4656.    {
  4657.       zero = 0,
  4658.       freeze = 32,
  4659.       boil = 220
  4660.    };
  4661.  
  4662.  After declaring an enumeration type, you can create a variable of that type
  4663.  and assign it a value from the type. The statement
  4664.  
  4665.    enum day today = wednesday;
  4666.  
  4667.  declares the variable  today, assigning it the value  wednesday  from the
  4668.  day  enumeration type.
  4669.  
  4670.  After you assign its value, you can use the variable  today  as you would an
  4671.  int variable. Although the variable is considered to have the enum type, it
  4672.  is an ordinary int for all practical purposes.
  4673.  
  4674.  Enumeration types aren't used very often, partly because you can achieve a
  4675.  similar effect using the #define directive. (Chapter 7, "Preprocessor
  4676.  Directives," explains #define in detail.) For example, the code
  4677.  
  4678.    #define SATURDAY 0
  4679.    #define SUNDAY 1
  4680.    #define MONDAY 2
  4681.    #define TUESDAY 3
  4682.    #define WEDNESDAY 4
  4683.       .
  4684.       .
  4685.       .
  4686.    int today = WEDNESDAY;
  4687.  
  4688.  uses #define to create symbolic constants named  SATURDAY,  SUNDAY,  MONDAY,
  4689.   TUESDAY, and  WEDNESDAY, assigning them the values 0 through 4. The last
  4690.  line in the example creates the int variable  today  and assigns it the
  4691.  value of  WEDNESDAY. The result is identical to the statement shown earlier:
  4692.  
  4693.  
  4694.    enum day today = wednesday;
  4695.  
  4696.  One advantage of using enum over #define directives is that it groups
  4697.  related names in one place and can be more compact than a long series of
  4698.  directives.
  4699.  
  4700.  This concludes our main discussion of data types. The next chapter,
  4701.  "Operators," examines the C language's rich set of operators, which allow
  4702.  you to manipulate data in many different ways.
  4703.  
  4704.  
  4705.  
  4706.  
  4707.  
  4708.  
  4709.  Chapter 6  Operators
  4710.  ────────────────────────────────────────────────────────────────────────────
  4711.  
  4712.  Compared with other languages, C is very compact, using fewer than 50
  4713.  keywords. One reason C can get by with so few reserved words is its
  4714.  abundance of powerful operators─well over 30.
  4715.  
  4716.  Most C operators are easy to understand and remember. Even if you have never
  4717.  seen a C program, you probably understand that the statement
  4718.  
  4719.    val = val * 5;
  4720.  
  4721.  multiplies the variable  val  by 5 and assigns the result to  val.
  4722.  
  4723.  Because the printable ASCII character set has only so many unique symbols, C
  4724.  uses some ASCII symbols in more than one operator. For instance, the
  4725.  asterisk (*) performs either a multiplication or pointer operation,
  4726.  depending on context. Similarly, the ampersand (&) is part of three C
  4727.  operators. Depending on context, the ampersand can obtain an address or
  4728.  perform a logical or bitwise AND operation. Be careful not to confuse
  4729.  operators that look similar but do different jobs.
  4730.  
  4731.  This chapter describes the C operators, beginning with those that are common
  4732.  to most languages, and then discussing those unique to C.
  4733.  
  4734.  
  4735.  Introducing C's Operators
  4736.  
  4737.  We'll start by discussing C operators that look and behave similarly to
  4738.  operators in other languages. These include the following groups:
  4739.  
  4740.  
  4741.    ■   Arithmetic operators, which do operations such as addition and
  4742.        multiplication
  4743.  
  4744.    ■   Relational operators, which compare two values and give a true or
  4745.        false result
  4746.  
  4747.    ■   Assignment operators, which make one value equal to another
  4748.  
  4749.  
  4750.  
  4751.  Arithmetic Operators
  4752.  
  4753.  The C language's arithmetic operators closely resemble those in other
  4754.  languages. Table 6.1 lists C's arithmetic operators.
  4755.  
  4756.  Table 6.1  Arithmetic Operators
  4757.  
  4758. ╓┌─────────────────────────┌─────────────────────────────────────────────────╖
  4759.  Operator                  Description
  4760.  ────────────────────────────────────────────────────────────────────────────
  4761.  *                         Multiplication
  4762.  /                         Division
  4763.  %                         Modulus
  4764.  +                         Addition
  4765.  -                         Subtraction
  4766.  ────────────────────────────────────────────────────────────────────────────
  4767.  
  4768.  
  4769.  The "modulus operator" (%) may be unfamiliar. It divides a value and gives
  4770.  the remainder. For instance, the statement
  4771.  
  4772.    remainder = 20 % 3;
  4773.  
  4774.  assigns the value 2 to the variable  remainder  (20 divided by 3 equals 6,
  4775.  with a remainder of 2). If the division doesn't produce a remainder, the
  4776.  modulus operator yields the value 0.
  4777.  
  4778.  
  4779.  Relational Operators
  4780.  
  4781.  "Relational operators" evaluate the relationship between two expressions,
  4782.  giving a true result (the value 1) or a false result (the value 0). C has
  4783.  six relational operators, which are listed in Table 6.2.
  4784.  
  4785.  Table 6.2  Relational Operators
  4786.  
  4787. ╓┌──────────────────────┌────────────────────────────────────────────────────╖
  4788.  Operator               Description
  4789.  ────────────────────────────────────────────────────────────────────────────
  4790.  Operator               Description
  4791.  ────────────────────────────────────────────────────────────────────────────
  4792.  <                      Less than
  4793.  <=                     Less than or equal
  4794.  >                      Greater than
  4795.  >=                     Greater than or equal
  4796.  ==                     Equal
  4797.  !=                     Not equal
  4798.  ────────────────────────────────────────────────────────────────────────────
  4799.  
  4800.  
  4801.  The "equality operator" (==), shown above, tests whether two expressions are
  4802.  equal.
  4803.  
  4804.  Don't confuse the equality operator with the assignment operator (=)
  4805.  discussed in the next section. The assignment operator sets one value equal
  4806.  to another, as we'll see shortly. (Chapter 10, "Programming Pitfalls,"
  4807.  discusses this common programming error.)
  4808.  
  4809.  The C language gives the value 1 for true and 0 for false but recognizes any
  4810.  nonzero value as true. The following code fragment demonstrates this
  4811.  difference:
  4812.  
  4813.    printf( "C generates %d for true\n", 2 == 2 );
  4814.    printf( "C generates %d for false\n", 2 == 4 );
  4815.    if( -33 )
  4816.       printf( "C recognizes any nonzero value as true\n" );
  4817.  
  4818.  The output from this code,
  4819.  
  4820.    C generates 1 for true
  4821.    C generates 0 for false
  4822.    C recognizes any nonzero value as true
  4823.  
  4824.  shows that the true expression ( 2 == 2 ) gives the value 1 and the false
  4825.  expression ( 2 == 4 ) gives the value 0. The last output line shows that C
  4826.  recognizes the nonzero value -33 as a true value.
  4827.  
  4828.  
  4829.  Assignment Operators
  4830.  
  4831.  The "assignment operator" (=) sets one value equal to another. The following
  4832.  statement assigns the value of  sample  to  val:
  4833.  
  4834.    val = sample;
  4835.  
  4836.   You can combine an assignment with a bitwise  or arithmetic operation.
  4837.  
  4838.  In a convenient shorthand, C allows you to combine the assignment operator
  4839.  with any arithmetic or bitwise operator (see the "Arithmetic Operators" and
  4840.  "Bitwise Operators" sections). For example, the statement
  4841.  
  4842.    val = val + sample;
  4843.  
  4844.  can more conveniently be written
  4845.  
  4846.    val += sample;
  4847.  
  4848.  Both statements add  val  to  sample  and then assign the result to  val.
  4849.  
  4850.  Table 6.3 lists C's special assignment operators.
  4851.  
  4852.  Table 6.3  Special Assignment Operators
  4853.  
  4854. ╓┌───────────┌─────────────┌─────────────────────────────────────────────────╖
  4855.  Expression  Equivalent    Operation
  4856.  ────────────────────────────────────────────────────────────────────────────
  4857.  x *= y       x = x * y    Multiplication
  4858.  x /= y       x = x / y    Division
  4859.  x %= y       x = x % y    Modulus
  4860.  x += y       x = x + y    Addition
  4861.  x -= y       x = x - y    Subtraction
  4862.  x <<= y      x = x << y   Left shift
  4863.  x >>= y      x = x >> y   Right shift
  4864.  x &= y       x = x & y    AND
  4865.  x ^= y       x = x ^ y    Exclusive OR
  4866.  x |= y       x = x | y    Inclusive OR
  4867.  ────────────────────────────────────────────────────────────────────────────
  4868.  
  4869.  
  4870.  Note that the equal sign always follows the other operator. In the following
  4871.  code,
  4872.  
  4873.    val ^= sample;
  4874.    val =^ sample;
  4875.  
  4876.  the first statement is meaningful, but the second is a syntax error.
  4877.  
  4878.  
  4879.  C's Unique Operators
  4880.  
  4881.  The remaining sections in this chapter describe C operators that fall into
  4882.  two categories: those that are unique to C and those that look or behave
  4883.  differently in C than in other languages.
  4884.  
  4885.  
  4886.  Increment and Decrement Operators
  4887.  
  4888.  The C language's unique "increment" (++) and "decrement" (- -) operators are
  4889.  very useful. They increase or decrease an expression by a value of 1.
  4890.  
  4891.  Table 6.4  Increment and Decrement Operators
  4892.  
  4893. ╓┌─────────────────────┌─────────────────────────────────────────────────────╖
  4894.  Operator              Operation
  4895.  Operator              Operation
  4896.  ────────────────────────────────────────────────────────────────────────────
  4897.  ++                    Increment expression by 1
  4898.  - -                   Decrement expression by 1
  4899.  ────────────────────────────────────────────────────────────────────────────
  4900.  
  4901.  
  4902.  Thus, the two statements
  4903.  
  4904.    val = val + 1;
  4905.    val++;
  4906.  
  4907.  are equivalent and so are these statements:
  4908.  
  4909.    val = val - 1;
  4910.    val--;
  4911.  
  4912.   You can use the ++ and - - operators before  or after an expression.
  4913.  
  4914.  The ++ and - - operators can precede or follow an expression. Placed before
  4915.  an expression, the operator changes the expression before the expression's
  4916.  value is used. In this case, the operator is said to be a "prefix" operator.
  4917.  Placed after an expression, the operator (known as a "postfix" operator)
  4918.  changes the value of the expression after the expression's value is used.
  4919.  
  4920.  In the DECRMENT.C program, shown below, the decrement operator is used both
  4921.  as a prefix operator and a postfix operator.
  4922.  
  4923.    /* DECRMENT.C: Demonstrate prefix and postfix operators. */
  4924.  
  4925.    #include <stdio.h>
  4926.    main()
  4927.    {
  4928.       int val, sample = 3, proton = 3;
  4929.       val = sample--;
  4930.       printf( "val = %d  sample = %d\n", val, sample );
  4931.       val = --proton;
  4932.       printf( "val = %d  proton = %d\n", val, proton );
  4933.    }
  4934.  
  4935.  Here is the output from DECRMENT.C:
  4936.  
  4937.    val = 3  sample = 2
  4938.    val = 2  proton = 2
  4939.  
  4940.  In the first use of the decrement operator, the statement
  4941.  
  4942.    val = sample--;
  4943.  
  4944.  assigns the value of  sample  (3) to the variable  val  and then decrements
  4945.  sample  to the value 2. Contrast this with the statement
  4946.  
  4947.    val = --proton;
  4948.  
  4949.  which first decrements  proton  to the value 2 and then assigns that value
  4950.  to  val.
  4951.  
  4952.  
  4953.  Bitwise Operators
  4954.  
  4955.  The "bitwise operators," listed in Table 6.5, manipulate bits in data of the
  4956.  integer type. These operators are often used in programs that must interact
  4957.  with hardware.
  4958.  
  4959.  Table 6.5  Bitwise Operators
  4960.  
  4961. ╓┌─────────────────────────┌─────────────────────────────────────────────────╖
  4962.  Operator                  Description
  4963.  ────────────────────────────────────────────────────────────────────────────
  4964.  ~                         Complement
  4965.  <<                        Left shift
  4966.  >>                        Right shift
  4967.  &                         AND
  4968.  ^                         Exclusive OR
  4969.  |                         Inclusive OR
  4970.  ────────────────────────────────────────────────────────────────────────────
  4971.  
  4972.  
  4973.  The ~ operator, known as the "one's complement," acts on only one value
  4974.  (rather than on two, as do most operators). This operator changes every 1
  4975.  bit in its operand to a 0 bit and vice versa.
  4976.  
  4977.  The  and >> operators, known as the "shift operators," shift the left
  4978.  operand by the value given in the right operand. These operators offer a
  4979.  fast, convenient way to multiply or divide integers by a power of 2.
  4980.  
  4981.  The & operator, known as the "bitwise AND," sets a bit to 1 if either of the
  4982.  corresponding bits in its operands is 1, or to 0 if both corresponding bits
  4983.  are 0. It is often used to "mask," or turn off, one or more bits in a value.
  4984.  
  4985.  
  4986.  The ^ operator, known as the "bitwise exclusive OR," sets a bit to 1 if the
  4987.  corresponding bits in its operands are different, or to 0 if they are the
  4988.  same.
  4989.  
  4990.  The  |  operator, known as the "bitwise inclusive OR," sets a bit to 1 if
  4991.  either of the corresponding bits in its operands is 1, or to 0 if both
  4992.  corresponding bits are 0. It is often used to turn on bits in a value.
  4993.  
  4994.  Each of the bitwise operators is used in the BITWISE.C program, shown below.
  4995.  
  4996.  
  4997.    /* BITWISE.C: Demonstrate bitwise operators. */
  4998.  
  4999.    #include <stdio.h>
  5000.  
  5001.    main()
  5002.    {
  5003.       printf( "255 & 15 = %d\n", 255 & 15 );
  5004.       printf( "255 | 15 = %d\n", 255 | 15 );
  5005.       printf( "255 ^ 15 = %d\n", 255 ^ 15 );
  5006.       printf( "2 << 2   = %d\n", 2 << 2 );
  5007.       printf( "16 >> 2  = %d\n", 16 >> 2 );
  5008.       printf( "~2       = %d\n", ~2 );
  5009.    }
  5010.  
  5011.  The output from BITWISE.C,
  5012.  
  5013.    255 & 15 = 15
  5014.    255 | 15 = 255
  5015.    255 ^ 15 = 240
  5016.    2 << 2   = 8
  5017.    16 >> 2  = 4
  5018.    ~2  = -3
  5019.  
  5020.  shows the results of the program's various bitwise operations.
  5021.  
  5022.  The fourth and fifth output lines show you how to use shift operators to
  5023.  multiply and divide by powers of 2. The program multiplies 2 by 4 by
  5024.  shifting the value 2 twice to the left:
  5025.  
  5026.    2 << 2   = 8
  5027.  
  5028.  Similarly, the program divides 16 by 4 by shifting the value 16 twice to the
  5029.  right:
  5030.  
  5031.    16 >> 2  = 4
  5032.  
  5033.  
  5034.  Logical Operators
  5035.  
  5036.  C has three logical operators─AND, OR, and NOT─that allow you to test more
  5037.  than one condition in a single expression. Table 6.6 lists C's logical
  5038.  operators.
  5039.  
  5040.  Table 6.6  Logical Operators
  5041.  
  5042. ╓┌──────────────────────────┌────────────────────────────────────────────────╖
  5043.  Operator                   Description
  5044.  ────────────────────────────────────────────────────────────────────────────
  5045.  !                          Logical NOT
  5046.  &&                         Logical AND
  5047.  | |                        Logical OR
  5048.  ────────────────────────────────────────────────────────────────────────────
  5049.  
  5050.  
  5051.  The logical OR ( | | ) and AND (&&) operators are often used to combine
  5052.  logical tests within a conditional statement. For example, the if statement
  5053.  
  5054.  
  5055.    if( val > 10 && sample < 10 )
  5056.       printf( "Oh joy!\n" );
  5057.  
  5058.  prints  Oh joy!  if both conditions in the test expression are true (if  val
  5059.   is greater than 10 and  sample  is less than 10). Here, the relational
  5060.  operators (> and ) have higher "precedence" than the logical AND operator
  5061.  (&&), so the compiler evaluates them first. We discuss operator precedence
  5062.  later in this chapter.
  5063.  
  5064.  The logical NOT operator (!) reverses an expression's logical value. For
  5065.  instance, if the variable  val  has the value 8, the expression  (val == 8)
  5066.  is true but the expression  !(val == 8)  is false.
  5067.  
  5068.  The NOT.C program below shows a common use of this operator.
  5069.  
  5070.    /* NOT.C: Demonstrate logical NOT operator. */
  5071.  
  5072.    #include <stdio.h>
  5073.  
  5074.    main()
  5075.    {
  5076.      int val = 0;
  5077.      if( !val )
  5078.         printf( "val is zero" );
  5079.    }
  5080.  
  5081.  The expression  if( !val )  is equivalent to the expression  if( val == 0 ).
  5082.  When used in this way, the logical NOT operator converts a 0 value to 1 and
  5083.  any nonzero value to 0.
  5084.  
  5085.  ────────────────────────────────────────────────────────────────────────────
  5086.  NOTE
  5087.  
  5088.  Don't confuse the logical OR and AND operators with the bitwise OR and AND
  5089.  operators discussed in the previous section. The bitwise operators use the
  5090.  same ASCII symbols, but have only one character. For instance, logical AND
  5091.  is &&, whereas bitwise AND is &.
  5092.  ────────────────────────────────────────────────────────────────────────────
  5093.  
  5094.  
  5095.  Address Operators
  5096.  
  5097.  The C language has two operators that work with memory addresses. Table 6.7
  5098.  lists C's address operators.
  5099.  
  5100.  Table 6.7  Address Operators
  5101.  
  5102. ╓┌──────────────┌────────────────────────────────────────────────────────────╖
  5103.  Operator       Operation
  5104.  ────────────────────────────────────────────────────────────────────────────
  5105.  Operator       Operation
  5106.  ────────────────────────────────────────────────────────────────────────────
  5107.  &              Yield address of the operand
  5108.  *              Yield value contained at the operand's address
  5109.  ────────────────────────────────────────────────────────────────────────────
  5110.  
  5111.  
  5112.  Both address operators are often used with pointers─variables that contain
  5113.  the addresses of other variables. Chapter 8, "Pointers," and Chapter 9,
  5114.  "Advanced Pointers," are devoted to explaining pointers, including the use
  5115.  of these two operators with them. Since you must understand pointers in
  5116.  order to understand these operators fully, we'll describe them briefly here
  5117.  and elaborate on their use in Chapter 8.
  5118.  
  5119.  The "address-of operator" (&) yields a constant equal to the machine address
  5120.  of its operand. For instance, if the variable  val  contains the value 10,
  5121.  and its storage is located at address 1508, the expression  val  yields the
  5122.  value 10, while the expression  &val  yields the constant 1508.
  5123.  
  5124.  Since the address-of operator yields a constant, you can't assign a value to
  5125.  an expression that uses it. The statement
  5126.  
  5127.    &val = 20;
  5128.  
  5129.  is illegal for the same reason that the statement
  5130.  
  5131.    1508 = 20;
  5132.  
  5133.  won't pass muster.
  5134.  
  5135.  The "indirection operator" (*) yields the value contained in the address
  5136.  referenced by its operand. If you declare  ptr  as a pointer variable, the
  5137.  expression
  5138.  
  5139.    *ptr
  5140.  
  5141.  yields the contents of the address to which  ptr  points.
  5142.  
  5143.  
  5144.  Conditional Operator
  5145.  
  5146.  The "conditional operator" (? :) is made up of two symbols and requires
  5147.  three expressions. It is similar to an if-else construct. If the first
  5148.  expression evaluates as true, the first operand is assigned the value of the
  5149.  second operand. If the first expression is false, the first operand is
  5150.  assigned the value of the third operand.
  5151.  
  5152.  The following statement gives the absolute value of the variable  val. The
  5153.  variable is assigned its original value if it is nonnegative or is negated
  5154.  if its original value is negative:
  5155.  
  5156.    val = (val >= 0 ) ? val : -val;
  5157.  
  5158.  The statement is equivalent to the following if-else construct:
  5159.  
  5160.    if( val >= 0 )
  5161.       val = val;
  5162.    else
  5163.       val = -val;
  5164.  
  5165.  
  5166.  The sizeof Operator
  5167.  
  5168.  The "sizeof operator" yields the number of bytes contained in its operand,
  5169.  which can be either a general data type or a specific variable. If you apply
  5170.  sizeof to a type name in parentheses, as in the expression
  5171.  
  5172.    sizeof( int )
  5173.  
  5174.  the operator yields the size of that data type in bytes. This example yields
  5175.  the value 2, indicating that an int contains two bytes on DOS machines. You
  5176.  can use this feature to determine the sizes of types that are implementation
  5177.  dependent when transporting a program from one machine to another.
  5178.  
  5179.  If you place sizeof in front of a variable name, the operator returns the
  5180.  number of bytes in the variable. For instance, if you create the string
  5181.  
  5182.    char my_string[] = "Hello";
  5183.  
  5184.  the expression
  5185.  
  5186.    sizeof my_string
  5187.  
  5188.  yields the value 6, showing that the string contains 5 printing characters
  5189.  and a null character.
  5190.  
  5191.  
  5192.  Comma Operator
  5193.  
  5194.  Preceding chapters have shown various ways to use the comma (,) in C
  5195.  programming. For instance, commas can separate multiple function arguments
  5196.  or variable declarations. In such cases the comma is not an operator in the
  5197.  formal sense but merely punctuation, like the semicolon that ends a
  5198.  statement.
  5199.  
  5200.   The comma is used as punctuation and as an operator in C.
  5201.  
  5202.  In C, the comma can also perform as an operator. The commas that separate
  5203.  multiple expressions determine the order in which the expressions are
  5204.  evaluated, and the type and value of the result that is returned. The comma
  5205.  operator causes expressions to be evaluated from left to right. The value
  5206.  and type of the result are the value and type of the rightmost operand.
  5207.  
  5208.  For example, the statement
  5209.  
  5210.    val = sample, sample = temp;
  5211.  
  5212.  first assigns the value of  sample  to  val, then assigns the value of  temp
  5213.   to  sample.
  5214.  
  5215.  The comma operator often appears in for statements, where it can separate
  5216.  multiple initializing expressions or multiple modifying expressions. The
  5217.  FORLOOP1.C program from Chapter 3, "Flow Control," demonstrates both uses.
  5218.  Here is the for statement from that program:
  5219.  
  5220.    for( a = 256, b = 1; b < 512; a = a / 2, b = b * 2 )
  5221.       printf( "a = %d \tb = %d\n", a, b );
  5222.  
  5223.  The statement initializes two variables ( a  and  b ) and contains two
  5224.  modifying expressions ( a = a / 2  and  b = b * 2 ). Chapter 3 explains the
  5225.  FORLOOP1.C program in detail.
  5226.  
  5227.  
  5228.  Base Operator
  5229.  
  5230.  The base operator (:>) associates a base expression with a based pointer.
  5231.  Based-object support is a highly advanced feature included in QuickC 2.5 for
  5232.  compatibility with Microsoft C version 6.0; please refer to your C 6.0
  5233.  documentation for information about based objects.
  5234.  
  5235.  
  5236.  Operator Precedence
  5237.  
  5238.  Like all languages, C has precedence rules that control the order for
  5239.  evaluating the elements in expressions containing more than one operator. If
  5240.  you're familiar with precedence rules in other languages, you won't find any
  5241.  surprises in C. Table 6.8 shows the "pecking order" established for C's
  5242.  operators.
  5243.  
  5244.  Three general rules control the order of evaluation:
  5245.  
  5246.  
  5247.    1.  When two operators have unequal precedence, the operator with higher
  5248.        precedence is evaluated first.
  5249.  
  5250.    2.  Operators with equal precedence are evaluated from left to right.
  5251.  
  5252.    3.  You can change the normal order of precedence by enclosing an
  5253.        expression in parentheses. The enclosed expression is then evaluated
  5254.        first. (If parentheses are nested, inner parentheses have higher
  5255.        precedence than outer ones.)
  5256.  
  5257.  
  5258.  We'll demonstrate operator precedence with a simple example. Since the
  5259.  multiplication operator (*) has higher precedence than the addition operator
  5260.  (+), the statement
  5261.  
  5262.  val = 2 + 3 * 4
  5263.  
  5264.  assigns to val the value of 14 (or 2 + 12) rather than 20 (or 5 * 4). Since
  5265.  parentheses have higher precedence than any operator, they can change the
  5266.  normal precedence order. If you enclose the addition operation in
  5267.  parentheses, as follows
  5268.  
  5269.  val = (2 + 3) * 4
  5270.  
  5271.  the addition is done first. Now the statement assigns to val  the value 20
  5272.  (or 5 * 4).
  5273.  
  5274.  Table 6.8 lists the C operators and their precedence values. The lines in
  5275.  the table separate precedence levels. The highest precedence level is at the
  5276.  top of the table.
  5277.  
  5278.  Table 6.8  C Operators
  5279.  
  5280. ╓┌───────────────────────┌────────────────────────────────────┌──────────────╖
  5281.  Symbol                  Name or Meaning                      Associativity
  5282.  ────────────────────────────────────────────────────────────────────────────
  5283.  ( )                     Function call                        Left to right
  5284.  
  5285.  [ ]                     Array element
  5286.  
  5287.  .                       Structure or union
  5288.                          member
  5289.  
  5290.  ->                      Pointer to structure
  5291.                          member
  5292.  
  5293.  ────────────────────────────────────────────────────────────────────────────
  5294.  Symbol                  Name or Meaning                      Associativity
  5295.  ────────────────────────────────────────────────────────────────────────────
  5296. ────────────────────────────────────────────────────────────────────────────
  5297.  
  5298.  - -                     Decrement                            Right to left
  5299.  
  5300.  ++                      Increment
  5301.  
  5302.  ────────────────────────────────────────────────────────────────────────────
  5303.  
  5304.  :>                      Base operator                        Left to right
  5305.  
  5306.  ────────────────────────────────────────────────────────────────────────────
  5307.  
  5308.  !                       Logical NOT                          Right to left
  5309.  
  5310.  ~                       One's complement
  5311.  
  5312.  -                       Unary minus
  5313.  
  5314.  +                       Unary plus
  5315.  Symbol                  Name or Meaning                      Associativity
  5316.  ────────────────────────────────────────────────────────────────────────────
  5317. +                       Unary plus
  5318.  
  5319.  &                       Address
  5320.  
  5321.  *                       Indirection
  5322.  
  5323.  sizeof                  Size in bytes
  5324.  
  5325.  (type)                  Type cast [for example, (float) i]
  5326.  
  5327.  ────────────────────────────────────────────────────────────────────────────
  5328.  
  5329.  *                       Multiply                             Left to right
  5330.  
  5331.  /                       Divide
  5332.  
  5333.  %                       Modulus (remainder)
  5334.  
  5335.  ────────────────────────────────────────────────────────────────────────────
  5336.  Symbol                  Name or Meaning                      Associativity
  5337.  ────────────────────────────────────────────────────────────────────────────
  5338. ────────────────────────────────────────────────────────────────────────────
  5339.  
  5340.  +                       Add                                  Left to right
  5341.  
  5342.  -                       Subtract
  5343.  
  5344.  ────────────────────────────────────────────────────────────────────────────
  5345.  
  5346.  <<                      Left shift                           Left to right
  5347.  
  5348.  >>                      Right shift
  5349.  
  5350.  ────────────────────────────────────────────────────────────────────────────
  5351.  
  5352.  <                       Less than                            Left to right
  5353.  
  5354.  <=                      Less than or equal
  5355.  
  5356.  >                       Greater than
  5357.  Symbol                  Name or Meaning                      Associativity
  5358.  ────────────────────────────────────────────────────────────────────────────
  5359. >                       Greater than
  5360.  
  5361.  >=                      Greater than or equal
  5362.  
  5363.  ────────────────────────────────────────────────────────────────────────────
  5364.  
  5365.  ==                      Equal                                Left to right
  5366.  
  5367.  !=                      Not equal
  5368.  
  5369.  ────────────────────────────────────────────────────────────────────────────
  5370.  
  5371.  &                       Bitwise AND                          Left to right
  5372.  
  5373.  ────────────────────────────────────────────────────────────────────────────
  5374.  
  5375.  ^                       Bitwise exclusive OR                 Left to right
  5376.  
  5377.  ────────────────────────────────────────────────────────────────────────────
  5378.  Symbol                  Name or Meaning                      Associativity
  5379.  ────────────────────────────────────────────────────────────────────────────
  5380. ────────────────────────────────────────────────────────────────────────────
  5381.  
  5382.  |                       Bitwise OR                           Left to right
  5383.  
  5384.  ────────────────────────────────────────────────────────────────────────────
  5385.  
  5386.  &&                      Logical AND                          Left to right
  5387.  
  5388.  ────────────────────────────────────────────────────────────────────────────
  5389.  
  5390.  ||                      Logical OR                           Left to right
  5391.  
  5392.  ────────────────────────────────────────────────────────────────────────────
  5393.  
  5394.  ? :                     Conditional                          Right to left
  5395.  
  5396.  ────────────────────────────────────────────────────────────────────────────
  5397.  
  5398.  =                       Assignment                           Right to left
  5399.  Symbol                  Name or Meaning                      Associativity
  5400.  ────────────────────────────────────────────────────────────────────────────
  5401. =                       Assignment                           Right to left
  5402.  
  5403.  *=, /=, %=, +=, -=,     Compound assignment
  5404.  
  5405.  <<=, >>=,  &=, ^=, |=
  5406.  
  5407.  ────────────────────────────────────────────────────────────────────────────
  5408.  
  5409.  ,                       Comma                                Left to right
  5410.  
  5411.  ────────────────────────────────────────────────────────────────────────────
  5412.  
  5413.  
  5414.  
  5415.  
  5416.  
  5417.  
  5418.  
  5419.  
  5420.  Chapter 7  Preprocessor Directives
  5421.  ────────────────────────────────────────────────────────────────────────────
  5422.  
  5423.  This chapter describes preprocessor directives─commands that control the
  5424.  QuickC compiler. It explains how to insert the contents of one source file
  5425.  into another file, how to do text substitutions throughout a file, and how
  5426.  to compile different parts of a file in different situations.
  5427.  
  5428.  A "preprocessor directive" is a command to the QuickC compiler. Although
  5429.  they appear in the same source file as executable statements, preprocessor
  5430.  directives aren't statements in the formal sense. Unlike executable
  5431.  statements, they are not translated into machine code. Instead, they tell
  5432.  the compiler itself to take some action while it translates your source
  5433.  program. For instance, an #include directive tells QuickC to insert another
  5434.  file into the source file.
  5435.  
  5436.  The term "preprocessor" refers to the time when these commands are carried
  5437.  out. Like most language compilers, QuickC translates your source program in
  5438.  several phases, the first of which is called the "preprocessor phase."
  5439.  QuickC first "preprocesses" all the directives in your source program, then
  5440.  processes the program's executable statements.
  5441.  
  5442.  All preprocessor directives begin with a number sign (#), which must be the
  5443.  first nonblank character in the line on which it appears. Since directives
  5444.  aren't statements, they don't end with semicolons. You can't put other
  5445.  statements or directives on the same line with a preprocessor directive,
  5446.  except for a comment, which must appear to the right of the directive.
  5447.  
  5448.  Because the compiler reads your source file sequentially, line by line, the
  5449.  position of directives is important. A preprocessor directive only affects
  5450.  statements that follow it in the source file.
  5451.  
  5452.  
  5453.  The #include Directive
  5454.  
  5455.   The #include directive inserts another file in the source file.
  5456.  
  5457.  The #include directive inserts the contents of another file into your source
  5458.  file. The inserted file is called an include file or header file.
  5459.  
  5460.  When the compiler encounters an #include, it searches for the file named in
  5461.  the directive. This directive makes QuickC look for the standard include
  5462.  file STDIO.H:
  5463.  
  5464.    #include <stdio.h>
  5465.  
  5466.  If the designated file is found, the compiler inserts its contents at the
  5467.  spot where the #include directive appears. Figure 7.1 illustrates a program
  5468.  SAMPLE.C that includes the file STDIO.H.
  5469.  
  5470.  (This figure may be found in the printed book.)
  5471.  
  5472.  When QuickC compiles the SAMPLE.C program shown in Figure 7.1, it inserts
  5473.  the contents of file STDIO.H into SAMPLE.C at the spot marked by the
  5474.  #include directive.
  5475.  
  5476.  Most include files contain commonly used declarations and definitions.
  5477.  Standard include files, supplied with QuickC, contain declarations and
  5478.  definitions for QuickC library routines. You can also write include files of
  5479.  your own.
  5480.  
  5481.  Standard include files end with the .H file extension (STDIO.H is an
  5482.  example). You can use any extension for include files you create, but most
  5483.  programmers stick with the .H extension.
  5484.  
  5485.  ────────────────────────────────────────────────────────────────────────────
  5486.  NOTE
  5487.  
  5488.  In some languages, it's common to put executable statements, as well as
  5489.  declarations and definitions, in include files. This practice is legal but
  5490.  not recommended in QuickC. Microsoft debugging tools such as the Microsoft
  5491.  CodeView(R) debugger may not recognize executable statements in include
  5492.  files.
  5493.  ────────────────────────────────────────────────────────────────────────────
  5494.  
  5495.  The #include directive doesn't support wild cards, so you can't insert a
  5496.  group of related files with a single directive. Each #include directive
  5497.  inserts only one file.
  5498.  
  5499.  Include files can be nested. For instance, the source program SAMPLE.C might
  5500.  include a file named INOUT.H. The INOUT.H file, in turn, might contain a
  5501.  second #include directive that includes a file named KEYBOARD.H. Figure 7.2
  5502.  illustrates this process.
  5503.  
  5504.  (This figure may be found in the printed book.)
  5505.  
  5506.  Although it's rarely necessary to nest include files more than two or three
  5507.  levels, nesting may continue up to 10 levels.
  5508.  
  5509.  
  5510.  Specifying Include Files
  5511.  
  5512.  There are two ways to tell QuickC where to search for an include file. You
  5513.  may have noticed that the #include directive shown earlier encloses the file
  5514.  name STDIO.H in angle brackets (<>). If you enclose the file name in angle
  5515.  brackets, as in the directive
  5516.  
  5517.    #include <stdio.h>
  5518.  
  5519.  the compiler searches the "standard directories" for the file.
  5520.  
  5521.  In QuickC, the standard directories are one or more directories that you
  5522.  define by a DOS environment variable named INCLUDE. An advantage of
  5523.  specifying the standard directories is that QuickC can automatically search
  5524.  more than one directory.
  5525.  
  5526.  Alternatively, you can enclose the file name in double quotes, in the
  5527.  following manner,
  5528.  
  5529.    #include "myfile.h"
  5530.  
  5531.  to cause QuickC to start searching in the directory that contains the
  5532.  current source file. If the target file isn't in that directory, the
  5533.  compiler searches the standard directories.
  5534.  
  5535.  ────────────────────────────────────────────────────────────────────────────
  5536.  NOTE
  5537.  
  5538.  You can specify additional directories on the DOS command line when you
  5539.  invoke QuickC with the QCL command. See Chapter 1, "Creating Executable
  5540.  Programs," in the Microsoft QuickC Tool Kit.
  5541.  ────────────────────────────────────────────────────────────────────────────
  5542.  
  5543.  
  5544.  The #define and #undef Directives
  5545.  
  5546.  The #define directive performs a text substitution in the source file. This
  5547.  directive has two main uses: simple text replacement and creation of
  5548.  function-like macros. It is also used with the #undef directive to control
  5549.  conditional compilation, as we'll discuss later.
  5550.  
  5551.  
  5552.  Simple Text Replacement
  5553.  
  5554.   The #define directive works  like the search and replace  function of a
  5555.  word processor.
  5556.  
  5557.  At the simplest level, the #define directive works much like the "search and
  5558.  replace" function of a word processor, replacing one piece of text in the
  5559.  source file with another piece of text. The #define directive is commonly
  5560.  used to create a symbolic constant─a meaningful name for a "magic number"
  5561.  whose meaning might not otherwise be apparent. This improves the program's
  5562.  readability.
  5563.  
  5564.  For instance, in the VOLUME.C program in Chapter 1, "Anatomy of a C
  5565.  Program," the directive
  5566.  
  5567.    #define PI 3.14
  5568.  
  5569.  defines a symbolic constant named  PI. The directive causes QuickC to
  5570.  replace every occurrence of the text  PI  in the VOLUME.C source program
  5571.  with the text  3.14. For example, when the compiler encounters the program
  5572.  line
  5573.  
  5574.    result = 4 * PI * result;
  5575.  
  5576.  it expands the line to read
  5577.  
  5578.    result = 4 * 3.14 * result;
  5579.  
  5580.  Besides making your program more readable, symbolic constants can streamline
  5581.  its maintenance. For instance, say you later decide to use 3.14159265 rather
  5582.  than 3.14 in VOLUME.C. All you need to change is one #define directive at
  5583.  the beginning of the program.
  5584.  
  5585.  The replacement text can be longer than the 3.14159265 we used above. A
  5586.  replacement text can't be longer than 512 bytes in QuickC, but you'll
  5587.  rarely, if ever, have to worry about this limit.
  5588.  
  5589.  
  5590.  Function-Like Macros
  5591.  
  5592.   A function-like macro accepts arguments, like a function.
  5593.  
  5594.  Some languages use the term "macro" when referring to replacement text. In
  5595.  C, a macro can do more than simply replace text. It can also accept
  5596.  arguments in much the same way that a function does. In this case the
  5597.  replacement text is called a "function-like macro."
  5598.  
  5599.  A well-designed macro can be every bit as useful as a function. In fact,
  5600.  some C library routines are implemented as macros rather than C functions.
  5601.  
  5602.  The MACRO.C program below has a macro that works like the abs library
  5603.  function, returning the absolute value of any integer. The macro uses the
  5604.  conditional operator (? :), which we explained in Chapter 6.
  5605.  
  5606.    /* MACRO.C: Demonstrate macros. */
  5607.  
  5608.    #include <stdio.h>
  5609.    #define ABS(value)  ( (value) >= 0 ? (value) : -(value) )
  5610.  
  5611.    main()
  5612.    {
  5613.       int val = -20;
  5614.       printf( "result = %d\n", ABS(val) );
  5615.    }
  5616.  
  5617.  The  ABS  macro behaves much like a function. You can "call" it by name,
  5618.  passing it an argument you want to process. The macro is defined in the
  5619.  following program line:
  5620.  
  5621.    #define ABS(value)  ( (value) >= 0 ? (value) : -(value) )
  5622.  
  5623.  The parameter  value  appears four times in the macro─once in the macro name
  5624.   ABS  and three times in the replacement text that follows the name.
  5625.  
  5626.   Always enclose macro parameters in parentheses.
  5627.  
  5628.  To avoid unwanted side effects, you should always enclose macro parameters
  5629.  in parentheses. If the parameter passed to the  ABS  macro is an expression
  5630.  containing operators, the lack of parentheses could cause
  5631.  operator-precedence errors. See the section "Omitting Parentheses from Macro
  5632.  Arguments" in Chapter 10, "Programming Pitfalls."
  5633.  
  5634.  Function-like macros, like other #define directives, are expanded during the
  5635.  preprocessor phase of compilation, before QuickC translates any executable
  5636.  statements. When QuickC encounters the line
  5637.  
  5638.    printf( "result= %d\n", ABS(val) );
  5639.  
  5640.  it expands it to read:
  5641.  
  5642.    printf( "result= %d\n", ( (val) >= 0 ? (val) : -(val) ) );
  5643.  
  5644.   Macros can improve readability.
  5645.  
  5646.  A macro can improve a program's readability by describing the nature of an
  5647.  operation while hiding its complex details. Most people find the first of
  5648.  the two statements above easier to understand than the expanded version.
  5649.  
  5650.   Macros are faster than functions but can make  a program bigger.
  5651.  
  5652.  Function-like macros are fast, too. Since a macro creates in-line code, it
  5653.  doesn't have the overhead associated with a normal function call. On the
  5654.  other hand, each use of a macro inserts the same code in your program,
  5655.  whereas a function definition occurs only once. So while macros can be
  5656.  faster than functions, they can also bloat the size of the executable file.
  5657.  
  5658.  
  5659.  
  5660.  The #undef Directive
  5661.  
  5662.  The "#undef directive" is related to #define. As the name suggests, #undef
  5663.  removes ("undefines") a name that was created with #define. For instance, if
  5664.  you create the symbolic constant  PI  with the #define directive,
  5665.  
  5666.    #define PI  3.14
  5667.  
  5668.  you can then remove the name  PI  with the following #undef directive:
  5669.  
  5670.    #undef PI
  5671.  
  5672.  You can use #define and #undef to create a name that has meaning in only
  5673.  part of a source program. The next two sections explain why you might want
  5674.  to do this.
  5675.  
  5676.  
  5677.  Conditional Directives
  5678.  
  5679.   Conditional directives are useful for making different versions of a
  5680.  program.
  5681.  
  5682.  Conditional directives can make QuickC skip part of a source file. They are
  5683.  used primarily to create different versions of a program. While developing a
  5684.  program, for instance, you might want to include debugging code at some
  5685.  times but not others. Or, if you plan to move a program to some other
  5686.  machine, you can compile machine-specific sections of code only for a
  5687.  certain machine.
  5688.  
  5689.  The C-language conditional directives are listed below.
  5690.  
  5691.  #if                               #endif
  5692.  #else                             #ifdef
  5693.  #elif                             #ifndef
  5694.  
  5695.  ────────────────────────────────────────────────────────────────────────────
  5696.  NOTE
  5697.  
  5698.  The #ifdef and #ifndef directives are obsolete under the ANSI C standard;
  5699.  see "The defined Operator" below.
  5700.  ────────────────────────────────────────────────────────────────────────────
  5701.  
  5702.   The #if directive works  like the if statement.
  5703.  
  5704.  The #if and #endif directives work like an if statement, allowing you to
  5705.  compile a block of source code if a given condition is true. The #if
  5706.  directive is followed by a constant expression, which the compiler tests at
  5707.  compile time. If the expression is false, the compiler skips every line
  5708.  between the #if and the next #endif.
  5709.  
  5710.  The example below calls the  display  function only if the name  DEBUG  was
  5711.  previously defined as 1 (with #define).
  5712.  
  5713.    #if DEBUG == 1
  5714.       display( debuginfo );
  5715.    #endif
  5716.  
  5717.  Here, the "conditional block" is a single line (the  display  function
  5718.  call). A conditional block can contain any number of valid C program lines,
  5719.  including preprocessor directives as well as executable statements.
  5720.  
  5721.  The test expression for a conditional directive can be almost any expression
  5722.  that evaluates to a constant, with a few minor exceptions (the expression
  5723.  can't use the sizeof operator, type casts, or the float and enum types).
  5724.  
  5725.   The #else directive works  like the else keyword.
  5726.  
  5727.  The #else and #elif directives work like the else keyword and can perform
  5728.  more complex conditional tests. For example, you could use code like that in
  5729.  the following example to build different versions of a program for various
  5730.  IBM PC computers, including different files for each computer.
  5731.  
  5732.    #if XT == 1
  5733.       #include "XT.H"
  5734.    #elif AT == 1
  5735.       #include "AT.H"
  5736.    #else
  5737.       #include "PS2.H"
  5738.    #endif
  5739.  
  5740.  The code includes the file XT.H if the name  XT  is defined as 1 and it
  5741.  includes the file AT.H if the name  AT  is defined as 1. If both  XT  and
  5742.  AT  are undefined, the third conditional block executes, causing QuickC to
  5743.  include the file PS2.H.
  5744.  
  5745.  You can nest conditional directives in the same way as you would conditional
  5746.  C language statements.
  5747.  
  5748.  
  5749.  The defined Operator
  5750.  
  5751.   The defined operator  tests whether a name  has been defined.
  5752.  
  5753.  The test expression of an #if or #elif directive can use the defined
  5754.  operator to test whether a name has been defined. You can use this feature,
  5755.  along with #define and #undef, to turn various parts of a program on and
  5756.  off, compiling different parts under different conditions.
  5757.  
  5758.  The defined operator is true if its argument has been defined and false
  5759.  otherwise. A name is considered defined if it has been created with #define
  5760.  (and not later removed with #undef).
  5761.  
  5762.  The DEFINED.C program below prints  Hi  because the name  DEBUG  is defined
  5763.  when the compiler encounters the #if defined directive.
  5764.  
  5765.    /* DEFINED.C: Demonstrate defined operator. */
  5766.  
  5767.    #define DEBUG 12345
  5768.  
  5769.    main()
  5770.    {
  5771.       #if defined( DEBUG )
  5772.          printf( "Hi\n" );
  5773.       #endif
  5774.    }
  5775.  
  5776.  The defined operator tests only whether a name is defined, not whether it
  5777.  has a certain value. Thus, the DEFINED.C program will print  Hi  no matter
  5778.  what value is assigned  DEBUG. You could substitute the directive
  5779.  
  5780.    #define DEBUG 0
  5781.  
  5782.  to define  DEBUG  as 0, or the directive
  5783.  
  5784.    #define DEBUG
  5785.  
  5786.  to define  DEBUG  as having no value at all. Both directives define the name
  5787.   DEBUG, so the program would print  Hi  in both cases.
  5788.  
  5789.  You can use the logical NOT operator (!) to reverse the logic of an #if
  5790.  defined directive. (Logical operators are explained in Chapter 6.) The code
  5791.  
  5792.  
  5793.    #if !defined( DEBUG )
  5794.       printf( "Hi\n");
  5795.    #endif
  5796.  
  5797.  prints  Hi  if  DEBUG  is not currently defined.
  5798.  
  5799.  A plain #if directive treats undefined names a little differently than does
  5800.  an #if defined directive. If a name is not currently defined, the #if
  5801.  directive treats the name as having the value 0.
  5802.  
  5803.  In the following code, the #if directive explicitly tests whether  DEBUG
  5804.  equals 0.
  5805.  
  5806.    #undef DEBUG
  5807.    #if DEBUG == 0
  5808.       printf( "Hi\n" );
  5809.    #endif
  5810.  
  5811.  The result is the same as that of the previous example.
  5812.  
  5813.  ────────────────────────────────────────────────────────────────────────────
  5814.  NOTE
  5815.  
  5816.  The defined operator is new under the ANSI C standard. You may see older
  5817.  programs that use the older directives #ifdef and #ifndef for the same
  5818.  purpose. These directives are obsolete, but QuickC version 2.5 supports them
  5819.  for the sake of compatibility. The #ifdef directive is followed by a name
  5820.  (not in parentheses) and works the same as #if with defined. If the given
  5821.  name has been defined, #ifdef is true. The #ifndef directive is the opposite
  5822.  of #ifdef. It is true if the given name is not currently defined.
  5823.  ────────────────────────────────────────────────────────────────────────────
  5824.  
  5825.  
  5826.  Pragmas
  5827.  
  5828.    Pragmas are implementationspecific compiler commands.
  5829.  
  5830.  Although portability is a hallmark of C, the language's creators recognized
  5831.  that every C compiler will need to support some features unique to its host
  5832.  machine. The "#pragma directive" offers a way for each C compiler to offer
  5833.  machine-specific features while retaining overall compatibility with the C
  5834.  language. Since pragmas are machine-specific by definition, they can be─and
  5835.  usually are─different for every C compiler.
  5836.  
  5837.  Pragmas have the same general syntax as preprocessor directives. The pragma
  5838.  must begin with a number sign (#) and it can't share a line with other
  5839.  directives or statements except a comment, which must appear to the right of
  5840.  the pragma.
  5841.  
  5842.  QuickC supports four pragmas: check_stack, check_pointer, message, and pack.
  5843.  Each of these pragmas is described in online help.
  5844.  
  5845.  Some pragmas take arguments, which come after the #pragma keyword. In the
  5846.  following code, the message pragma displays different messages during
  5847.  compilation depending on the outcome of an #if test:
  5848.  
  5849.    #if XT == 1
  5850.       #pragma message( "Building XT version" )
  5851.    #elif AT == 1
  5852.       #pragma message( "Building AT version" )
  5853.    #endif
  5854.  
  5855.  The message displayed by the message pragma is visible only if you compile
  5856.  from the DOS command line with the QCL command.
  5857.  
  5858.  
  5859.  
  5860.  
  5861.  
  5862.  
  5863.  Chapter 8  Pointers
  5864.  ────────────────────────────────────────────────────────────────────────────
  5865.  
  5866.  The next two chapters explain pointers─a large and important topic in C.
  5867.  This chapter explains fundamental techniques: how to use pointers with
  5868.  various data types and pass them to functions. In Chapter 9, "Advanced
  5869.  Pointers," we'll explore more advanced pointer techniques, such as multiple
  5870.  indirection.
  5871.  
  5872.  If you have never used pointers before, you may want to read this chapter
  5873.  now and then turn to Chapter 9 after you have had some practice using
  5874.  pointers in your own programs.
  5875.  
  5876.   Don't panic!
  5877.  
  5878.  There's a lot of new information in these two chapters. Don't be discouraged
  5879.  if you don't grasp it all on a first reading. The idea behind a pointer is
  5880.  simple, but some advanced pointer techniques are not so easy to follow at
  5881.  first.
  5882.  
  5883.  
  5884.  Using Pointers in C
  5885.  
  5886.  Almost every real-world C program uses pointers in some way or another. Much
  5887.  of the usefulness of pointers stems from the fact that in C all function
  5888.  arguments are passed by value. Because a function only receives local copies
  5889.  of such arguments, it can't change the original values that the arguments
  5890.  represent. Pointers make this possible.
  5891.  
  5892.  Here are some common uses of pointers:
  5893.  
  5894.  
  5895.    ■   Manipulating strings
  5896.  
  5897.    ■   Passing command-line arguments to a program at run time
  5898.  
  5899.    ■   Returning more than one value from a function
  5900.  
  5901.    ■   Accessing variables that wouldn't otherwise be visible to a function
  5902.  
  5903.    ■   Manipulating an array by moving pointers to its elements instead of
  5904.        using array subscripting
  5905.  
  5906.    ■   Accessing the address of a memory area that your program allocates at
  5907.        run time
  5908.  
  5909.    ■   Passing the address of one function to another function
  5910.  
  5911.  
  5912.  
  5913.  Pointers to Simple Variables
  5914.  
  5915.   A pointer variable contains the address of a data object.
  5916.  
  5917.  Although pointers have many different uses, it takes only a few words to say
  5918.  what a pointer is. A "pointer" is a variable that contains the address of
  5919.  some other data object─usually a variable. Because a pointer contains the
  5920.  other variable's address, it is said to "point to" that variable.
  5921.  
  5922.  This section uses the program POINTER.C to demonstrate the basic mechanics
  5923.  of pointers─how to declare and initialize a pointer and use it to access a
  5924.  simple variable:
  5925.  
  5926.    /* POINTER.C: Demonstrate pointer basics. */
  5927.  
  5928.    #include <stdio.h>
  5929.  
  5930.    main()
  5931.    {
  5932.       int val = 25;
  5933.       int *ptr;
  5934.       ptr = &val;
  5935.       printf( " val = %d\n", val );
  5936.       printf( "*ptr = %d\n\n", *ptr );
  5937.       printf( "&val = %u\n", &val );
  5938.       printf( " ptr = %d\n", ptr );
  5939.    }
  5940.  
  5941.  Here is the output from POINTER.C:
  5942.  
  5943.    val = 25
  5944.    *ptr = 25
  5945.  
  5946.    &val = 5308
  5947.     ptr = 5308
  5948.  
  5949.  (The third and fourth output lines show addresses. These may differ when you
  5950.  run POINTER.C depending on factors such as available memory.)
  5951.  
  5952.  POINTER.C creates a pointer variable named  ptr  and makes  ptr  point to an
  5953.  int variable named  val. Then it prints the two values to show that  ptr
  5954.  can access the value stored in  val. The program goes on to print the
  5955.  address where  val  is stored and the address contained in  ptr, to show
  5956.  they are the same.
  5957.  
  5958.  
  5959.  Declaring a Pointer Variable
  5960.  
  5961.  Like any variable, a pointer variable must be declared before it is used,
  5962.  and its value can change in the course of a program. A pointer variable can
  5963.  have any legal variable name. Here is the pointer declaration from
  5964.  POINTER.C:
  5965.  
  5966.    int *ptr;
  5967.  
  5968.  This declaration states the program has a pointer variable named  ptr  that
  5969.  can point to a data object of the int type.
  5970.  
  5971.  Notice the similarity to a simple variable declaration. As in other cases,
  5972.  the declaration gives a type (int) and name ( ptr ) for the variable.
  5973.  
  5974.   Use the indirection  operator ( *) to declare  a pointer variable.
  5975.  
  5976.  The indirection operator (*) in front of the name  ptr  shows this variable
  5977.  is a pointer. This operator has two different uses in C. In declarations,
  5978.  such as the one above, it simply means "this is a pointer." In other
  5979.  contexts, as we'll elaborate throughout this chapter, it means
  5980.  indirection─using the data object that a pointer points to.
  5981.  
  5982.   A pointer declaration shows what type of data object a pointer references.
  5983.  
  5984.  
  5985.  A pointer doesn't have a type in the same sense as other variables. When you
  5986.  declare a simple variable, the type specifier shows what type of value the
  5987.  variable stores. When you declare a pointer variable, the type specifier
  5988.  shows what type of data object the pointer points to.
  5989.  
  5990.  Thus, in POINTER.C the declaration of the variable  val  indicates  val
  5991.  stores a value of the type int,
  5992.  
  5993.    int val = 25;
  5994.  
  5995.  while the declaration of the variable  ptr  indicates it points to a data
  5996.  object of the type int:
  5997.  
  5998.    int *ptr;
  5999.  
  6000.  To declare pointers to other types of variables, you can use whatever type
  6001.  specifier is appropriate. These statements, for instance, declare pointers
  6002.  to char and float variables:
  6003.  
  6004.    char *c_ptr, *ch;
  6005.    float *f_pointer;
  6006.  
  6007.  Note that if you declare more than one pointer variable in the same line,
  6008.  each name must be preceded by the indirection operator. The first line in
  6009.  the previous example declares two pointer variables:  c_ptr  and  ch. Each
  6010.  pointer can point to an object of the char type. If you omit the second
  6011.  indirection operator from the first line,
  6012.  
  6013.    char *c_ptr, ch;
  6014.  
  6015.  the line declares a pointer variable named  c_ptr  and an ordinary char
  6016.  variable named  ch.
  6017.  
  6018.   A pointer declared with type void can point to any type of data object.
  6019.  
  6020.  In most cases a pointer points to a particular type of object, such as an
  6021.  int. You can also declare a pointer with type void, which allows it to point
  6022.  to any type of object.
  6023.  
  6024.  One use of void pointers is to write a general-purpose function, such as a
  6025.  sort, that can operate on data of more than one type. Each time you use a
  6026.  void pointer, you must perform an explicit type cast to show what type of
  6027.  object it points to on that occasion.
  6028.  
  6029.  Figure 8.1 shows the relationship between  val  and  ptr  in POINTER.C,
  6030.  immediately after  ptr  has been declared. The figure shows that the
  6031.  variable  val  is stored at memory location 5308, as in the output shown
  6032.  above. Again, the actual address may differ when you run POINTER.C.
  6033.  
  6034.  (This figure may be found in the printed book.)
  6035.  
  6036.  Figure 8.1 uses question marks to show that the contents of  ptr  are
  6037.  undefined at this stage in the program. Like any other variable that has
  6038.  been declared but not initialized, the contents of  ptr  are unknown. You
  6039.  must take special care not to use pointers that have not been initialized,
  6040.  since an uninitialized pointer might point anywhere in memory─including
  6041.  sensitive operating-system addresses.
  6042.  
  6043.  ────────────────────────────────────────────────────────────────────────────
  6044.  WARNING
  6045.  
  6046.  Because a pointer can potentially access any memory address, using an
  6047.  uninitialized pointer can have drastic consequences.
  6048.  ────────────────────────────────────────────────────────────────────────────
  6049.  
  6050.  
  6051.  How Pointers Are Stored
  6052.  
  6053.  Figure 8.1 also shows that while a pointer is a special kind of variable, it
  6054.  is not a mysterious entity floating in limbo. A pointer is a true variable
  6055.  whose contents are stored at a specific memory address.
  6056.  
  6057.  In POINTER.C we don't care precisely where the pointer's contents are
  6058.  stored─the compiler handles that detail for us, as it does so many others.
  6059.  So Figure 8.1 does not include the address of the storage for  ptr. It does
  6060.  show, however, that the pointer is stored in two bytes, the same amount of
  6061.  memory needed to store an int value.
  6062.  
  6063.  ────────────────────────────────────────────────────────────────────────────
  6064.  NOTE
  6065.  
  6066.  The actual amount of memory needed to store a pointer variable depends on
  6067.  the current "memory model." In the small memory model─the default for QuickC
  6068.  version 2.5─a pointer is stored in two bytes. In some larger memory models,
  6069.  a pointer is stored in four bytes. For purposes of discussion, this chapter
  6070.  and the following chapter assume the small memory model. Appendix B,
  6071.  "Working with QuickC Memory Models," in the Microsoft QuickC Tool Kit
  6072.  discusses memory models.
  6073.  ────────────────────────────────────────────────────────────────────────────
  6074.  
  6075.  
  6076.  Initializing a Pointer Variable
  6077.  
  6078.  The next step in the POINTER.C program is to initialize the pointer variable
  6079.   ptr, making it point to some meaningful address in memory:
  6080.  
  6081.    ptr = &val;
  6082.  
  6083.  The "address-of operator" (&) gives the address of the name it precedes. So
  6084.  in plain English the above statement says, "assign the address of  val  to
  6085.  ptr."
  6086.  
  6087.  After its initialization, the variable  ptr  points to  val  in the sense
  6088.  that it contains the address where  val  is stored.
  6089.  
  6090.  The output from POINTER.C shows that  ptr  contains the address of  val.
  6091.  First it prints the address of  val  using the address-of operator to
  6092.  directly obtain the variable's address,
  6093.  
  6094.    &val = 5308
  6095.  
  6096.  then it prints the contents of  ptr:
  6097.  
  6098.    ptr = 5308
  6099.  
  6100.  The two values are identical. Figure 8.2 shows the relationship of  val  and
  6101.   ptr  at this stage in the POINTER.C program.
  6102.  
  6103.  (This figure may be found in the printed book.)
  6104.  
  6105.  Initialization is especially important for pointers because, as noted
  6106.  earlier, they have the potential to point anywhere in memory. If you forget
  6107.  to initialize it, or make it point to the wrong place, a pointer can wreak
  6108.  havoc with your program or even the operating system itself.
  6109.  
  6110.   The target of a pointer  must be present in  memory at run time.
  6111.  
  6112.  The pointer in POINTER.C points to a simple int variable. As a general rule,
  6113.  pointers can point to any data object that is present in memory at run time.
  6114.  This category mainly includes objects for which the program allocates (sets
  6115.  aside) memory. Memory can be allocated implicitly, by defining a variable or
  6116.  function, or explicitly, by calling a memory-allocating library function
  6117.  such as malloc.
  6118.  
  6119.  A pointer can't point to program elements such as expressions or register
  6120.  variables, which aren't present in addressable memory.
  6121.  
  6122.  POINTER.C initializes the pointer  ptr  by assigning it an address constant
  6123.  (the address of  val, obtained with the address-of operator). You can also
  6124.  assign the value of one pointer to another, as shown here:
  6125.  
  6126.    ptr = ptr1;
  6127.  
  6128.  If  ptr  and  ptr1  are both pointers, this statement assigns the address
  6129.  contained in  ptr1  to  ptr.
  6130.  
  6131.  
  6132.  Using a Pointer Variable
  6133.  
  6134.  Once  ptr  points to  val, we have two ways to access the int value stored
  6135.  in  val. The usual way is direct, using the name of  val:
  6136.  
  6137.    printf( " val = %d\n", val );
  6138.  
  6139.  The second way to access  val  is indirect, using the pointer variable  ptr
  6140.  and the indirection operator:
  6141.  
  6142.    printf( "*ptr = %d\n\n", *ptr );
  6143.  
  6144.  Both of the preceding statements print the value of  val, confirming that
  6145.  you can access the contents of  val  indirectly as well as directly. Once
  6146.  ptr  points to  val  you can use  *ptr  anywhere that you would use  val.
  6147.  
  6148.   The indirection operator can obtain the value to which a pointer points.
  6149.  
  6150.  Using the indirection operator to access the contents of  val  is the second
  6151.  use of this operator (the first is in declaring pointer variables, as
  6152.  explained earlier). When the asterisk appears in front of the name  ptr, the
  6153.  expression states that you want to use the value the pointer points to, not
  6154.  the value of  ptr  itself.
  6155.  
  6156.  The second printf statement in POINTER.C uses the expression  *ptr  to
  6157.  access the value stored in  val.
  6158.  
  6159.  This use of a pointer is analogous to the PEEK function in QuickBASIC. You
  6160.  can just as easily use  ptr  to change the data in  val, an operation that
  6161.  somewhat resembles a QuickBASIC POKE statement.
  6162.  
  6163.  For instance, if you add the following statements to the end of POINTER.C,
  6164.  
  6165.    *ptr = 3301;
  6166.    printf( "%d\n", val );
  6167.  
  6168.  the program prints  3301.
  6169.  
  6170.  Figure 8.3 shows the relationship between  ptr  and  val  after executing
  6171.  the previous two statements.
  6172.  
  6173.  (This figure may be found in the printed book.)
  6174.  
  6175.  As Figure 8.3 shows, the value stored in  val  has changed from 25 to 3301.
  6176.  The contents of  val  were changed indirectly, through the pointer  ptr.
  6177.  
  6178.  
  6179.  Summary of Pointer Basics
  6180.  
  6181.  In the preceding sections, you have seen how to do these operations:
  6182.  
  6183.  
  6184.    ■   Declare a pointer to a simple variable
  6185.  
  6186.    ■   Initialize a pointer, making it point to a variable
  6187.  
  6188.    ■   Use a pointer to get the value of a variable
  6189.  
  6190.    ■   Use a pointer to change the contents of a variable
  6191.  
  6192.  
  6193.  It's important for you to be comfortable with these basic ideas before
  6194.  reading about the more advanced uses of pointers. If you're not sure you
  6195.  understand these concepts, you may want to experiment with the POINTER.C
  6196.  program to reinforce what you know. For instance, you might add some new
  6197.  variables of different types and create new pointers to access them.
  6198.  
  6199.  
  6200.  Pointers to Arrays
  6201.  
  6202.  Pointers and arrays are closely related in C─a major theme we'll elaborate
  6203.  throughout the rest of this chapter and Chapter 9, "Advanced Pointers." This
  6204.  section explains one of the simpler ways to use pointers with arrays.
  6205.  
  6206.  A pointer to an array, or "array pointer," combines two powerful language
  6207.  features─the pointer's ability to provide indirect access and the
  6208.  convenience of accessing array elements through numerical subscripts.
  6209.  
  6210.   An array pointer can point to any element in a given array.
  6211.  
  6212.  A pointer to an array is not much different than a pointer to a simple
  6213.  variable. In both cases, the pointer can point only to a single object at
  6214.  any given time. An array pointer, however, can reference any individual
  6215.  element within an array (but just one at a time).
  6216.  
  6217.  The program PARRAY.C shows how to access the elements of an int array
  6218.  through a pointer:
  6219.  
  6220.    /* PARRAY.C: Demonstrate pointer to array. */
  6221.  
  6222.    #include <stdio.h>
  6223.  
  6224.    int i_array[] = { 25, 300, 2, 12 };
  6225.  
  6226.    main()
  6227.    {
  6228.       int *ptr;
  6229.       int count;
  6230.       ptr = &i_array[0];
  6231.  
  6232.    for( count = 0; count < 4 ; count++ )   {
  6233.          printf( "i_array[%d] = %d\n", count, *ptr );
  6234.          ptr++;
  6235.       }
  6236.    }
  6237.  
  6238.  Here is the output from PARRAY.C:
  6239.  
  6240.    i_array[0] = 25
  6241.    i_array[1] = 300
  6242.    i_array[2] = 2
  6243.    i_array[3] = 12
  6244.  
  6245.  The PARRAY.C program creates a four-element int array named  i_array. Then
  6246.  it declares a pointer named  ptr  and uses  ptr  in a for loop to access
  6247.  each of the elements in  i_array.
  6248.  
  6249.  Notice the similarity between PARRAY.C and the previous example (POINTER.C).
  6250.  The pointer is declared in the same way:
  6251.  
  6252.    int *ptr;
  6253.  
  6254.  As noted before, this declaration states that  ptr  can point to any object
  6255.  of the int type, which includes an element in an int array as well as a
  6256.  simple int. The initialization of  ptr  looks similar, too:
  6257.  
  6258.    ptr = &i_array[0];
  6259.  
  6260.  This statement assigns  ptr  the address of the first element of  i_array,
  6261.  which is  i_array[0]. (There's a more compact way to initialize this
  6262.  pointer, but we'll defer that discussion for a moment.) Figure 8.4 shows the
  6263.  relationship between  ptr  and  i_array  immediately after  ptr  is
  6264.  initialized.
  6265.  
  6266.  (This figure may be found in the printed book.)
  6267.  
  6268.  
  6269.  Arrays and Pointer Arithmetic
  6270.  
  6271.  Once a pointer points to an array, it can access any of the array's
  6272.  elements. By adding or subtracting from the pointer's value (using "pointer
  6273.  arithmetic") you can access any element in the array, just as you can access
  6274.  it with array subscripts.
  6275.  
  6276.  So in PARRAY.C, just as in POINTER.C, we can use  *ptr  to access the int
  6277.  value that  ptr  references. The only difference is now  ptr  points to an
  6278.  array element instead of a simple variable.
  6279.  
  6280.  When the for loop in PARRAY.C executes the first time,  ptr  points to the
  6281.  first element of  i_array, which is  i_array[0]. The second statement in the
  6282.  loop body,
  6283.  
  6284.    ptr++;
  6285.  
  6286.  increments the pointer. Now  ptr  points to the next element in  i_array,
  6287.  which is  i_array[1]. Figure 8.5 shows the relationship of  ptr  and
  6288.  i_array  after the first iteration of the for loop in PARRAY.C.
  6289.  
  6290.  (This figure may be found in the printed book.)
  6291.  
  6292.  Figures 8.4 and 8.5 illustrate another important fact about pointers.
  6293.  Pointer arithmetic is automatically scaled to the size of the object that a
  6294.  pointer references. As explained above, incrementing  ptr  with the
  6295.  statement
  6296.  
  6297.    ptr++;
  6298.  
  6299.   Pointer arithmetic is scaled to the size of  elements in an array.
  6300.  
  6301.  moves the pointer forward to the next element in  i_array. Since each
  6302.  element of an int array contains two bytes, this operation actually adds 2
  6303.  to the address stored in  ptr, but you don't have to worry about that
  6304.  detail. The compiler knows the size of the elements in the array and adjusts
  6305.  the pointer accordingly.
  6306.  
  6307.  Incrementing a pointer adds 1 if it points to a char array, 4 if it points
  6308.  to a float array, and so on.
  6309.  
  6310.  You can also decrement an array pointer. If  ptr  points to  i_array[2],
  6311.  this statement moves the pointer back one element, to  i_array[1]:
  6312.  
  6313.    ptr--;
  6314.  
  6315.  Although the previous expressions increment and decrement  ptr  by 1, you
  6316.  can add or subtract any integer value from a pointer. For instance, the
  6317.  following statement moves  ptr  forward three elements in  i_array:
  6318.  
  6319.    ptr += 3;
  6320.  
  6321.  Be careful not to overrun the bounds of an array when accessing its elements
  6322.  with a pointer. As noted in Chapter 4, "Data Types," the C language doesn't
  6323.  check array subscripts. This rule applies equally when you access an array
  6324.  with a pointer, which can potentially reference any address in memory.
  6325.  
  6326.  ────────────────────────────────────────────────────────────────────────────
  6327.  WARNING
  6328.  
  6329.  The C language does not check array pointer references. If you increment or
  6330.  decrement a pointer past the limits of an array, you can corrupt other parts
  6331.  of your program or cause other unexpected results.
  6332.  ────────────────────────────────────────────────────────────────────────────
  6333.  
  6334.  It's your job to make sure an increment or decrement doesn't move a pointer
  6335.  outside the memory where an array is stored. For instance, if you decrement
  6336.  ptr  when it points to  i_array[0], it will point to whatever happens to be
  6337.  stored in the int-size memory area below the element  i_array[0].
  6338.  
  6339.  Most pointer arithmetic occurs in connection with arrays, where a numerical
  6340.  index has obvious utility. It's not illegal to do pointer arithmetic on
  6341.  nonarray pointers, but such operations normally serve no purpose. For
  6342.  instance, if you increment a pointer to a simple variable, the pointer no
  6343.  longer points to the variable and becomes useless.
  6344.  
  6345.  
  6346.  Comparing Pointers
  6347.  
  6348.  The special nature of a pointer variable─the fact that it contains an
  6349.  address─ precludes most operations that are legal for other variables.
  6350.  There's no such thing as a fractional memory address, for example. So it
  6351.  wouldn't make sense to divide a pointer, or add a floating-point number to
  6352.  it. The most common pointer operations are assignment, incrementing, and
  6353.  decrementing, as described earlier. You can also compare one pointer to
  6354.  another.
  6355.  
  6356.  If a program allocates memory for a stack, for instance, you might create
  6357.  two pointers that point to different parts of the stack. One pointer can
  6358.  show where the stack begins and the other where it ends. To see how much of
  6359.  the stack is in use, you can subtract the pointers. (A "stack" is a memory
  6360.  area used for temporary storage.)
  6361.  
  6362.   You can compare pointer variables with relational operators or by
  6363.  subtraction.
  6364.  
  6365.  Pointer comparisons can be done with relational operators (such as  ) or by
  6366.  subtracting one pointer from another. Of course, pointer comparisons are
  6367.  meaningful only for pointers that point to the same data object or related
  6368.  objects of the same type.
  6369.  
  6370.  
  6371.  PARRAY.C Revisited
  6372.  
  6373.  Before leaving the PARRAY.C program, we should note that most C programmers
  6374.  would write it more compactly (PARRAY1.C):
  6375.  
  6376.    /* PARRAY1.C: Compact version of PARRAY.C. */
  6377.  
  6378.    #include <stdio.h>
  6379.  
  6380.    int i_array[] = { 25, 300, 2, 12 };
  6381.  
  6382.    main()
  6383.    {
  6384.       int count;
  6385.       int *ptr = i_array;
  6386.       for( count = 0; count < 4 ; count++ )
  6387.          printf( "i_array[%d] = %d\n", count, *ptr++ );
  6388.    }
  6389.  
  6390.   You can declare and initialize a pointer variable  in one statement.
  6391.  
  6392.  The PARRAY1.C program uses several shorthand techniques you can expect to
  6393.  see in C programs. Like other variables, pointers can be initialized at the
  6394.  same time they are declared. The following statement in PARRAY1.C performs
  6395.  both operations:
  6396.  
  6397.    int *ptr = i_array;
  6398.  
  6399.  The statement above is equivalent to these statements:
  6400.  
  6401.    int *ptr;
  6402.    ptr = i_array;
  6403.  
  6404.  You may have noticed another difference in the way  ptr  is initialized. The
  6405.  PARRAY1.C program omits the address-of operator and array subscript that
  6406.  PARRAY.C used to signify the address of the first element of  i_array.
  6407.  Instead of
  6408.  
  6409.    &i_array[0]
  6410.  
  6411.  the program uses
  6412.  
  6413.    i_array
  6414.  
  6415.   An array name is a pointer.
  6416.  
  6417.  In fact, the two expressions are equivalent. In the C language, the name of
  6418.  an array is actually a pointer. Any array name that doesn't have a subscript
  6419.  is interpreted as a pointer to the base address of the array. (The "base
  6420.  address" is the address of the array's first element.) We'll explore this
  6421.  equivalence further in the following sections and in Chapter 9, "Advanced
  6422.  Pointers."
  6423.  
  6424.  Finally, PARRAY1.C uses the expression  *ptr++  to perform two jobs:
  6425.  accessing the value  ptr  points to and incrementing  ptr. Note the order in
  6426.  which the two operators in this expression take effect. The indirection
  6427.  operator takes effect first, accessing the value of the array element that
  6428.  ptr  currently points to. Then the increment operator (++) adds 1 to  ptr,
  6429.  making it point to the next element in  i_array.
  6430.  
  6431.  
  6432.  Pointers and Strings
  6433.  
  6434.   String pointers are handled like other array pointers.
  6435.  
  6436.  Because a string is an array of characters, pointers to strings are handled
  6437.  much like other array pointers. The program PSTRING.C is similar to the
  6438.  examples that demonstrated array pointers (PARRAY.C and PARRAY1.C). It uses
  6439.  a pointer to access a char array:
  6440.  
  6441.    /* PSTRING.C: Demonstrate pointer to a string. */
  6442.  
  6443.    #include <stdio.h>
  6444.  
  6445.    main()
  6446.    {
  6447.       int count;
  6448.       char name[] = "john";
  6449.       char *ptr = name;
  6450.       for( count = 0; count < 4; count++ )
  6451.       {
  6452.          printf( "name[%d]: %c\n", count, *ptr++ );
  6453.       }
  6454.    }
  6455.  
  6456.  The PSTRING.C program steps through the  name  array, printing each
  6457.  character in turn:
  6458.  
  6459.    name[0]: j
  6460.    name[1]: o
  6461.    name[2]: h
  6462.    name[3]: n
  6463.  
  6464.  The notable difference between PARRAY.C and PSTRING.C is that PSTRING.C has
  6465.  a char array instead of an int array. Again, incrementing an array pointer
  6466.  moves the pointer to the next array element. So in PSTRING.C each iteration
  6467.  of the for loop moves the pointer to the next char in the string.
  6468.  
  6469.  The first time through the loop,  ptr  points to  name[0]. The second time
  6470.  it points to  name[1], and so on.
  6471.  
  6472.  As mentioned in Chapter 4, "Data Types," one difference between strings and
  6473.  noncharacter arrays is that strings end with a null character. The string in
  6474.  PSTRING.C actually contains five characters: four letters and a null
  6475.  character. We can exploit this fact to simplify the program, as we do below
  6476.  in PSTRING.C.
  6477.  
  6478.    /* PSTRING1.C: Look for null at string's end.  */
  6479.  
  6480.    #include <stdio.h>
  6481.  
  6482.    main()
  6483.    {
  6484.       char name[] = "john";
  6485.       char *ptr = name;
  6486.       while( *ptr )
  6487.          printf( "*ptr = %c\n", *ptr++ );
  6488.    }
  6489.  
  6490.  Here is the output from PSTRING1.C:
  6491.  
  6492.    *ptr = j
  6493.    *ptr = o
  6494.    *ptr = h
  6495.    *ptr = n
  6496.  
  6497.  Like PSTRING.C, the PSTRING1.C program steps through the array one character
  6498.  at a time. However, it replaces the for loop with a simpler while loop. The
  6499.  test expression in the while loop,
  6500.  
  6501.    while( *ptr )
  6502.  
  6503.  is evaluated as true until  ptr  points to the null character that
  6504.  terminates the string. It's a more compact way of writing this expression:
  6505.  
  6506.    while( *ptr != 0 )
  6507.  
  6508.   Any operation done with array subscripts can also be done with pointer
  6509.  notation.
  6510.  
  6511.  This is an ideal time to elaborate on the relationship between arrays and
  6512.  pointers. Any operation you can do with conventional array notation
  6513.  (subscripts) can also be done with pointers. This is possible because an
  6514.  array name, as we noted earlier, is itself a pointer.
  6515.  
  6516.  To illustrate, the PSTRING2.C program uses only array notation:
  6517.  
  6518.    /* PSTRING2.C: Demonstrate strings and array notation. */
  6519.  
  6520.    #include <stdio.h>
  6521.    #include <string.h>
  6522.  
  6523.    main()
  6524.    {
  6525.       int count;
  6526.       char name[] = "john";
  6527.       for( count = 0; count < strlen( name ); count++ )
  6528.          printf( "name[%d]: %c\n", count, name[count] );
  6529.    }
  6530.  
  6531.  PSTRING2.C gives the same output as PSTRING.C. In this program, the
  6532.  expression
  6533.  
  6534.    name[count]
  6535.  
  6536.  uses  count  as in an index to the  name  array.
  6537.  
  6538.  PSTRING3.C is the same program written with pointer notation:
  6539.  
  6540.    /* PSTRING3.C: Strings and pointer notation.  */
  6541.  
  6542.    #include <stdio.h>
  6543.    #include <string.h>
  6544.  
  6545.    main()
  6546.    {
  6547.       int count;
  6548.       char name[] = "john";
  6549.       for( count = 0; count < strlen( name ); count++ )
  6550.          printf( "*(name+%d) = %c\n", count,*(name+count) );
  6551.    }
  6552.  
  6553.  Here is the output from PSTRING3.C:
  6554.  
  6555.    *(name+0) = j
  6556.    *(name+1) = o
  6557.    *(name+2) = h
  6558.    *(name+3) = n
  6559.  
  6560.  Notice how PSTRING3.C replaces the expression
  6561.  
  6562.    name[count]
  6563.  
  6564.  with the expression:
  6565.  
  6566.    *(name+count)
  6567.  
  6568.  Both expressions use the variable  count  as an offset from the base address
  6569.  of the array. The parentheses in the second expression are important. They
  6570.  are necessary because the indirection operator takes effect before the
  6571.  addition operator. If you omit the parentheses, as in
  6572.  
  6573.    *name+count
  6574.  
  6575.  the expression has the same effect as
  6576.  
  6577.    (*name)+count
  6578.  
  6579.  which adds the value of  count  to the object  name  references.
  6580.  
  6581.  In summary, the examples in this section show three alternative ways to
  6582.  access a character inside a string. In the printf statements in the
  6583.  examples, these expressions are equivalent:
  6584.  
  6585.    *ptr
  6586.  
  6587.    name[count]
  6588.  
  6589.    *(name+count)
  6590.  
  6591.  Many C programmers prefer pointer notation to array notation because
  6592.  pointers are faster for some operations. In other cases─including the one
  6593.  above─the choice is entirely one of taste. There's more to say about the
  6594.  relationship between pointers and arrays. We'll return to this topic later
  6595.  in this chapter and in Chapter 9, "Advanced Pointers."
  6596.  
  6597.  
  6598.  Passing Pointers to Functions
  6599.  
  6600.   A function that receives  pointers can access  variables that are local  to
  6601.  other functions.
  6602.  
  6603.  One of the most common uses of pointers is to pass them as arguments to
  6604.  functions. Functions that receive variables as parameters get local copies
  6605.  of those variables, not the originals. In contrast, functions that receive
  6606.  pointers to variables gain access to the original variables associated with
  6607.  the pointers. This allows the functions to
  6608.  
  6609.  
  6610.    ■   Return more than one value
  6611.  
  6612.    ■   Read and change values in variables─including arrays and
  6613.        structures─that otherwise aren't visible to the function
  6614.  
  6615.  
  6616.  The first item listed above relates to the return statement. As we noted in
  6617.  Chapter 2, "Functions," a function can return only one value through return.
  6618.  How-ever, it's not difficult to imagine a useful function─a sort, for
  6619.  instance─that would return more than one value. Pointers offer an elegant
  6620.  solution.
  6621.  
  6622.  The second item involves visibility. Most variables in C programs are local
  6623.  to the functions where they are defined, and a function normally can't
  6624.  access local variables in other functions. There are times, however, when
  6625.  you want a function to have access to a local variable defined elsewhere in
  6626.  the program. By passing the function a pointer to the local variable, you
  6627.  can give it access to the variable  itself.
  6628.  
  6629.  The PFUNC.C program illustrates both ideas. It has a function that returns
  6630.  more than one value and uses pointers to alter variables that aren't visible
  6631.  within the function:
  6632.  
  6633.    /* PFUNC.C: Pass pointers to a function. */
  6634.  
  6635.    #include <stdio.h>
  6636.  
  6637.    void swap( int *ptr1, int *ptr2 );
  6638.  
  6639.    main()
  6640.    {
  6641.       int first = 1, second = 3;
  6642.       int *ptr = &second;
  6643.       printf( "first: %d  second: %d\n", first, *ptr );
  6644.       swap( &first, ptr );
  6645.       printf( "first: %d  second: %d\n", first, *ptr );
  6646.    }
  6647.  
  6648.    void swap( int *ptr1, int *ptr2 )
  6649.    {
  6650.       int temp;
  6651.       temp = *ptr1;
  6652.       *ptr1 = *ptr2;
  6653.       *ptr2 = temp;
  6654.    }
  6655.  
  6656.  Here is the output from PFUNC.C:
  6657.  
  6658.    first: 1  second: 3
  6659.    first: 3  second: 1
  6660.  
  6661.    Pointers can eliminate the need for external variables.
  6662.  
  6663.  The PFUNC.C program swaps the values of two int variables named  first  and
  6664.  second, using a function named  swap. Since the exchange involves two
  6665.  values, the  swap  function can't use return to communicate its results.
  6666.  More-over, the variables  first  and  second  are defined only in the main
  6667.  function, and as good C programmers, we want to exchange their values
  6668.  without making them externally visible.
  6669.  
  6670.  The prototype for the  swap  function shows that  swap  expects to receive
  6671.  two pointers to int variables:
  6672.  
  6673.    void swap( int *ptr1, int *ptr2 );
  6674.  
  6675.  Notice the use of void in the prototype and function definition. The void
  6676.  specifier shows that the  swap  function doesn't return any value through a
  6677.  return statement. Instead, swap  returns its results indirectly, through the
  6678.  action of pointers.
  6679.  
  6680.  The variables we want to exchange are defined only in main:
  6681.  
  6682.    int first = 1, second = 3;
  6683.  
  6684.  No other function in the program can access these variables directly by
  6685.  using the variable names  first  and  second. We must pass these variables
  6686.  as arguments; but since the C language passes arguments by value, we need to
  6687.  pass pointers to the variables.
  6688.  
  6689.  The main function calls  swap  with the following statement:
  6690.  
  6691.    swap( &first, ptr );
  6692.  
  6693.  This statement shows two different ways to pass a pointer to a function. The
  6694.  first argument in the function call,
  6695.  
  6696.    &first
  6697.  
  6698.  passes the address of first as a constant, using the address-of operator.
  6699.  The second argument,
  6700.  
  6701.    ptr
  6702.  
  6703.  passes the address of  second  with a pointer variable. Earlier in PFUNC.C
  6704.  we declared  ptr  as a pointer to an int and assigned it the address of
  6705.  second:
  6706.  
  6707.    int *ptr = &second;
  6708.  
  6709.  Both arguments pass the same kind of data─the address of a local variable─to
  6710.  the function. We'll return to this idea after we see how the rest of PFUNC.C
  6711.  works.
  6712.  
  6713.  When the  swap  function executes, it creates two int pointers named  ptr1
  6714.  and  ptr2  and assigns the passed addresses to them:
  6715.  
  6716.    void swap( int *ptr1, int *ptr2 )
  6717.  
  6718.  Since there's a one-to-one correspondence between arguments and parameters,
  6719.  the pointer  ptr1  receives the address of  first  and  ptr2  receives the
  6720.  address of  second. The  swap  function exchanges the values of  first  and
  6721.  second, using the two pointers and a temporary int variable named  temp:
  6722.  
  6723.    int temp;
  6724.    temp = *ptr1;
  6725.    *ptr1 = *ptr2;
  6726.    *ptr2 = temp;
  6727.  
  6728.  Within the  swap  function, PFUNC.C uses the indirection operator to access
  6729.  the values that  ptr1  and  ptr2  reference. The expression  *ptr1  accesses
  6730.  the value stored in  first. Likewise, the expression  *ptr2  accesses the
  6731.  value stored in  second.
  6732.  
  6733.  Through the addresses contained in the pointers, the  swap  function can
  6734.  indirectly access variables that are local to the main function.
  6735.  
  6736.  
  6737.  Passing Address Constants Versus Passing Pointer Variables
  6738.  
  6739.  Now that you know how the  swap  function works, we can elaborate on the two
  6740.  methods that PFUNC.C uses to pass the address of  first  and  second  to
  6741.  swap.
  6742.  
  6743.   When you pass a pointer  to a function, the function actually receives an
  6744.  address.
  6745.  
  6746.  Earlier, we said the  swap  function expects to receive two pointers as
  6747.  parameters. While it's common to say pointers in this context, it would be
  6748.  more accurate to say the function expects addresses, since that's what it
  6749.  actually receives.
  6750.  
  6751.  To work correctly,  swap  only needs the addresses of two variables. Once it
  6752.  has the addresses, it assigns them to its own local pointers and proceeds to
  6753.  do its work─modifying the original variables at long distance, as it were.
  6754.  The  swap  function doesn't care whether you pass the addresses as constants
  6755.  or pointer variables, since it receives the same kind of value in either
  6756.  case. The address is all the function needs to change the value of a
  6757.  variable defined elsewhere.
  6758.  
  6759.  The first argument in the function call to  swap  shows a straightforward
  6760.  way to pass an address. Inside the main function of PFUNC.C, the expression
  6761.  &first  equals the address of  first. When you pass this argument to  swap,
  6762.  the function clearly receives an address.
  6763.  
  6764.  The second argument is an address, too. Since main assigns the address of
  6765.  second  to the pointer variable  ptr, the expression  ptr  equals the
  6766.  address of second. When you pass this argument to  swap, the function also
  6767.  receives an address. (Remember, the value contained in a pointer variable is
  6768.  an address.)
  6769.  
  6770.  Some beginning programmers get confused by functions that expect to receive
  6771.  pointers, thinking they must always pass pointer variables to such
  6772.  functions. As PFUNC.C shows, if the function expects an address you can
  6773.  simply pass the address as a constant, using the address-of operator.
  6774.  
  6775.  ────────────────────────────────────────────────────────────────────────────
  6776.  NOTE
  6777.  
  6778.  When a function expects to receive an address as a parameter, you can pass
  6779.  either an address constant or a pointer variable, whichever is more
  6780.  suitable.
  6781.  ────────────────────────────────────────────────────────────────────────────
  6782.  
  6783.  Why, then, would you ever go to the trouble of passing a pointer variable to
  6784.  this kind of function? In a real program, the function that calls  swap
  6785.  might well use pointers to process  first  and  second  for some other
  6786.  purpose. In such a case you might prefer to use pointers in the function
  6787.  call, too.
  6788.  
  6789.  
  6790.  Arrays of Pointers
  6791.  
  6792.  Pointers, like other variables, can be stored in arrays. This feature allows
  6793.  you to create a variety of useful data structures.
  6794.  
  6795.   In an array of pointers, each array element is  a pointer variable.
  6796.  
  6797.  If you find an array of pointers hard to picture, begin with the idea that
  6798.  an array is a group of variables of the same type. An "array of pointers" is
  6799.  also a group of variables, but instead of simple variables, it contains a
  6800.  group of pointer variables.
  6801.  
  6802.  Each element in an array of pointers, then, is a pointer that contains an
  6803.  address. Like other array elements, each element can be accessed with a
  6804.  numerical subscript.
  6805.  
  6806.  Pointer arrays are often used to speed up sorts. The QCSORT.C program shows
  6807.  the basic idea behind such a sort:
  6808.  
  6809.    /* QCSORT.C: Demonstrate sorting array of pointers. */
  6810.  
  6811.    #include <stdio.h>
  6812.    #define SIZE 4
  6813.  
  6814.    void sort( int size, double *p[] );
  6815.    void show( int size, double *p[], double dd[] );
  6816.  
  6817.    main()
  6818.    {
  6819.       int x;
  6820.       double d[] = { 3.333, 1.111, 2.222, 4.444 };
  6821.       double *d_ptr[SIZE];
  6822.       for( x = 0; x < SIZE; x++ )
  6823.          d_ptr[x] = &d[x];
  6824.       show( SIZE, d_ptr, d );
  6825.       sort( SIZE, d_ptr );
  6826.       show( SIZE, d_ptr, d );
  6827.    }
  6828.  
  6829.    void sort( int size, double *p[] )
  6830.    {
  6831.       int x, x1;
  6832.       double *temp;
  6833.       for( x = 0; x < size - 1; x++ )
  6834.          for( x1 = x + 1; x1 < size; x1++ )
  6835.          {
  6836.             if( *p[x] > *p[x1] )
  6837.             {
  6838.                temp = p[x1];
  6839.                p[x1] = p[x];
  6840.                p[x] = temp;
  6841.             }
  6842.          }
  6843.    }
  6844.  
  6845.    void show( int size, double *p[], double dd[] )
  6846.    {
  6847.       int x;
  6848.       printf( "------------------------" );
  6849.       printf( "------------------------\n" );
  6850.       for( x = 0; x < size; x++ )
  6851.       {
  6852.          printf( "*d_ptr[%d] = %1.3f   ", x, *p[x]);
  6853.          printf( "d_ptr[%d] = %u ", x, p[x]);
  6854.          printf( "  d[%d] = %1.3f\n", x, dd[x] );
  6855.       }
  6856.    }
  6857.  
  6858.  Here is the output from QCSORT.C:
  6859.  
  6860.    ------------------------------------------------
  6861.    *d_ptr[0] = 3.333   d_ptr[0] = 66   d[0] = 3.333
  6862.    *d_ptr[1] = 1.111   d_ptr[1] = 74   d[1] = 1.111
  6863.    *d_ptr[2] = 2.222   d_ptr[2] = 82   d[2] = 2.222
  6864.    *d_ptr[3] = 4.444   d_ptr[3] = 90   d[3] = 4.444
  6865.    ------------------------------------------------
  6866.    *d_ptr[0] = 1.111   d_ptr[0] = 74   d[0] = 3.333
  6867.    *d_ptr[1] = 2.222   d_ptr[1] = 82   d[1] = 1.111
  6868.    *d_ptr[2] = 3.333   d_ptr[2] = 66   d[2] = 2.222
  6869.    *d_ptr[3] = 4.444   d_ptr[3] = 90   d[3] = 4.444
  6870.  
  6871.  Since the purpose of QCSORT.C is to demonstrate pointers, not sorting
  6872.  methods, it uses a simple bubble sort. This method isn't efficient but has
  6873.  the advantage of being short and easy to follow.
  6874.  
  6875.  The QCSORT.C program creates a double array named  d  and an array of
  6876.  pointers named  d_ptr. Each array has four elements. To illustrate the sort,
  6877.  the elements of  d  are initialized out of order.
  6878.  
  6879.  The goal of QCSORT.C is to display a sorted list of the values in  d. You
  6880.  could do this by sorting the elements of  d  itself, but that solution is
  6881.  not efficient. Every double value contains eight bytes, and sorting a large
  6882.  number of double values requires that you move a lot of memory.
  6883.  
  6884.  Instead of moving the double values themselves, QCSORT.C creates an array of
  6885.  pointers that point to the elements of the  d  array, then sorts the
  6886.  pointers. This saves time because a pointer is stored in only two bytes.
  6887.  Figure 8.6 shows the relationship between the  d  and  d_ptr  arrays
  6888.  immediately after both are initialized.
  6889.  
  6890.  (This figure may be found in the printed book.)
  6891.  
  6892.  At the stage shown in Figure 8.6, the pointers in the  d_ptr  array have
  6893.  been initialized to point to the double elements in the  d  array. (The
  6894.  array element  d_ptr[0]  points to  d[0],  d_ptr[1]  points to  d[1], and so
  6895.  on.) The function  show  displays three sets of data:
  6896.  
  6897.  
  6898.    ■   The value each pointer references
  6899.  
  6900.    ■   The address assigned to each pointer
  6901.  
  6902.    ■   The value of each element in the  d  array
  6903.  
  6904.  
  6905.  After calling the  show  function, QCSORT.C calls the  sort  function, which
  6906.  sorts the pointers in  d_ptr.
  6907.  
  6908.  The declaration of  sort  contains something new. In the declaration
  6909.  
  6910.    void sort( int size, double *p[] );
  6911.  
  6912.  the expression  *p[]  shows that the  sort  function expects to receive a
  6913.  pointer to an array of pointers. When the program calls  sort, it passes the
  6914.  size of the array to be sorted (first argument) and a pointer to the array
  6915.  of pointers (second argument):
  6916.  
  6917.    sort( SIZE, d_ptr );
  6918.  
  6919.  Now the  sort  function has all the information it needs to sort the
  6920.  pointers in the  d_ptr  array, making each pointer point to the correct
  6921.  element in the  d  array.
  6922.  
  6923.  After the sort is complete, QCSORT.C calls  show  again to display the
  6924.  results of the sort. Now that the pointers have been sorted, they can be
  6925.  used to display a sorted list of double values. Figure 8.7 shows the
  6926.  relationship between the  d  and  d_ptr  arrays after the sort is complete.
  6927.  
  6928.  
  6929.  (This figure may be found in the printed book.)
  6930.  
  6931.  Of course, the array in QCSORT.C is so small that the time savings from
  6932.  using pointers is negligible. In a real program, however, which might sort
  6933.  thousands of values instead of four, the difference between moving eight
  6934.  bytes and two bytes can be dramatic. The advantage of sorting pointers is
  6935.  even greater when sorting large data objects such as strings or structures.
  6936.  
  6937.  
  6938.    The elements in a  pointer array can point  to any type of data.
  6939.  
  6940.  The QCSORT.C example section uses a fairly simple array of pointers. But you
  6941.  can use such arrays to create quite complex data structures. The basic form
  6942.  of the array is always the same─it is a group of pointer variables, each
  6943.  pointer accessible through a subscript─but the pointers in an array can
  6944.  point to any kind of data object. You can have an array of pointers to
  6945.  structures, an array of pointers to strings, and so on. The only difference
  6946.  is in what the pointers reference.
  6947.  
  6948.  Don't confuse an array of pointers with a pointer to an array. A pointer to
  6949.  an array (or "array pointer") is a single pointer variable that points to an
  6950.  array element. The single pointer can access any element of the array, but
  6951.  only one pointer is involved.
  6952.  
  6953.  In contrast, an array of pointers is a group of related pointer variables
  6954.  stored in an array. Each element in the array is a pointer, and you can
  6955.  access individual pointers with the array name and subscript. Each pointer
  6956.  in the array points, in turn, to some other object.
  6957.  
  6958.  
  6959.  A Pause for Reflection
  6960.  
  6961.  If this is your first exposure to pointers, you may want to reflect on what
  6962.  you have learned before reading the next chapter. This chapter has explained
  6963.  the basic uses of pointers, and you can write a great many useful programs
  6964.  using only these techniques. If you're not comfortable with all these ideas,
  6965.  you may want to experiment with them before reading more about pointers.
  6966.  
  6967.  The next chapter, "Advanced Pointers," examines further uses of pointers,
  6968.  including multiple indirection and pointers to structures.
  6969.  
  6970.  
  6971.  
  6972.  
  6973.  
  6974.  
  6975.  Chapter 9  Advanced Pointers
  6976.  ────────────────────────────────────────────────────────────────────────────
  6977.  
  6978.  The preceding chapter, "Pointers," explained the basics of using pointers─
  6979.  how to declare and initialize pointer variables and use them to access basic
  6980.  data types. This chapter explores more advanced pointer techniques,
  6981.  including multiple indirection, pointers to structures, and pointers to
  6982.  functions.
  6983.  
  6984.  
  6985.  Pointers to Pointers
  6986.  
  6987.  In Chapter 8, "Pointers," we stated a pointer can point to any kind of
  6988.  variable. Since a pointer is a variable, you can make it the target of
  6989.  another pointer, creating a pointer to a pointer. This concept is useful in
  6990.  itself and is also important for understanding the equivalence of array
  6991.  notation and pointer notation, which is explained in the next section.
  6992.  
  6993.  The program PTRPTR.C demonstrates a pointer to a pointer insimple terms:
  6994.  
  6995.    /* PTRPTR.C: Demonstrate a pointer to a pointer. */
  6996.  
  6997.    #include <stdio.h>
  6998.  
  6999.    main()
  7000.    {
  7001.       int val = 501;
  7002.       int *ptr = &val;
  7003.       int **ptr_ptr = &ptr;
  7004.       printf( "val = %d\n", **ptr_ptr );
  7005.    }
  7006.  
  7007.  Here is the output from PTRPTR.C:
  7008.  
  7009.    val = 501
  7010.  
  7011.  The first two statements in PTRPTR.C should look familiar by now. They
  7012.  create an int variable named  val  and an int pointer named  ptr. The third
  7013.  line, however, requires some explanation:
  7014.  
  7015.    int **ptr_ptr = &ptr;
  7016.  
  7017.  This statement uses double indirection to create a variable named  ptr_ptr,
  7018.  which is a pointer to a pointer. This pointer is assigned the address of the
  7019.  first pointer,  ptr. The pointer  ptr  references  val, and the pointer
  7020.  ptr_ptr  references  ptr. Figure 9.1 illustrates the relationship between
  7021.  ptr  and  ptr_ptr.
  7022.  
  7023.  (This figure may be found in the printed book.)
  7024.  
  7025.  Once we have initialized both pointers, we can use  ptr_ptr  to access  val:
  7026.  
  7027.  
  7028.    **ptr_ptr
  7029.  
  7030.   The double indirection operator ( ** ) is used with a pointer to a pointer.
  7031.  
  7032.  
  7033.  The double indirection operator (**) in front of  ptr_ptr  tells two things
  7034.  about ptr_ptr: that  ptr_ptr  is itself a pointer and it points to a second
  7035.  pointer. Both asterisks are needed to access the contents of  val. If you
  7036.  use only one, as in
  7037.  
  7038.    *ptr_ptr
  7039.  
  7040.  then  ptr_ptr  accesses the contents of  ptr, which is the address of  val.
  7041.  This statement, for instance, prints the address stored in  ptr:
  7042.  
  7043.    printf( "ptr = %u", *ptr_ptr );
  7044.  
  7045.  Using pointers to pointers is known as "multiple indirection." One pointer
  7046.  points to a second pointer, which in turn accesses a third data object. In
  7047.  theory, there's no limit to how far you can take multiple indirection. You
  7048.  can create pointers to pointers, pointers to pointers to pointers, and so
  7049.  on. However, there's rarely any practical reason to carry indirection beyond
  7050.  two levels (a pointer to a pointer).
  7051.  
  7052.  
  7053.  Equivalence of Array and Pointer Notation
  7054.  
  7055.  In previous sections we noted, more or less in passing, two important facts
  7056.  about arrays and pointers:
  7057.  
  7058.  
  7059.    1.  An array name is actually a pointer.
  7060.  
  7061.    2.  Array notation (subscripts) and pointer notation are interchangeable.
  7062.  
  7063.  
  7064.  These ideas are significant enough to warrant an explicit demonstration.
  7065.  Let's rewrite the QCSORT.C program using pointer notation:
  7066.  
  7067.    /* QCSORT1.C: Demonstrate sort with pointer notation. */
  7068.  
  7069.    #include <stdio.h>
  7070.    #define SIZE 4
  7071.  
  7072.    void sort( int size, double **p );
  7073.    void show( int size, double **p, double dd[] );
  7074.  
  7075.    main()
  7076.    {
  7077.       int x;
  7078.       double d[] = { 3.333, 1.111, 2.222, 4.444 };
  7079.       double *d_ptr[SIZE];
  7080.       for( x = 0; x < SIZE; x++ )
  7081.          d_ptr[x] = &d[x];
  7082.       show( SIZE, d_ptr, d );
  7083.       sort( SIZE, d_ptr );
  7084.       show( SIZE, d_ptr, d );
  7085.    }
  7086.  
  7087.    void sort( int size, double **p )
  7088.    {
  7089.       int x, x1;
  7090.       double *temp;
  7091.       for( x = 0; x < size - 1; x++ )
  7092.          for( x1 = x + 1; x1 < size; x1++ )
  7093.          {
  7094.             if( **(p+x) > **(p+x1) )
  7095.             {
  7096.                temp = *(p+x1);
  7097.                *(p+x1) = *(p+x);
  7098.                *(p+x) = temp;
  7099.             }
  7100.          }
  7101.    }
  7102.  
  7103.    void show( int size, double **p, double dd[] )
  7104.    {
  7105.       int x;
  7106.       printf( "------------------------" );
  7107.       printf( "------------------------\n" );
  7108.       for( x = 0; x < size; x++ )
  7109.       {
  7110.          printf( "*d_ptr[%d] = %1.3f   ", x, **(p+x) );
  7111.          printf( "d_ptr[%d] = %u ", x, *(p+x) );
  7112.          printf( "  d[%d] = %1.3f\n", x, dd[x] );
  7113.       }
  7114.    }
  7115.  
  7116.  The QCSORT1.C program works like its predecessor, QCSORT.C. (It sorts an
  7117.  array of pointers that point to elements in an int array.) The only
  7118.  difference is QCSORT1.C uses pointer notation instead of array notation.
  7119.  
  7120.  Let's look at how the change affects the  sort  function, beginning with its
  7121.  prototype. In the previous program, QCSORT.C, the prototype
  7122.  
  7123.    void sort( int size, double *p[] );
  7124.  
  7125.  uses array notation to show we'll pass the name of an array of pointers to
  7126.  sort. Since an array name is a pointer, we can rewrite the prototype using
  7127.  pointer notation, as in QCSORT1.C:
  7128.  
  7129.    void sort( int size, double **p );
  7130.  
  7131.  The  sort  function definition is rewritten in the same way. Here is the
  7132.  definition of  sort  in the original program (QCSORT.C):
  7133.  
  7134.    void sort( int size, double *p[] )
  7135.    {
  7136.       int x, x1;
  7137.       double *temp;
  7138.       for( x = 0; x < size - 1; x++ )
  7139.          for( x1 = x + 1; x1 < size; x1++ )
  7140.          {
  7141.             if( *p[x] > *p[x1] )
  7142.             {
  7143.             temp = p[x1];
  7144.             p[x1] = p[x];
  7145.             p[x] = temp;
  7146.             }
  7147.          }
  7148.    }
  7149.  
  7150.  The same function using pointers looks like this in QCSORT1.C:
  7151.  
  7152.    void sort( int size, double **p )
  7153.    {
  7154.       int x, x1;
  7155.       double *temp;
  7156.       for( x = 0; x < size - 1; x++ )
  7157.          for( x1 = x + 1; x1 < size; x1++ )
  7158.          {
  7159.             if( **(p+x) > **(p+x1) )
  7160.             {
  7161.                temp = *(p+x1);
  7162.                *(p+x1) = *(p+x);
  7163.                *(p+x) = temp;
  7164.             }
  7165.          }
  7166.    }
  7167.  
  7168.  Within the  sort  function, the variable  p  is a pointer to a pointer. When
  7169.  we use a single asterisk, as in,
  7170.  
  7171.    *(p+x1)
  7172.  
  7173.  we access the contents of the  x1  pointer, which is an address. When we
  7174.  place a double asterisk in front of an address value, as in,
  7175.  
  7176.    **(p+x)
  7177.  
  7178.  we access the contents of this address.
  7179.  
  7180.  Using pointer notation in place of array notation, QCSORT1.C achieves the
  7181.  same result as QCSORT.C. In many cases─including this one─it doesn't really
  7182.  matter which notation you use. If you're still more comfortable with array
  7183.  notation, you may prefer to use it sometimes. Since many C programs use
  7184.  pointers to manipulate arrays, however, it's worth taking the time to learn
  7185.  pointer notation, too.
  7186.  
  7187.  
  7188.  Getting Command-Line Arguments
  7189.  
  7190.    Command-line arguments are passed to programs through argv, an array of
  7191.  pointers.
  7192.  
  7193.  Arrays of pointers have one very common use─accessing command-line
  7194.  arguments. When a C program begins execution, DOS passes two arguments to
  7195.  it. The first argument, normally called  argc, is an int variable that
  7196.  indicates the number of command-line arguments. The second, normally called
  7197.  argv, is a pointer to an array of strings. Each string in the array contains
  7198.  one of the command-line arguments.
  7199.  
  7200.  Even if you don't plan to use  argc  and  argv  in your programs, you can
  7201.  expect to see them often in other C programs, so it's useful to know how
  7202.  they're used. The ARGV.C program uses  argc  and  argv.
  7203.  
  7204.    /* ARGV.C: Demonstrate accessing command-line arguments. */
  7205.  
  7206.    #include <stdio.h>
  7207.  
  7208.    void show_args( char *argument );
  7209.  
  7210.    int main( int argc, char *argv[] )
  7211.    {
  7212.       int count;
  7213.       for( count=0; count < argc; count++ )
  7214.          show_args( argv[count] );
  7215.       return 0;
  7216.    }
  7217.  
  7218.    void show_args( char *argument )
  7219.    {
  7220.       printf( "%s\n", argument );
  7221.    }
  7222.  
  7223.  To make ARGV.C produce output, you must give it some command-line arguments.
  7224.  (If you run ARGV.C in the QuickC environment, select Run/Debug from the
  7225.  Options menu and type the command-line arguments at the Command Line
  7226.  prompt.) The program prints each argument on the screen.
  7227.  
  7228.  If you use this command line, for instance,
  7229.  
  7230.    argv harpo chico groucho zeppo
  7231.  
  7232.  then ARGV.C gives this output:
  7233.  
  7234.    C:\SOURCES\ARGV.EXE
  7235.    harpo
  7236.    chico
  7237.    groucho
  7238.    zeppo
  7239.  
  7240.  The first argument may have surprised you. In DOS versions 3.0 and higher,
  7241.  the first string in the  argv  array ( argv[0] ) contains the drive
  7242.  specification and full pathname to the program that is executing. The drive
  7243.  and path you see will depend on how your system is configured. In the
  7244.  example the ARGV.EXE program is located in the SOURCES directory of drive C.
  7245.  
  7246.  
  7247.  Thus, the value of  argc  actually is one greater than the number of
  7248.  command-line arguments, and the first argument typed on the command line is
  7249.  the second string in the array ( argv[1] ). If you type the arguments shown
  7250.  above, the value of  argc  is 5 and  argv[1]  contains the argument  harpo.
  7251.  
  7252.  
  7253.  
  7254.  Null Pointers
  7255.  
  7256.  We can use the ARGV.C program to illustrate another handy property of
  7257.  pointers: null pointers. Consider this modification (ARGV1.C):
  7258.  
  7259.    /* ARGV1.C: Demonstrate null pointers. */
  7260.  
  7261.    #include <stdio.h>
  7262.  
  7263.    void show_args( char *argument );
  7264.  
  7265.    int main( int argc, char **argv )
  7266.    {
  7267.       while( *argv )
  7268.          show_args( *(argv++) );
  7269.       return 0;
  7270.    }
  7271.  
  7272.    void show_args( char *argument )
  7273.    {
  7274.       printf( "%s\n", argument );
  7275.    }
  7276.  
  7277.  The ARGV1.C program gives the same output as the previous program but it
  7278.  uses a while loop instead of a for loop. The test expression in this loop,
  7279.  
  7280.    while( *argv )
  7281.  
  7282.  is equivalent to this test expression:
  7283.  
  7284.    while( *argv != 0 )
  7285.  
  7286.  The loop in ARGV1.C continues until it finds a "null pointer," a pointer
  7287.  that contains 0. In this case, the null pointer means we have reached the
  7288.  end of the array: no more strings are available.
  7289.  
  7290.   Null pointers can be used to show success or failure and as markers in a
  7291.  series.
  7292.  
  7293.  Many C library functions use null pointers to signal the success or failure
  7294.  of an operation that returns a pointer. For instance, the library function
  7295.  malloc normally returns a pointer to the beginning address of the memory
  7296.  area it allocates. If no memory is available, malloc returns a null pointer
  7297.  to show the operation failed. Similarly, the fopen function usually returns
  7298.  a pointer to a FILE structure, but returns a null pointer when it fails.
  7299.  
  7300.  Null pointers can also be used to mark the end of a list of pointers, such
  7301.  as the  argv  array or a linked list.
  7302.  
  7303.  
  7304.  Pointers to Structures
  7305.  
  7306.   A structure pointer can access any member of a structure.
  7307.  
  7308.  A pointer to a structure, or "structure pointer," is conceptually similar to
  7309.  an array pointer. Just as an array pointer can point to any element in an
  7310.  array, a structure pointer can reference any member in a structure. The
  7311.  major difference is one of notation.
  7312.  
  7313.  In case you're not yet an expert on structure notation, let's review it very
  7314.  briefly. First recall that each element in an array has the same type, so
  7315.  you refer to individual array elements with subscripts:
  7316.  
  7317.    i_array[3]
  7318.  
  7319.  Because members of a structure can have different types, you can't use
  7320.  numerical subscripts to refer to them based on their order. Instead, each
  7321.  structure member has a symbolic name. You refer to a member with a structure
  7322.  name and member name, separating the two names with the member-of operator
  7323.  (.):
  7324.  
  7325.    jones.name
  7326.  
  7327.  The notation for structure pointers follows the same pattern, with only two
  7328.  differences. You must
  7329.  
  7330.  
  7331.    1.  Replace the structure name with the name of the pointer
  7332.  
  7333.    2.  Replace the member-of operator with a two-character operator called
  7334.        the "pointer-member" operator (->)
  7335.  
  7336.  
  7337.  The pointer-member operator is formed by a dash and a right-angle bracket.
  7338.  The following name uses the pointer-member operator:
  7339.  
  7340.    jones_ptr->name
  7341.  
  7342.  Here  jones_ptr  is the name of a pointer to a structure, and  name  is a
  7343.  member of the structure that  jones_ptr  points to.
  7344.  
  7345.  The EMPLOY1.C program is a revision of the EMPLOYEE.C program that
  7346.  demonstrates structures in Chapter 4, "Data Types." This program illustrates
  7347.  how to manipulate a structure through a pointer:
  7348.  
  7349.    /* EMPLOY1.C: Demonstrate structure pointers. */
  7350.  
  7351.    #include <stdio.h>
  7352.  
  7353.    struct employee
  7354.    {
  7355.       char name[10];
  7356.       int months;
  7357.       float wage;
  7358.    };
  7359.  
  7360.    void display( struct employee *e_ptr  );
  7361.  
  7362.    main()
  7363.    {
  7364.       struct employee jones =
  7365.       {
  7366.          "Jones, J",
  7367.          77,
  7368.          13.68
  7369.       };
  7370.  
  7371.       display( &jones );
  7372.    }
  7373.  
  7374.    void display( struct employee *e_ptr )
  7375.    {
  7376.       printf( "Name: %s\n", e_ptr->name );
  7377.       printf( "Months of service: %d\n", e_ptr->months );
  7378.       printf( "Hourly wage: %6.2f\n", e_ptr->wage );
  7379.    }
  7380.  
  7381.   Structure pointers allow  functions to access  structures that are local
  7382.  to other functions.
  7383.  
  7384.  The EMPLOY1.C program gives the same output as the earlier version. But
  7385.  instead of passing the entire structure to the  display  function, this
  7386.  program passes a structure pointer. This method conserves memory, since the
  7387.  display  function doesn't create a local copy of the structure. It also
  7388.  allows  display  to change members in the original structure, which is local
  7389.  to the main function.
  7390.  
  7391.  The header of the  display  function shows that the function expects to
  7392.  receive a structure pointer:
  7393.  
  7394.    void display( struct employee *e_ptr  )
  7395.  
  7396.  The expression in parentheses specifies what type of value the function
  7397.  expects. This expression is a bit complex, so let's look at each part
  7398.  individually. The expression  *e_ptr  indicates the function expects to
  7399.  receive a pointer, which it names  e_ptr. It is preceded by
  7400.  
  7401.    struct employee
  7402.  
  7403.  which states what type of pointer  e_ptr  is. The struct keyword indicates
  7404.  e_ptr  is a pointer to a structure, and the tag  employee  specifies the
  7405.  structure type.
  7406.  
  7407.  The next item of interest in EMPLOY1.C is the function call that passes the
  7408.  structure pointer:
  7409.  
  7410.    display( &jones );
  7411.  
  7412.  This statement uses the address-of operator to pass the address of the
  7413.  jones  structure to the  display  function. The address-of operator is not
  7414.  optional. Since we want the function to access the original structure─not a
  7415.  local copy─we must pass the structure's address.
  7416.  
  7417.  When the  display  function executes, it creates a pointer variable named
  7418.  e_ptr  and assigns to it the address passed in the function call. Now the
  7419.  display  function can refer to any member of the structure indirectly
  7420.  through the pointer  e_ptr. Within the  display  function, the statement
  7421.  
  7422.    printf( "%s\n", e_ptr->name );
  7423.  
  7424.  has the same effect that the statement
  7425.  
  7426.    printf( "%s\n", jones.name );
  7427.  
  7428.  has in the main function. Figure 9.2 illustrates the relationship between
  7429.  the structure pointer and structure members in EMPLOY1.C.
  7430.  
  7431.  (This figure may be found in the printed book.)
  7432.  
  7433.  Just to confirm that the  display  function can access the original
  7434.  structure in EMPLOY1.C, try adding this statement to the end of the  display
  7435.   function:
  7436.  
  7437.    strcpy( e_ptr->name, "King, M" );
  7438.  
  7439.  and this statement to the end of the main function:
  7440.  
  7441.    printf( "%s\n", jones.name );
  7442.  
  7443.  These changes cause EMPLOY1.C to print:
  7444.  
  7445.    King, M
  7446.  
  7447.  Acting indirectly through a structure pointer, the  display  function was
  7448.  able to change a structure defined elsewhere in the program.
  7449.  
  7450.  
  7451.  Pointers to Functions
  7452.  
  7453.  At the beginning of the previous chapter we stated that a pointer can point
  7454.  to any object present in memory at run time. Since functions themselves are
  7455.  located in memory, you can assign the address of a function to a pointer,
  7456.  creating a "function pointer."
  7457.  
  7458.   A function pointer makes it possible to pass a function as a function
  7459.  argument.
  7460.  
  7461.  Function pointers provide a way─in fact, the only practical way─to pass a
  7462.  function as an argument to another function. This permits the second
  7463.  function to call the first function indirectly through the pointer.
  7464.  
  7465.  While function pointers may sound rather obscure, they have some common
  7466.  practical uses:
  7467.  
  7468.  
  7469.    ■   Some QuickC run-time library functions, such as qsort, expect to
  7470.        receive a pointer to a user-defined function in your program. (Online
  7471.        help includes an example program that uses qsort.)
  7472.  
  7473.    ■   Function pointers are used extensively in Windows and OS/2
  7474.        Presentation Manager programs.
  7475.  
  7476.    ■   Using an array of function pointers, you can create a "dispatch
  7477.        table." A dispatch table is a list of related functions that can be
  7478.        called based on some choice made at run time. It is similar to an ON
  7479.        GOSUB statement in BASIC or a call table in assembly language.
  7480.  
  7481.  
  7482.  The syntax for function pointers is a bit complex, so let's start with a
  7483.  simple example. The FUNCPTR.C program creates a pointer to our old friend,
  7484.  printf, and calls printf through the pointer:
  7485.  
  7486.    /* FUNCPTR.C: Demonstrate function pointers. */
  7487.  
  7488.    #include <stdio.h>
  7489.  
  7490.    main()
  7491.    {
  7492.       int (*func_ptr) ();
  7493.       func_ptr = printf;
  7494.       (*func_ptr) ( "Curiouser and curiouser...\n" );
  7495.    }
  7496.  
  7497.  Here is the output from FUNCPTR.C:
  7498.  
  7499.    Curiouser and curiouser...
  7500.  
  7501.  This line from FUNCPTR.C declares  func_ptr  as a pointer to a function:
  7502.  
  7503.    int (*func_ptr) ();
  7504.  
  7505.  The declaration of a function pointer must use the same type specifier as
  7506.  the function it references. If the function returns a float value, the
  7507.  pointer uses type float, and so on. Since the printf function returns an int
  7508.  value showing how many characters it displays, the declaration of  func_ptr
  7509.  uses the type int.
  7510.  
  7511.   A function-pointer declaration must have two pairs of parentheses.
  7512.  
  7513.  Function-pointer declarations may look complex, but all the parentheses are
  7514.  essential. The empty parentheses at the end of the declaration are needed to
  7515.  show the pointer points to a function.
  7516.  
  7517.  The parentheses enclosing the function name itself are mandatory, too.
  7518.  Notice what happens if you omit them:
  7519.  
  7520.    void *func_ptr(); /* Error! Not a function pointer. */
  7521.  
  7522.  Instead of declaring a pointer to a function, this statement declares a
  7523.  function that returns a pointer─not at all what we want in FUNCPTR.C.
  7524.  
  7525.  The next program line initializes the function pointer, assigning it the
  7526.  address of the printf function:
  7527.  
  7528.    func_ptr = printf;
  7529.  
  7530.  This line has two important features. First, notice the name printf isn't
  7531.  followed by parentheses, as it would be when you call printf directly. We
  7532.  want to obtain the address of printf, not call it.
  7533.  
  7534.  Second, note that it's not necessary to place the address-of operator before
  7535.  the name printf. Because  func_ptr  was declared as a function pointer, the
  7536.  compiler knows it should use the address of printf here. If you like,
  7537.  however, you can add the address-of operator to make the statement a little
  7538.  more readable:
  7539.  
  7540.    func_ptr = &printf;
  7541.  
  7542.  The next line calls the printf function indirectly through the pointer
  7543.  func_ptr:
  7544.  
  7545.    (*func_ptr) ( "Curiouser and curiouser...\n" );
  7546.  
  7547.  Note the similarity between this statement and a normal call to printf. It's
  7548.  equivalent to this line:
  7549.  
  7550.    printf( "Curiouser and curiouser...\n" );
  7551.  
  7552.  To call printf indirectly through  func_ptr, you supply the same arguments
  7553.  as when you call printf directly.
  7554.  
  7555.  
  7556.  Passing Function Pointers as Arguments
  7557.  
  7558.   Function pointers are usually passed as function arguments.
  7559.  
  7560.  Like other pointers, function pointers can be passed as arguments to
  7561.  functions. Normally, in fact, this is the only reason to use a function
  7562.  pointer.
  7563.  
  7564.  The FUNCPTR.C program in the previous section is easy to follow but not very
  7565.  practical. In a real program, you wouldn't go to the trouble of creating a
  7566.  function pointer just to call printf from the main function.
  7567.  
  7568.  The FUNCPTR1.C program demonstrates how to pass a function pointer as an
  7569.  argument. It has a function named  gimme_func  that expects to be passed a
  7570.  function pointer:
  7571.  
  7572.    /* FUNCPTR1.C: Passing function pointers as arguments. */
  7573.  
  7574.    #include <stdio.h>
  7575.  
  7576.    void gimme_func( void (*func_ptr) () );
  7577.  
  7578.    main()
  7579.    {
  7580.       gimme_func( puts );
  7581.       gimme_func( printf );
  7582.    }
  7583.  
  7584.    void gimme_func( void (*func_ptr) () )
  7585.    {
  7586.       (*func_ptr) ( "Ausgezeichnet!" );
  7587.    }
  7588.  
  7589.  Here is the output from FUNCPTR1.C:
  7590.  
  7591.    Ausgezeichnet!
  7592.    Ausgezeichnet!
  7593.  
  7594.  In the interests of brevity, the function  gimme_func  does a very simple
  7595.  job. It expects to receive a pointer to a function that can display a string
  7596.  and uses that pointer to print the string. The first call to  gimme_func
  7597.  passes a pointer to the library function puts, and the second passes a
  7598.  pointer to printf.
  7599.  
  7600.  Since the declaration of  gimme_func  states it takes a pointer to a
  7601.  function, the address-of operator is optional in a call to  gimme_func. The
  7602.  following statements are equivalent:
  7603.  
  7604.    gimme_func( puts );
  7605.    gimme_func( &puts );
  7606.  
  7607.  
  7608.  A Parting Word on Pointers
  7609.  
  7610.  If you have read the previous two chapters from beginning to end, you may be
  7611.  suffering from a mild─or perhaps not so mild─case of information overload.
  7612.  Pointers have so many different uses that it's difficult to learn everything
  7613.  about them at once.
  7614.  
  7615.  Don't be discouraged if some uses of pointers still aren't clear to you. The
  7616.  latter parts of this chapter cover some rather esoteric techniques, which
  7617.  you probably won't use often. When needed, however, these techniques offer
  7618.  some very powerful capabilities.
  7619.  
  7620.  Like other programming concepts, pointers are best learned through practice,
  7621.  so use them at every sensible opportunity. Remember, you don't need to know
  7622.  everything about pointers in order to do something with them. The more you
  7623.  use pointers in everyday programming, the sooner all the pieces of the
  7624.  puzzle will fall into place.
  7625.  
  7626.  
  7627.  
  7628.  
  7629.  
  7630.  
  7631.  Chapter 10  Programming Pitfalls
  7632.  ────────────────────────────────────────────────────────────────────────────
  7633.  
  7634.  In C, as in every language, it's rare for any program to work perfectly the
  7635.  first time. An important part of knowing a language is recognizing what not
  7636.  to do and why certain problems occur.
  7637.  
  7638.  This chapter describes common C programming pitfalls and how to avoid them.
  7639.  It is organized under broad topics, such as "Pointer Problems," with a
  7640.  category for miscellaneous problems at the end. The description of each
  7641.  error gives a code example, explains why the error occurs, and offers a
  7642.  solution.
  7643.  
  7644.  
  7645.  Operator Problems
  7646.  
  7647.  The most common operator problems involve operators unique to C. Others
  7648.  involve questions of precedence, which can cause problems in any language.
  7649.  
  7650.  
  7651.  Confusing Assignment and Equality Operators
  7652.  
  7653.  A common error is to confuse the assignment operator (=) with the equality
  7654.  operator (==). The mistake often occurs in decision-making statements:
  7655.  
  7656.    int val = 555;
  7657.    if( val = 20 ) /* Error! */
  7658.       printf( "val equals 20\n" );
  7659.  
  7660.  The above code prints  val equals 20  even though it's clear  val  doesn't
  7661.  equal 20 when the if statement begins. Instead of testing whether  x  equals
  7662.  20, the expression  val = 20  assigns the value 20 to  val.
  7663.  
  7664.  Remember, the single equal sign (=) performs an assignment in C. This
  7665.  particular assignment results in a nonzero value, so the if test is
  7666.  evaluated as true, causing the printf statement to execute.
  7667.  
  7668.  To correct the problem, use the double equal sign (==) to test equality:
  7669.  
  7670.    if( x == 20 )
  7671.       printf( "x equals 20\n" );
  7672.  
  7673.  Once you're in the habit of using the equality operator, you might make the
  7674.  opposite mistake of using two equal signs where you should use only one:
  7675.  
  7676.    main()
  7677.    {
  7678.       int val;
  7679.       for( val == 0; val < 5; val++ )  /* Error! */
  7680.          printf( "val = %d\n", val );
  7681.    }
  7682.  
  7683.  Here the error appears in the initializing expression of the for statement.
  7684.  It's the reverse of what happened in the first example. Instead of assigning
  7685.  the value 0 to  val, the expression  val == 0  evaluates whether or not  val
  7686.   equals 0. The expression doesn't change the value of  val  at all. Since
  7687.  val  is an uninitialized variable, the for loop is unpredictable.
  7688.  
  7689.  
  7690.  Confusing Operator Precedence
  7691.  
  7692.  Peculiar things can happen if you ignore operator precedence:
  7693.  
  7694.    main()
  7695.    {
  7696.       int ch;
  7697.       while( ch = getch() != '\r' )
  7698.          printf( "%d\n", ch );
  7699.    }
  7700.  
  7701.  Instead of assigning the result of the getch library-function call to  ch,
  7702.  the above code assigns the value 0 to  ch  when you press the ENTER key and
  7703.  the value 1 when you press any other key. (The values 1 and 0 represent true
  7704.  and false.)
  7705.  
  7706.  The error occurs because the inequality operator (!=) has higher precedence
  7707.  than the assignment operator (=). The expression
  7708.  
  7709.    ch = getch() != '\r'
  7710.  
  7711.  is the same as
  7712.  
  7713.    ch = (getch() != '\r')
  7714.  
  7715.  Both expressions compare the result of the getch call to the character
  7716.  constant \r. The result of that comparison is then assigned to  ch.
  7717.  
  7718.  For the program to work correctly, these operations must happen in the
  7719.  reverse order. The result of the function call must be assigned to the
  7720.  variable before the variable is compared to the constant. We can solve the
  7721.  problem by adding parentheses:
  7722.  
  7723.    main()
  7724.    {
  7725.       int ch;
  7726.       while( (ch = getch()) != '\r')
  7727.        printf( "%d\n", ch );
  7728.    }
  7729.  
  7730.  Parentheses have the highest precedence of any operator, so the expression
  7731.  
  7732.    (ch = getch()) != '\r'
  7733.  
  7734.  works correctly. It assigns the result of the getch call to  ch  before
  7735.  comparing  ch  to the constant.
  7736.  
  7737.  The list of precedence-related errors is almost endless. Fortunately, QuickC
  7738.  makes it unnecessary to memorize precedence rules. To view a complete table
  7739.  of operator precedences, see Appendix A, "C Language Guide," and online help
  7740.  in the QuickC environment.
  7741.  
  7742.   Use parentheses  to avoid operator  precedence problems.
  7743.  
  7744.  When in doubt, use extra parentheses to make the order of operations
  7745.  absolutely clear. Extra parentheses don't degrade performance, and they can
  7746.  improve readability as well as minimize precedence problems.
  7747.  
  7748.  
  7749.  Confusing Structure-Member Operators
  7750.  
  7751.  Two different operators are used to access the members of a structure. Use
  7752.  the structure-member operator (.) to access a structure member directly, and
  7753.  the pointer-member operator (->) to access a structure member indirectly
  7754.  through a pointer.
  7755.  
  7756.  For instance, you may create a pointer to a structure of the  employee
  7757.  type,
  7758.  
  7759.    struct employee *p_ptr;
  7760.  
  7761.  and initialize the pointer to point to the  jones  structure:
  7762.  
  7763.    p_ptr = &jones;
  7764.  
  7765.  If you use the structure-member operator to access a structure member
  7766.  through the pointer,
  7767.  
  7768.    p_ptr.months = 78; /* Error! */
  7769.  
  7770.  QuickC issues this error message:
  7771.  
  7772.    C2040: '.' requires struct/union name
  7773.  
  7774.  Use the pointer-member operator to access a structure member through a
  7775.  pointer:
  7776.  
  7777.    p_ptr->months = 78;
  7778.  
  7779.  
  7780.  Array Problems
  7781.  
  7782.  The most common errors associated with arrays involve indexing errors. The
  7783.  problems described in this section all concern indexing errors of one form
  7784.  or another.
  7785.  
  7786.  
  7787.  Array Indexing Errors
  7788.  
  7789.   The first C array subscript is 0.
  7790.  
  7791.  If you're used to a language that has different subscripting rules, it's
  7792.  easy to forget that the first subscript of a C array is 0 and the last
  7793.  subscript is 1 less than the number used to declare the array. Here's an
  7794.  example:
  7795.  
  7796.    int i_array[4] = { 3, 55, 600, 12 };
  7797.    main()
  7798.    {
  7799.       int count;
  7800.       for( count = 1; count < 5; count++ )  /* Error! */
  7801.          printf( "i_array[%d] = %d\n", i_array[count] );
  7802.    }
  7803.  
  7804.  The for loop in the above program starts at  i_array[1]  and ends at
  7805.  i_array[4]. It should begin with the first element,  i_array[0]  and end at
  7806.  the last, i_array[3]. The following corrects the error.
  7807.  
  7808.    for( count = 0; count < 4; count++ )
  7809.       printf( "i_array[%d] = %d\n", i_array[count] );
  7810.  
  7811.  
  7812.  Omitting an Array Subscript in Multidimensional Arrays
  7813.  
  7814.   Enclose each subscript  in its own set of brackets.
  7815.  
  7816.  Programmers who know QuickBASIC, QuickPascal, or FORTRAN may be tempted to
  7817.  place more than one array subscript in the same pair of brackets. In C, each
  7818.  subscript of a multidimensional array is enclosed in its own pair of
  7819.  brackets:
  7820.  
  7821.    int i_array[2][2] = { { 12, 2 }, { 6, 55 } };
  7822.    main()
  7823.    {
  7824.       printf( "%d\n", i_array[ 0, 1 ] ); /* Error! */
  7825.    }
  7826.  
  7827.  In the preceding example, the expression
  7828.  
  7829.    i_array[ 0, 1 ]
  7830.  
  7831.  does not access element 0,1 of  i_array . Here is the correct way to refer
  7832.  to that array element:
  7833.  
  7834.    i_array[0][1]
  7835.  
  7836.  Interestingly, the deviant array reference doesn't cause a syntax error. As
  7837.  mentioned in Chapter 6, "Operators," it's legal to separate multiple
  7838.  expressions with a comma operator, and the final value of such a series is
  7839.  the value of the rightmost expression in the group. Thus, the expression
  7840.  
  7841.    i_array[ 0, 1 ]
  7842.  
  7843.  is equivalent to this one:
  7844.  
  7845.    i_array[ 1 ];
  7846.  
  7847.  Both expressions give an address, not the value of an array element.
  7848.  
  7849.  
  7850.  Overrunning Array Boundaries
  7851.  
  7852.  Since C doesn't check array subscripts for validity, you must keep track of
  7853.  array boundaries on your own. For instance, if you initialize a
  7854.  five-character array,
  7855.  
  7856.    char sample[] = "ABCD";
  7857.  
  7858.  and refer to a nonexistent array element,
  7859.  
  7860.    sample[9] = 'X';
  7861.  
  7862.  QuickC doesn't signal an error, although the second statement overwrites
  7863.  memory outside the array. It stores a character in element 9 of an array
  7864.  that contains only 5 elements.
  7865.  
  7866.  The same problem can occur when accessing an array through a pointer:
  7867.  
  7868.    char sample[] = "ABCD";
  7869.    char *ptr = sample;
  7870.    *--ptr = 'X';  /* Error! */
  7871.  
  7872.  The code overwrites the byte in memory below the array. To avoid such
  7873.  problems, confine all array operations within the range used to declare the
  7874.  array.
  7875.  
  7876.  
  7877.  String Problems
  7878.  
  7879.  Strings are handled a little differently in C than most languages─a fact
  7880.  that can cause problems. The following errors are common to programs that
  7881.  use strings.
  7882.  
  7883.  
  7884.  Confusing Character Constants and Character Strings
  7885.  
  7886.  Remember the difference between a character constant, which has one byte,
  7887.  and a character string, which is a series of characters ending with a null
  7888.  character:
  7889.  
  7890.    char ch = 'Y';
  7891.    if( ch == "Y" )  /* Error! */
  7892.       printf( "The ayes have it..." );
  7893.  
  7894.  The example above mistakenly compares the char variable  ch  to a
  7895.  twocharacter string ( "Y" ) instead of a single character constant ( 'Y' ).
  7896.  Since the comparison is false, the printf statement never executes─no matter
  7897.  what  ch  equals.
  7898.  
  7899.  The if statement needs to use single quotes. This code correctly tests
  7900.  whether  ch  equals the character  'Y':
  7901.  
  7902.    char ch = 'Y';
  7903.    if( ch == 'Y' )
  7904.       printf( "The ayes have it..." );
  7905.  
  7906.  
  7907.  Forgetting the Null Character That Terminates Strings
  7908.  
  7909.  Remember that strings end with a null character in C. If you declare this
  7910.  five-character array,
  7911.  
  7912.    char sample[5];
  7913.  
  7914.  the compiler allocates five bytes of memory for the array. If you try to
  7915.  store the string "Hello"  in the array like this,
  7916.  
  7917.    strcpy( sample, "Hello" );
  7918.  
  7919.  you'll overrun the array's bounds. The string "Hello"  contains six
  7920.  characters (five letters and a null character), so it's one byte too big to
  7921.  fit in the  sample  array. The strcpy overwrites one byte of memory outside
  7922.  the array's storage.
  7923.  
  7924.  It's easy to make this error when allocating memory for a string, too:
  7925.  
  7926.    char str[] = "Hello";
  7927.    char *ptr;
  7928.    ptr = malloc( strlen( str ) ); /* Error! */
  7929.    if( ptr == NULL )
  7930.       exit( 1 );
  7931.    else
  7932.       strcpy( ptr, str );
  7933.  
  7934.  This time the error occurs in the call to the malloc function, which
  7935.  allocates memory to a pointer prior to a string copy. The strlen function
  7936.  returns the length of a string not including the null character that ends
  7937.  the string. Since the amount of memory allocated is one byte too small, the
  7938.  strcpy operation overwrites memory, just as in the previous example.
  7939.  
  7940.  To avoid the problem, add 1 to the value returned by strlen:
  7941.  
  7942.    ptr = malloc( strlen( str ) + 1 );
  7943.  
  7944.  
  7945.  Forgetting to Allocate Memory for a String
  7946.  
  7947.  If you declare a string as a pointer, don't forget to allocate memory for
  7948.  it. This example tries to create a char pointer named  ptr  and initialize
  7949.  it with a string:
  7950.  
  7951.    main()
  7952.    {
  7953.       char *ptr;
  7954.       strcpy( ptr, "Ashby" );  /* Error! */
  7955.    }
  7956.  
  7957.  The pointer declaration  char *ptr;  creates a pointer variable but nothing
  7958.  else. It allocates enough memory for the pointer to store an address but
  7959.  doesn't allocate any memory to store the object to which  ptr  will point.
  7960.  The strcpy operation in the next line overwrites memory by copying the
  7961.  string into an area not used by the program.
  7962.  
  7963.  One way to allocate memory is by declaring a char array large enough to hold
  7964.  the string:
  7965.  
  7966.    main()
  7967.    {
  7968.       char c_array[10];
  7969.       strcpy( c_array, "Randleman" );
  7970.    }
  7971.  
  7972.  You can also call the malloc library function to allocate memory at run
  7973.  time:
  7974.  
  7975.    #define BUFFER_SIZE 30
  7976.    #include <malloc.h>
  7977.  
  7978.    main()
  7979.    {
  7980.       char *ptr;
  7981.       if( ptr = (char *) malloc( BUFFER_SIZE ) )
  7982.       {
  7983.          strcpy( ptr, "Duvall" );
  7984.          printf( ptr );
  7985.          free( ptr );
  7986.       }
  7987.    }
  7988.  
  7989.  
  7990.  Pointer Problems
  7991.  
  7992.  Every experienced C programmer has a collection of favorite pointer-induced
  7993.  bugs. Pointer errors can wreak havoc because pointers can change the
  7994.  contents of any addressable memory location. If a pointer writes to an
  7995.  unexpected address, the results can be disastrous.
  7996.  
  7997.  
  7998.  Using the Wrong Address Operator to Initialize a Pointer
  7999.  
  8000.  If you're still learning about pointers, it's easy to forget which address
  8001.  operator to use when initializing a pointer variable. For example, you might
  8002.  want to create a pointer to a simple int variable:
  8003.  
  8004.    int val = 25;
  8005.    int *ptr;
  8006.    ptr = val; /* Error! */
  8007.  
  8008.  The code above doesn't initialize  ptr  correctly. Instead of assigning to
  8009.  ptr  the address of  val, the statement
  8010.  
  8011.    ptr = val;
  8012.  
  8013.  tries to assign  ptr  the contents of  val, causing an error message:
  8014.  
  8015.    warning C4047: '=' : different levels of indirection
  8016.  
  8017.  Because  val  is an int variable, its contents can't form a meaningful
  8018.  address for ptr. You must use the address-of operator to initialize  ptr:
  8019.  
  8020.    ptr = &val;
  8021.  
  8022.  Here's another pointer initialization error:
  8023.  
  8024.    int val = 25;
  8025.    int *ptr;
  8026.    *ptr = &val; /* Error! */
  8027.  
  8028.  The last line doesn't initialize  ptr  to point to the variable  val. The
  8029.  expression to the left of the equal sign,  *ptr, stands for the object  ptr
  8030.  points to. Instead of assigning  ptr  the address of  val, the line tries to
  8031.  assign the address of  val  to the place where  ptr  points. Because  ptr
  8032.  has never been initialized, the assignment triggers a run-time error:
  8033.  
  8034.    run-time error R6001
  8035.    -null pointer assignment
  8036.  
  8037.  Here is the correct way to initialize this pointer:
  8038.  
  8039.    ptr = &val;
  8040.  
  8041.  
  8042.  Declaring a Pointer with the Wrong Type
  8043.  
  8044.  You should make sure the type used to declare a pointer matches the type of
  8045.  data object it points to:
  8046.  
  8047.    main()
  8048.    {
  8049.       int *ptr;
  8050.       .
  8051.       .
  8052.       .
  8053.       float val = 3.333333;
  8054.       ptr = val;  /* Error! */
  8055.       printf( "val = %f\n", *ptr );
  8056.    }
  8057.  
  8058.  The program declares  ptr  as a pointer to an int. Later on, forgetting what
  8059.  type we used when declaring  ptr, we assign it the address of the
  8060.  floating-point variable  val.
  8061.  
  8062.   Declaring a pointer with the wrong type can cause unwanted type
  8063.  conversions.
  8064.  
  8065.  Since C allows you to assign any address to a pointer, the assignment
  8066.  doesn't cause an error. But accessing  val  through  ptr  creates problems.
  8067.  Because  ptr  is declared as a pointer to an int, the compiler does a type
  8068.  conversion on the float it points to, converting the float value to an int.
  8069.  The output is garbage:
  8070.  
  8071.    val = 11242989923343410000000000000000000000000000000000000
  8072.    000000000000000000000000000000000000000000000000000.000000
  8073.  
  8074.  The following program cures the error by declaring  ptr  as a pointer to a
  8075.  float data type:
  8076.  
  8077.    main()
  8078.    {
  8079.       float *ptr;
  8080.       float val = 3.333333;
  8081.       ptr = &val;
  8082.       printf( "%f\n", *ptr );
  8083.    }
  8084.  
  8085.  Now it gives the correct output:
  8086.  
  8087.    val = 3.333333
  8088.  
  8089.  
  8090.  Using Dangling Pointers
  8091.  
  8092.  A "dangling pointer" is one that points to a memory area no longer in use by
  8093.  your program. Dangling pointers, like uninitialized pointers, can be very
  8094.  dangerous to use.
  8095.  
  8096.  For instance, say you allocate a block of memory with the malloc library
  8097.  function:
  8098.  
  8099.    #define BUFSIZE 1000
  8100.    char *ptr;
  8101.    if( ptr = (char *) malloc( BUFSIZE ) )
  8102.       /* do something */ ;
  8103.  
  8104.  After the memory block has been allocated with malloc, the pointer  ptr
  8105.  points to a valid data object. Once you're done using allocated memory, you
  8106.  normally return it to the heap:
  8107.  
  8108.    free( ptr );
  8109.  
  8110.  After you free the memory it points to,  ptr  is a dangling pointer. It
  8111.  still points to a valid machine address, but that address is no longer in
  8112.  use by the program. You shouldn't use the pointer at this stage, just as you
  8113.  shouldn't use it before it has been initialized.
  8114.  
  8115.  Dangling pointers can also be created by a function that returns a pointer
  8116.  to a local variable:
  8117.  
  8118.    int *boo_boo( void )
  8119.    {
  8120.       int object;
  8121.       .
  8122.       .
  8123.       .
  8124.       return &object; /* Error! */
  8125.    }
  8126.  
  8127.  The  boo_boo  function returns the address of the local variable  object,
  8128.  forgetting the storage for  object  is no longer part of the program after
  8129.  the function ends.
  8130.  
  8131.  Here's a variant of the previous example involving a string pointer:
  8132.  
  8133.    char *boo_boo( void )
  8134.    {
  8135.       char *c_ptr;
  8136.       c_ptr = "Hello";
  8137.       .
  8138.       .
  8139.       .
  8140.       return c_ptr; /* Error! */
  8141.    }
  8142.  
  8143.  Since the string constant  "Hello"  is local to the function, it evaporates
  8144.  when the function ends, leaving the pointer  c_ptr  dangling.
  8145.  
  8146.  
  8147.  Library-Function Problems
  8148.  
  8149.  Once you've learned enough about C to write practical programs, you can
  8150.  begin to explore the rich function library supplied with QuickC. This
  8151.  section outlines a few common problems related to using library functions.
  8152.  Again, you can use online help to get information about specific library
  8153.  functions.
  8154.  
  8155.  
  8156.  Failing to Check Return Values from Library Functions
  8157.  
  8158.   Always check library function return values.
  8159.  
  8160.  Almost all library functions return some value─either the result of
  8161.  processing or an error code showing success or failure. You should always
  8162.  check libraryfunction return values, even if you're confident of the result.
  8163.  
  8164.  
  8165.  This rule is critical when calling a library function such as malloc, which
  8166.  allocates memory at run time:
  8167.  
  8168.    char *ptr;
  8169.    ptr = (char *) malloc( BUFSIZE );  /* Error! */
  8170.  
  8171.  If the call to malloc fails, the pointer  ptr  is assigned a null (0) value.
  8172.  Using  ptr  under these circumstances can overwrite unexpected memory
  8173.  addresses or cause a run-time error. The following code checks the return
  8174.  value from malloc:
  8175.  
  8176.    #define NULL 0
  8177.    #define BUFSIZE 32768
  8178.       .
  8179.       .
  8180.       .
  8181.    char *ptr;
  8182.    if( (ptr = (char *) malloc( BUFSIZE ) ) != NULL )
  8183.    {
  8184.       printf( "Copacetic.\n" );
  8185.       /* Do something useful... */
  8186.    }
  8187.    else
  8188.       printf( "Not enough memory!\n" );
  8189.  
  8190.  
  8191.  Duplicating Library-Function Names
  8192.  
  8193.  There are so many functions in the QuickC run-time library that it's
  8194.  sometimes difficult to avoid duplicating function names. For instance, if
  8195.  you write a function that reads data from a buffer, the name  read  may
  8196.  strike you as short and descriptive.
  8197.  
  8198.  The only problem is that read is the name of a QuickC library function. A
  8199.  program that defines its own  read  function may work correctly at first,
  8200.  but if you later include the header file that declares the read library
  8201.  function,
  8202.  
  8203.    #include <io.h>
  8204.  
  8205.  then redefinition errors occur. You can't use the same name for two
  8206.  different functions. The solution here is to rename the user-defined
  8207.  function.
  8208.  
  8209.   Use online help to check  for function-name conflicts.
  8210.  
  8211.  QuickC's online help lets you check for such name conflicts on the spot. Put
  8212.  the cursor on the function name you wish to use, then press F1. If the name
  8213.  is already used for a library function, online help displays information
  8214.  about the function. If the name isn't in online help, it's not used in the
  8215.  QuickC function library and is a safe choice.
  8216.  
  8217.  Unless you're writing your own library functions, it's a good rule to avoid
  8218.  declaring names that begin with an underscore ( _ ), since many of the
  8219.  system-defined names in QuickC start with that character. (Non-ANSI library
  8220.  functions begin with a single underscore. Predefined identifiers such as
  8221.  TIME start with two underscores, and routines internal to the C run-time
  8222.  library can begin with either one or two underscores.)
  8223.  
  8224.  
  8225.  Forgetting to Include Header Files for Library Functions
  8226.  
  8227.  Because they contain needed function prototypes, it's important to include
  8228.  the correct header files when using QuickC library functions:
  8229.  
  8230.    main()
  8231.    {
  8232.       double val = sqrt( (double) 10 );
  8233.       printf( "square root of 10 = %le\n", val );
  8234.    }
  8235.  
  8236.  The program above calls the library function sqrt, which calculates a square
  8237.  root. Most of the program is correct. When passing the value 10 to sqrt, it
  8238.  casts the argument as a double, the type sqrt expects. The return value from
  8239.  sqrt is assigned to a double variable, too.
  8240.  
  8241.  Unfortunately, the program still gives the wrong output. The square root of
  8242.  10 is not 171 (1.710000e+002 in exponential notation):
  8243.  
  8244.    square root of 10 = 1.710000e+002
  8245.  
  8246.   Function prototypes can prevent unexpected type conversions.
  8247.  
  8248.  Because the program has no prototype for the sqrt function, sqrt has the int
  8249.  return type by default. The value returned by sqrt undergoes an unexpected
  8250.  type conversion─from type double to int─and becomes garbage.
  8251.  
  8252.  This problem is easily solved. Simply include the standard header file that
  8253.  contains the prototype for sqrt:
  8254.  
  8255.    #include <stdio.h>
  8256.    #include <math.h>
  8257.    main()
  8258.    {
  8259.       double val = sqrt( (double) 10 );
  8260.       printf( "square root of 10 = %le\n", val );
  8261.    }
  8262.  
  8263.  Now the program works correctly:
  8264.  
  8265.    square root of 10 = 3.162278e+000
  8266.  
  8267.  If you're not sure which header file a library function needs, take
  8268.  advantage of QuickC's online help. (Put the cursor on the function name and
  8269.  press F1.) If the function needs a header file, the file name appears in an
  8270.  #include directive above the function prototype.
  8271.  
  8272.  
  8273.  Omitting the Address-Of Operator When Calling scanf
  8274.  
  8275.  Don't forget to put the address-of operator in front of arguments when using
  8276.  the scanf library function (the scanf function accesses keyboard input; see
  8277.  Chapter 11, "Input and Output"):
  8278.  
  8279.    main()
  8280.    {
  8281.       int val;
  8282.       printf( "Type a number: " );
  8283.       scanf( "%d", val ); /* Error! */
  8284.       printf( "%d", val );
  8285.    }
  8286.  
  8287.  When the program calls scanf, it omits the address-of operator that should
  8288.  precede the second argument:
  8289.  
  8290.    scanf( "%d", val );  /* Error! */
  8291.  
  8292.  The scanf function expects to be passed a pointer to a variable (in this
  8293.  case, a pointer to  val ) so it can assign an input value to the variable.
  8294.  But because the address-of operator is missing, the program passes the value
  8295.  of  val, not its address.
  8296.  
  8297.  Instead of storing an input value in  val  as intended, scanf uses the
  8298.  uninitialized value of  val  as a pointer and assigns the input value to an
  8299.  unpredictable address. As a result,  val  remains uninitialized and the
  8300.  program overwrites memory elsewhere─two very undesirable events.
  8301.  
  8302.  Here is the correct way to call scanf in this program:
  8303.  
  8304.    scanf( "%d", &val );
  8305.  
  8306.  
  8307.  Macro Problems
  8308.  
  8309.  Function-like macros─macro definitions that take arguments─share many of the
  8310.  advantages of functions. They can cause unwanted side effects, however, if
  8311.  you fail to put parentheses around their arguments or carelessly supply an
  8312.  argument that uses an increment or decrement operator.
  8313.  
  8314.  
  8315.  Omitting Parentheses from Macro Arguments
  8316.  
  8317.  A macro definition that doesn't enclose its arguments in parentheses can
  8318.  create precedence problems:
  8319.  
  8320.    #include <stdio.h>
  8321.  
  8322.    #define FOURX(arg)  ( arg * 4 )
  8323.  
  8324.    main()
  8325.    {
  8326.       int val;
  8327.       val = FOURX( 2 + 3 );
  8328.       printf( "val = %d\n", val );
  8329.    }
  8330.  
  8331.  The  FOURX  macro in the program multiplies its argument by 4. The macro
  8332.  works fine if you pass it a single value, as in
  8333.  
  8334.    val = FOURX( 2 );
  8335.  
  8336.  but returns the wrong result if you pass it this expression:
  8337.  
  8338.    val = FOURX( 2 + 3 );
  8339.  
  8340.  QuickC expands the above line to this line:
  8341.  
  8342.    val = 2 + 3 * 4;
  8343.  
  8344.   Use parentheses to  avoid precedence  problems in macros.
  8345.  
  8346.  Because the multiplication operator has higher precedence than the addition
  8347.  operator, this line assigns  val  the value 14 (or 2 + 12) rather than the
  8348.  correct value 20 (or 5 * 4).
  8349.  
  8350.  You can avoid the problem by enclosing the macro argument in parentheses
  8351.  each time it appears in the macro definition:
  8352.  
  8353.    #include <stdio.h>
  8354.  
  8355.    #define FOURX(arg)  ( (arg) * 4 )
  8356.  
  8357.    main()
  8358.    {
  8359.       int val;
  8360.       val = FOURX(2 + 3);
  8361.       printf( "val = %d\n", val );
  8362.    }
  8363.  
  8364.  Now the program expands this line
  8365.  
  8366.    val = FOURX(2 + 3);
  8367.  
  8368.  into this one:
  8369.  
  8370.    val = (2 + 3) * 4;
  8371.  
  8372.  The extra parentheses assure that the addition is performed before the
  8373.  multiplication, giving the desired result.
  8374.  
  8375.  
  8376.  Using Increment and Decrement Operators in Macro Arguments
  8377.  
  8378.  If a function-like macro evaluates an argument more than once, you should
  8379.  avoid passing it an expression that contains an increment or decrement
  8380.  operator:
  8381.  
  8382.    #include <stdio.h>
  8383.    #define ABS(value)  ( (value) >= 0 ? (value) : -(value) )
  8384.  
  8385.    main()
  8386.    {
  8387.       int array[4] = {3, -20, -555, 6};
  8388.       int *ptr = array;
  8389.       int val, count;
  8390.       for( count = 0; count < 4; count++ )
  8391.       {
  8392.          val = ABS(*ptr++); /* Error! */
  8393.          printf( "abs of array[%d] = %d\n", count, val );
  8394.       }
  8395.    }
  8396.  
  8397.  The program uses the  ABS  macro that was used to explain macros in Chapter
  8398.  7, "Preprocessor Directives." The macro returns the absolute value of the
  8399.  argument you pass to it.
  8400.  
  8401.  The goal in this program is to display the absolute value of every element
  8402.  in  array. It uses a for loop to step through the array and a pointer named
  8403.  ptr  to access each array element in turn. Instead of the output you would
  8404.  expect,
  8405.  
  8406.    abs of array[0] = 3
  8407.    abs of array[1] = 20
  8408.    abs of array[2] = 555
  8409.    abs of array[3] = 6
  8410.  
  8411.  the program gives this output:
  8412.  
  8413.    abs of array[0] = -20
  8414.    abs of array[1] = -6
  8415.    abs of array[2] = 8307
  8416.    abs of array[3] = 24864
  8417.  
  8418.  (The last two array values may differ if you run the program. They are the
  8419.  contents of memory not used by the program.)
  8420.  
  8421.  The error occurs in this line,
  8422.  
  8423.    val = ABS(*ptr++); /* Error! */
  8424.  
  8425.  which QuickC expands as shown here:
  8426.  
  8427.    val = ( (*ptr++) >= 0 ? (*ptr++) : -(*ptr++) ); /* Error! */
  8428.  
  8429.  Because it uses the conditional operator, the  ABS  macro always evaluates
  8430.  its argument at least twice. This isn't a problem when the argument is a
  8431.  constant or simple variable. In the example, however, the argument is the
  8432.  expression  *ptr++. Each time the macro evaluates this expression, the
  8433.  increment operator takes effect, causing  ptr  to point to the next element
  8434.  of  array.
  8435.  
  8436.  The first time the program invokes the macro,  ptr  points to the first
  8437.  array element,  array[0]. Since this element contains a nonnegative value
  8438.  (3) the macro evaluates the argument twice. The first evaluation takes the
  8439.  value that  ptr  points to and then increments  ptr. Now  ptr  points to the
  8440.  second element,  array[1]. The second evaluation takes the value of
  8441.  array[1]  and increments  ptr  again.
  8442.  
  8443.  The first macro invocation not only returns an incorrect value (-20, the
  8444.  value of  array[1] ). It also leaves  ptr  pointing to the third array
  8445.  element, making the results of later invocations unpredictable. (The pointer
  8446.  eventually moves past the last element of  array  and points to unknown
  8447.  data.)
  8448.  
  8449.  To avoid the problem, don't use the increment or decrement operators in
  8450.  arguments you pass to a macro. This revision removes the error by
  8451.  incrementing ptr  in the for statement instead of the macro invocation:
  8452.  
  8453.    #include <stdio.h>
  8454.    #define ABS(value)  ( (value) >= 0 ? (value) : -(value) )
  8455.  
  8456.    main()
  8457.    {
  8458.       int array[4] = {3, -20, -555, 6};
  8459.       int *ptr = array;
  8460.       int val, count;
  8461.       for( count = 0; count < 4; count++, ptr++ )
  8462.       {
  8463.          val = ABS(*ptr);
  8464.          printf( "abs of array[%d] = %d\n", count, val );
  8465.       }
  8466.    }
  8467.  
  8468.  This advice applies generally to QuickC library routines as well as macros
  8469.  you write. Remember, some run-time library routines are implemented as
  8470.  macros rather than C functions. If you're not sure whether a library routine
  8471.  is actually a macro, look it up in online help.
  8472.  
  8473.  
  8474.  Miscellaneous Problems
  8475.  
  8476.  This section describes C programming problems that don't fit into any
  8477.  convenient category.
  8478.  
  8479.  
  8480.  Mismatching if and else Statements
  8481.  
  8482.  In nested if statements, each else is associated with the closest preceding
  8483.  if statement that does not have an else. Although indentation can make
  8484.  nested constructs more readable, it has no syntactical effect:
  8485.  
  8486.    if( val > 5 )
  8487.       if( count == 10 )
  8488.          val = sample;
  8489.    else
  8490.       val = 0;
  8491.  
  8492.  The indentation suggests that the else associates with the first if. In
  8493.  fact, the else is part of the second if, as shown more clearly here:
  8494.  
  8495.    if( val > 5 )
  8496.       if( count == 10 )
  8497.          val = sample;
  8498.       else
  8499.          val = 0;
  8500.  
  8501.  The else is part of the second if statement─the closest preceding if that
  8502.  doesn't have a matching else. To tie the else to the first if, you must use
  8503.  braces:
  8504.  
  8505.    if( val > 5 )
  8506.    {
  8507.       if( count == 10 )
  8508.          val = sample;
  8509.    }
  8510.    else
  8511.       val = 0;
  8512.  
  8513.   Indentation makes  programs easier to read, but  is ignored by the
  8514.  compiler.
  8515.  
  8516.  Now the else belongs with the outermost if. Remember, indentation is
  8517.  meaningful only to humans. The compiler relies strictly on punctuation when
  8518.  it translates the source file.
  8519.  
  8520.  
  8521.  Misplacing Semicolons
  8522.  
  8523.  Misplaced semicolons can cause subtle bugs:
  8524.  
  8525.    #include <stdio.h>
  8526.  
  8527.    main()
  8528.    {
  8529.       int count;
  8530.       for( count = 0; count < 500; count++ ); /* Error! */
  8531.       {
  8532.          printf( "count = %d\n", count );
  8533.          printf( "And the beat goes on...\n" );
  8534.       }
  8535.    }
  8536.  
  8537.  You might expect the program to print the value of  count  500 times, but
  8538.  this is all it prints:
  8539.  
  8540.    count = 500
  8541.    And the beat goes on...
  8542.  
  8543.  The culprit is the extra semicolon immediately after the parentheses of the
  8544.  for statement. Its effect is more evident if we reformat the statement:
  8545.  
  8546.    #include <stdio.h>
  8547.  
  8548.    main()
  8549.    {
  8550.       int count;
  8551.       for( count = 0; count < 500; count++ )
  8552.          ; /* Null statement */
  8553.       {
  8554.          printf( "count = %d\n", count );
  8555.          printf( "And the beat goes on...\n" );
  8556.       }
  8557.    }
  8558.  
  8559.  Instead of printing the value of  count  500 times, the program executes the
  8560.  null statement (;) 500 times. Null statements are perfectly legal in C, so
  8561.  the compiler has no way to tell this is a mistake.
  8562.  
  8563.  Since the null statement is interpreted as the loop body, the printf
  8564.  statements inside curly braces are interpreted as a statement block and
  8565.  executed once. Statement blocks usually appear as part of a loop, function
  8566.  definition, or decision- making statement, but it's legal to enclose any
  8567.  series of statements in braces.
  8568.  
  8569.  The program works as intended if you remove the extra semicolon:
  8570.  
  8571.    #include <stdio.h>
  8572.  
  8573.    main()
  8574.    {
  8575.       int count;
  8576.       for( count = 0; count < 500; count++ )
  8577.       {
  8578.          printf( "count = %d\n", count );
  8579.          printf( "And the beat goes on...\n" );
  8580.       }
  8581.    }
  8582.  
  8583.  Here's another one. If you know QuickPascal, you might be tempted to put a
  8584.  semicolon after the parentheses of a function definition:
  8585.  
  8586.    void func( void );
  8587.  
  8588.    void func( void ); /* Error! No semicolon here. */
  8589.    {
  8590.       printf( "C is not Pascal\n" );
  8591.    }
  8592.  
  8593.  The function header causes a syntax error. While a function declaration
  8594.  requires a semicolon after its parentheses, a function definition does not.
  8595.  This code corrects the error:
  8596.  
  8597.    void func( void );
  8598.  
  8599.    void func( void )
  8600.    {
  8601.       printf( "C is not Pascal\n" );
  8602.    }
  8603.  
  8604.  
  8605.  Omitting Double Backslashes in DOS Path Specifications
  8606.  
  8607.  Because C uses the backslash (\) as an escape character, it's easy to create
  8608.  garbled path specifications:
  8609.  
  8610.    fp = fopen( "c:\temp\bodkin.txt", "w" );
  8611.  
  8612.  At first glance, the path specification in the string
  8613.  
  8614.    "c:\temp\bodkin.txt"
  8615.  
  8616.  looks good because that's how you would type it on the DOS command line. In
  8617.  a quoted string, however, the backslash is interpreted as an escape
  8618.  character. In this string the sequences \t and \b are interpreted as the tab
  8619.  and backspace character, respectively, garbling the path and file name. Even
  8620.  if the indicated file exists, this call to fopen is sure to fail.
  8621.  
  8622.  In a quoted string the escape sequence for a backslash character is a double
  8623.  backslash (\\). This statement solves the problem:
  8624.  
  8625.    fp = fopen( "c:\\temp\\bodkin.txt", "w" );
  8626.  
  8627.  
  8628.  Omitting break Statements from a switch Statement
  8629.  
  8630.  Don't forget to include break statements when using the switch statement:
  8631.  
  8632.    switch( ch )
  8633.    {
  8634.       case 'e':
  8635.          printf( "Bye bye\n" );
  8636.          break;
  8637.       case 'l':
  8638.          printf( "Loading the file\n" );
  8639.          load_file( fp );
  8640.          break;
  8641.  
  8642.    case 's':
  8643.          printf( "Saving the file\n" );
  8644.          write_file( fp );  /* Error! Missing break. */
  8645.       case 'd':
  8646.          printf( "Deleting the file\n" );
  8647.          kill_file( fp );
  8648.          break;
  8649.       default:
  8650.          break;
  8651.    }
  8652.  
  8653.  In this code a break statement is missing from the statements following the
  8654.  third case label (the statements that print  Saving the file ). After those
  8655.  statements execute, execution falls through to the next case label, deleting
  8656.  the newly saved file.
  8657.  
  8658.  To avoid this problem, place a break at the end of every case item:
  8659.  
  8660.    case 's':
  8661.       printf( "Saving the file.\n" );
  8662.       write_file( fp );
  8663.       break;
  8664.  
  8665.  It's legal, of course, to write a program in which execution deliberately
  8666.  falls through from one case label to the next. In such cases you may want to
  8667.  add a comment to prevent confusion.
  8668.  
  8669.  
  8670.  Mixing Signed and Unsigned Values
  8671.  
  8672.  If you explicitly compare two values of different types, the compiler
  8673.  normally catches the error. Some type mismatches aren't easy to spot,
  8674.  however, even for humans:
  8675.  
  8676.    #define CHARVAL '\xff'
  8677.  
  8678.    main()
  8679.    {
  8680.       unsigned char uc;
  8681.       uc = CHARVAL;
  8682.       if( uc == CHARVAL )
  8683.          printf( "Eureka!" );
  8684.       else
  8685.          printf( "Oops..." );
  8686.    }
  8687.  
  8688.  The program prints  Oops...  which probably wasn't expected. The comparison
  8689.  between  CHARVAL  and  uc  is false even though both are clearly char
  8690.  values.
  8691.  
  8692.  The answer lies in the way the compiler converts signed and unsigned char
  8693.  values into int values for internal use. The #define directive,
  8694.  
  8695.    #define CHARVAL '\xff'
  8696.  
  8697.  defines  CHARVAL  as the constant 0xff. Since no sign is specified, the
  8698.  compiler treats the constant as a signed char value by default. When it
  8699.  converts the char to an int for internal use, as it does all character
  8700.  values, the compiler extends the value's sign. The result is an int with the
  8701.  value 0xffff.
  8702.  
  8703.  The variable  uc  undergoes the same internal conversion, with an important
  8704.  difference. Since  uc  is explicitly declared as unsigned, its value is
  8705.  converted to an int value of 0x00ff.
  8706.  
  8707.  When the two int values are compared, the result is false (0xffff does not
  8708.  equal 0x00ff). One solution is to explicitly cast  CHARVAL  to the desired
  8709.  type:
  8710.  
  8711.    #define CHARVAL (unsigned char)'\xff'
  8712.  
  8713.  Now the compiler compares two unsigned char values, giving the desired
  8714.  result. Another solution is to make  CHARVAL  an int instead of a char
  8715.  constant:
  8716.  
  8717.    #define CHARVAL 0xff
  8718.  
  8719.  Both solutions give the desired result, although the second is slightly less
  8720.  efficient. It creates word-size, rather than byte-size, machine-code
  8721.  instructions.
  8722.  
  8723.  
  8724.  
  8725.  
  8726.  
  8727.  
  8728.  PART II  Using C
  8729.  ────────────────────────────────────────────────────────────────────────────
  8730.  
  8731.  Part 2 of C for Yourself  is called "Using C" and should be read after you
  8732.  are familiar with basic C concepts. It covers practical topics that make it
  8733.  possible for you to write real programs. The features discussed in these
  8734.  chapters are provided in the QuickC run-time library, which, as you may
  8735.  recall from Part 1, is not part of the C language itself.
  8736.  
  8737.  While Part 1 was designed to be read sequentially, Part 2 is topical. So you
  8738.  don't need to read its chapters in any particular order. If you are new to
  8739.  C, however, it is recommended that you begin with Chapter 11, "Input and
  8740.  Output," which describes how to read and write data, and process files.
  8741.  Similarly, if you're not familiar with QuickC graphics, you should read
  8742.  Chapters 13-15 in order.
  8743.  
  8744.  
  8745.  
  8746.  
  8747.  
  8748.  
  8749.  Chapter 11  Input and Output
  8750.  ────────────────────────────────────────────────────────────────────────────
  8751.  
  8752.  The first part of this book explored the fundamentals of the C language. In
  8753.  the second part (starting with this chapter), the topics include more
  8754.  complex and powerful functions: accessing disk files, creating
  8755.  high-resolution graphics, creating graphs, manipulating fonts, and adding
  8756.  assembly-language routines to your C programs.
  8757.  
  8758.  Program examples in previous chapters used printf to print to the screen. In
  8759.  this chapter, we'll cover printf in more detail, moving on to other I/O
  8760.  functions such as fprintf, which prints to a file, instead of to the screen.
  8761.  
  8762.  
  8763.  This chapter covers three broad topics: keyboard and screen input/output
  8764.  (I/O), reading and writing standard disk files, and low-level disk access.
  8765.  It also introduces several common string-handling functions.
  8766.  
  8767.  
  8768.  Input and Output Streams
  8769.  
  8770.  Books about C often refer to "input streams" and "output streams." A stream
  8771.  is a sequence of bytes flowing into the program (input) or flowing out
  8772.  (output). The data might have originally come from the keyboard, a modem, a
  8773.  disk file, or some other peripheral device. The outgoing data might be sent
  8774.  out to the screen, a modem, or a disk file.
  8775.  
  8776.  Thus, when you see a phrase such as "opening a stream," it means opening a
  8777.  line of communication to the disk drive or to some other peripheral.
  8778.  
  8779.   Peripherals and files are called "streams" in C.
  8780.  
  8781.  The five streams always open and available for input or output are shown in
  8782.  Table 11.1.
  8783.  
  8784.  Table 11.1  Standard I/O Streams
  8785.  
  8786. ╓┌───────────────┌───────────────────────────────────────────────────────────╖
  8787.  Name            Stream
  8788.  ────────────────────────────────────────────────────────────────────────────
  8789.  stdin           Standard input (keyboard)
  8790.  stdout          Standard output (screen)
  8791.  stderr          Standard error channel (screen)
  8792.  stdprn          Standard printer (parallel port)
  8793.  stdaux          Standard auxiliary device (serial port)
  8794.  ────────────────────────────────────────────────────────────────────────────
  8795.  
  8796.  
  8797.  
  8798.  Screen and Keyboard I/O
  8799.  
  8800.  Imagine an application program that doesn't ever send output to the screen
  8801.  or accept input from the keyboard. It's possible to write such a program,
  8802.  but it's unlikely you'd ever want to.
  8803.  
  8804.  In most situations, you need to display various kinds of data on the screen
  8805.  and to accept input from the keyboard. "Manipulating and Printing Strings"
  8806.  introduces the functions commonly used to communicate back and forth.
  8807.  
  8808.  
  8809.  Manipulating and Printing Strings
  8810.  
  8811.    Always pass at least one  string to the printf function.
  8812.  
  8813.  Previous chapters have used the printf function to display results on the
  8814.  screen. By now you should be accustomed to how it works. There's one rule
  8815.  you must always follow when using printf: pass it at least one format
  8816.  string, which may be a literal string or a pointer to a string. The string
  8817.  may or may not include format specifiers, which are defined below.
  8818.  
  8819.  The printf function always prints to the stdout device. Unless the output
  8820.  has been redirected, the standard output device is the screen.
  8821.  
  8822.  The following program illustrates some typical ways to manipulate strings
  8823.  and to print them:
  8824.  
  8825.    /* PRTSTR.C: Print strings. */
  8826.  
  8827.    #include <stdio.h>
  8828.    #include <string.h>
  8829.  
  8830.    main()
  8831.    {
  8832.       char aline[80], more[80];
  8833.       char *strptr;
  8834.  
  8835.       /* aline = "Another line."; */
  8836.       /* Note: This causes a compiler error */
  8837.  
  8838.       strcpy( aline, "Another line." );
  8839.       strcpy( more, aline );
  8840.       strptr = aline;
  8841.       strcat( aline, "dog" );
  8842.       printf( "A line of text." );
  8843.       printf( aline );
  8844.       printf( more );
  8845.       printf( strptr );
  8846.    }
  8847.  
  8848.  The declarations come first:
  8849.  
  8850.    char aline[80], more[80];
  8851.    char *strptr;
  8852.  
  8853.  The variables  aline  and  more  are arrays of characters. In this program,
  8854.  they act as strings. Although these arrays have 80 characters each (numbered
  8855.  0-79), the maximum string length is 79 characters, because strings must end
  8856.  with a null character. The variable  strptr  is a pointer to a string.
  8857.  
  8858.  If you've previously programmed in BASIC, you might expect to use the equal
  8859.  sign to assign a value to a string variable. The program won't compile if
  8860.  you remove the comment symbols from the following line:
  8861.  
  8862.    /* aline = "Another line."; */
  8863.  
  8864.  Faced with this line, QuickC prints the error message:
  8865.  
  8866.    2106: '=' : Left operand must be lvalue
  8867.  
  8868.  (an "lvalue" is a value allowed on the left side of an equal sign).
  8869.  
  8870.   Use the strcpy function─ not the equal sign─ to copy a string.
  8871.  
  8872.  You can use the equal sign to assign a value to a numeric variable. When
  8873.  you're using strings, however, you almost always use the library function
  8874.  strcpy, which copies a string to a character array from either a string
  8875.  constant or another array:
  8876.  
  8877.    strcpy( aline, "Another line." );
  8878.    strcpy( more, aline );
  8879.  
  8880.  The strcpy function makes an exact copy of a string. The first argument is
  8881.  the address of the destination string. The second is the address of the
  8882.  source string. The first strcpy above copies " Another line."  to the  aline
  8883.   string. The second copies  aline  to  more.
  8884.  
  8885.  Note that the first argument must be the address of an array, but the second
  8886.  is either a string constant (enclosed in quotation marks) or the address of
  8887.  a character array.
  8888.  
  8889.  The 80-character arrays have more than enough room for the 13 characters of
  8890.  "Another line."  and a null character. In your own programs, you should be
  8891.  aware of the declared size of an array and avoid overrunning the bounds of
  8892.  the array. See Chapter 10, "Programming Pitfalls," for more information
  8893.  about this programming mistake.
  8894.  
  8895.  It is possible to assign the address of a string to a pointer:
  8896.  
  8897.    strptr = aline;
  8898.  
  8899.  Notice that both  strptr  and  aline  point to the same string. There's one
  8900.  object in memory, but it has two different names. If  aline  changes, the
  8901.  same change occurs in the string referenced by  strptr, because they're the
  8902.  same string. Below, the word "dog"  is added to the end of the string
  8903.  aline:
  8904.  
  8905.    strcat( aline, "dog" );
  8906.  
  8907.  The strcat function concatenates one string to the end of a second string.
  8908.  In the line above, both  aline  and the string referenced by  strptr  have
  8909.  been changed from  "Another line."  to  "Another line.dog".
  8910.  
  8911.  Now four printf statements execute:
  8912.  
  8913.    printf( "A line of text." );
  8914.    printf( aline );
  8915.    printf( more );
  8916.    printf( strptr );
  8917.  
  8918.  The screen should look like this:
  8919.  
  8920.    A line of text.Another line.dogAnother line.Another line.dog
  8921.  
  8922.  To the first printf we passed a string constant. To the other three we
  8923.  passed names of strings. Concatenating  aline  and  "dog"  also affected the
  8924.  string referenced by  strptr, because they both point to the same string in
  8925.  memory. The contents of  more  weren't affected, however, because the strcpy
  8926.  function makes a complete and unique copy of the source string at the memory
  8927.  location referenced by  more.
  8928.  
  8929.  Unfortunately, the strings ran together. As we saw in Chapter 1, "Anatomy of
  8930.  a C Program," printf is unlike QuickBASIC's PRINT command or Pascal's
  8931.  Writeln procedure in one respect: it does not automatically move the cursor
  8932.  to the beginning of the next line. You need to include the newline character
  8933.  (\n), which is one of a series of available escape codes discussed in
  8934.  Chapter 4, "Data Types." The program below includes a few examples of escape
  8935.  codes, each of which begins with the backslash character:
  8936.  
  8937.    /* PRTESC.C: Print escape characters \",\n, and \t. */
  8938.  
  8939.    #include <stdio.h>
  8940.    #include <string.h>
  8941.  
  8942.    main()
  8943.    {
  8944.       char b[80];
  8945.       int i,j;
  8946.  
  8947.       strcpy( b, "and seven years ago\n" );
  8948.       printf( "\"Four score\n" );
  8949.       printf( b );
  8950.       printf( "\tone tab\n\t\ttwo tabs\n\t\t\tthree tabs\n" );
  8951.       i = sizeof( b );
  8952.       j = strlen( b );
  8953.       printf( "Size is %d\nLength is %d.\n", i, j );
  8954.    }
  8955.  
  8956.  If you compile and run the PRTESC.C program, the following text prints on
  8957.  the screen:
  8958.  
  8959.    "Four score
  8960.    and seven years ago
  8961.     one tab
  8962.      two tabs
  8963.       three tabs
  8964.    Size is 80
  8965.    Length is 20.
  8966.  
  8967.  To print a newline character in a string, type a backslash and the letter n
  8968.  (\n). For a quotation mark, use \". For tabs, use \t. Escape sequences can
  8969.  appear anywhere within a string:
  8970.  
  8971.    printf( "\tone tab\n\t\ttwo tabs\n\t\t\tthree tabs\n" );
  8972.  
  8973.  You'll find complete lists of escape characters in Appendix A, "C Language
  8974.  Guide," and in online help.
  8975.  
  8976.  
  8977.  Finding the Size
  8978.  
  8979.  The last call to printf in PRTESC.C provides two pieces of information: the
  8980.  size of the character array and the length of the string inside the array.
  8981.  
  8982.  The variable  b  was declared to be an 80-character array, but the string
  8983.  inside b  contains only 20 characters; it holds 19 letters plus one newline
  8984.  character. Although typing \n takes two characters, it's stored in memory as
  8985.  one character─ the ASCII value 10. As we'll see later in this chapter, the
  8986.  newline character is sometimes expanded to two characters (a carriage return
  8987.  and a linefeed) when it is written to disk. But while it's in memory, it's a
  8988.  single character.
  8989.  
  8990.   The sizeof operator examines array size; the strlen function returns the
  8991.  length of a string.
  8992.  
  8993.  There are two methods available to find the size of arrays and strings. The
  8994.  sizeof operator returns the size (in bytes) of an identifier or type. The
  8995.  string-handling function strlen counts the number of characters in a string,
  8996.  up to but not including the null that marks the end of the string:
  8997.  
  8998.    i = sizeof( b );
  8999.    j = strlen( b );
  9000.    printf( "Size is %d\nLength is %d.\n", i, j );
  9001.  
  9002.  The final line of the program PRTESC.C prints out two integer values, which
  9003.  follow the format string. When printf evaluates the format string, it
  9004.  substitutes the two values for the %d specifiers:
  9005.  
  9006.    Size is 80
  9007.    Length is 20
  9008.  
  9009.  The sizeof operator is part of the C language. In this example, it evaluates
  9010.  to the value 80, which is the size of the array. The strlen function is a
  9011.  library function for measuring strings (up to, but not including the null at
  9012.  the end). It returns a 20 because that's the length of the string.
  9013.  
  9014.  
  9015.  Printing Numeric Values
  9016.  
  9017.   The printf format string  may hold one or more  format specifiers.
  9018.  
  9019.  We've seen how printf requires at least one string (or a pointer to a
  9020.  string). To print variables and values, place a comma and the name of the
  9021.  variable or value after the format string. Then, within the format string,
  9022.  include a format specification. See Table 11.2.
  9023.  
  9024.  Table 11.2  Common Format Specifications
  9025.  
  9026. ╓┌─────────────────────┌─────────────────────────────────────────────────────╖
  9027.  Specification         Format
  9028.  ────────────────────────────────────────────────────────────────────────────
  9029.  %c                    Print a character
  9030.  %d                    Print a decimal integer
  9031.  %f                    Print a floating-point number
  9032.  Specification         Format
  9033.  ────────────────────────────────────────────────────────────────────────────
  9034. %f                    Print a floating-point number
  9035.  %i                    Print a decimal integer (same as %d)
  9036.  %s                    Print a string
  9037.  %u                    Print an unsigned integer
  9038.  %x                    Print in hexadecimal format
  9039.  ────────────────────────────────────────────────────────────────────────────
  9040.  
  9041.  
  9042.  The percent sign (%) always marks the beginning of a format specification.
  9043.  The letters c, d, f, i, s, u, and x are called the "type." Between the
  9044.  percent sign and the type, you may include optional specifications for
  9045.  flags, width, or precision values.
  9046.  
  9047.  At the very least, you must include the type, as in the program below:
  9048.  
  9049.    /* NFORMAT.C: Print numbers and a string. */
  9050.  
  9051.    #include <stdio.h>
  9052.    #include <string.h>
  9053.  
  9054.    main()
  9055.    {
  9056.       int    a = -765,
  9057.              b = 1,
  9058.              c = 44000,
  9059.              d = 33;
  9060.       float  e = 1.33E8,
  9061.              f = -0.1234567,
  9062.              g = 12345.6789,
  9063.              h = 1.0;
  9064.       char   i[80];
  9065.  
  9066.       strcpy( i, "word 1, word 2, word 3, word 4, word 5" );
  9067.  
  9068.       printf( "Unformatted:\n%d %d %d %d\n", a, b, c, d );
  9069.       printf( "%f %f %f %f\n", e, f, g, h );
  9070.       printf( "%s\n", i );
  9071.    }
  9072.  
  9073.  The output looks like this:
  9074.  
  9075.    Unformatted:
  9076.    -765 1 -21536 33
  9077.    133000000.000000 -0.123457 12345.678711 1.000000
  9078.    word 1, word 2, word 3, word 4, word 5
  9079.  
  9080.  If you carefully compare NFORMAT.C with its output, you'll notice some
  9081.  unexpected results. For example, the variable  c, which was initialized to
  9082.  44000, has somehow changed to -21536.
  9083.  
  9084.  The %d format specification applies to signed integers in the range -32768
  9085.  to +32767. The value of  c  (44000) is outside that range, but still within
  9086.  the realm of unsigned integers, which can hold values up to +65535. The
  9087.  proper format specification would be %u (where  u  represents the unsigned
  9088.  type).
  9089.  
  9090.  Two of the floating-point values have changed, too. The %f specification
  9091.  defaults to 6 digits of precision to the right of the decimal point. The
  9092.  value of  f  (.1234567) is therefore rounded off to a precision of 6 digits:
  9093.  .123457. Also, the limitations of floating-point accuracy transform the
  9094.  value of  g  from 12345.6789 to 12345.678711. If you modify the program,
  9095.  changing the  float  declarations to  double, the second problem disappears.
  9096.  The variable  g  prints correctly as 12345.67.
  9097.  
  9098.  Between the% and the type character, you may include two numbers separated
  9099.  by a period. The first number is called the "width;" the second is the
  9100.  "precision." The width and precision affect integers, floating-point
  9101.  numbers, and strings in different ways. For example, we could specify a
  9102.  width of 2 and precision of 3 for each of the above variables:
  9103.  
  9104.    printf( "\nWidth 2, Precision 3:\n" );
  9105.    printf( "%2.3d %2.3d %2.3u %2.3d\n", a, b, c, d );
  9106.    printf( "%2.3f %2.3f %2.3f %2.3f\n", e, f, g, h );
  9107.    printf( "%2.3s\n", i );
  9108.  
  9109.  (Note that the variable  c  has a format specifier of  %2.3u  instead of
  9110.  %2.3d.) The screen displays the following lines:
  9111.  
  9112.    Width 2, Precision 3:
  9113.    -765 001 44000 033
  9114.    133000000.000 -0.123 12345.679 1.000
  9115.    wor
  9116.  
  9117.  For integers, the precision of 3 causes at least 3 digits to print, preceded
  9118.  by leading zeros. For floating-point numbers, the precision of 3 truncates
  9119.  fractions to 3 digits to the right of the decimal point. For strings, the
  9120.  precision of 3 causes only 3 characters to print. The string output is
  9121.  truncated to the right. Numbers are never truncated, however.
  9122.  
  9123.  We can change the width to 8 and the precision to 1:
  9124.  
  9125.    printf( "\nWidth 8, Precision 1:\n" );
  9126.    printf( "%8.1d %8.1d %8.1u %8.1d\n", a, b, c, d );
  9127.    printf( "%8.1e %8.1f %8.1f %8.1f\n", e, f, g, h );
  9128.    printf( "%8.1s\n", i );
  9129.  
  9130.  We made an additional modification by printing the variable  e  as an %e
  9131.  type instead of an %f type. This prints the value of  e  (1.33E8) in
  9132.  exponential format:
  9133.  
  9134.    Width 8, Precision 1:
  9135.        -765        1    44000       33
  9136.    1.3e+008     -0.1  12345.7      1.0
  9137.           w
  9138.  
  9139.  The width controls the printing area: all 3 variable types are printed in
  9140.  fields 8 characters wide. The precision of 1 affects different data types in
  9141.  different ways: the integers print at least 1 digit; the floating-point
  9142.  numbers print only the first number to the right of the decimal point; and
  9143.  the string prints as the first character only. Each value prints flush right
  9144.  in its field.
  9145.  
  9146.  Between the % and the width, you may also insert a flag. The plus flag (+),
  9147.  for example, forces numbers to print with a leading sign:
  9148.  
  9149.    printf( "\nForced signs, Width 10, Precision 2:\n" );
  9150.    printf( "%+10.2d %+10.2d %+10.2u %+10.2d\n", a, b, c, d );
  9151.    printf( "%+10.2e %+10.2f %+10.2f %+10.2f\n", e, f, g, h );
  9152.    printf( "%+10.2s\n", i );
  9153.  
  9154.  Note that the plus flag has no effect on strings or on unsigned integers:
  9155.  
  9156.    Forced signs, Width 10, Precision 2:
  9157.          -765        +01      44000        +33
  9158.    +1.33e+008      -0.12  +12345.68      +1.00
  9159.            wo
  9160.  
  9161.  Another flag is the number 0, which forces leading zeros to print within the
  9162.  limits of the width. If you only specify the width, the system default is
  9163.  used for the precision. You can use the type %x to represent hexadecimal; it
  9164.  displays the letters a-f in lowercase. If you prefer uppercase, you can use
  9165.  %X instead.
  9166.  
  9167.    printf( "\nHexadecimal, Forced Zeros, Width 6:\n" );
  9168.    printf( "%06x %06x %06x %06x\n", a, b, c, d );
  9169.  
  9170.  The printf statements above display these lines:
  9171.  
  9172.    Hexadecimal, Forced Zeros, Width 6:
  9173.    00fd03 000001 00abe0 000021
  9174.  
  9175.  For strings, the width and precision specifiers describe the field width and
  9176.  the number of characters printed. Note the minus sign in the final line,
  9177.  which forces the truncated string to print from the left:
  9178.  
  9179.    printf( "\nWidth 40, Precision 10:\n" );
  9180.    printf( "%40.10s\n", i );
  9181.  
  9182.    printf( "\nWidth 40, Precision 20:\n" );
  9183.    printf( "%40.20s\n", i );
  9184.  
  9185.    printf( "\nFlush left, Width 40, Precision 20:\n" );
  9186.    printf( "%-40.20s\n", i );
  9187.  
  9188.  The lines are displayed on the screen as follows:
  9189.  
  9190.    Width 40, Precision 10:
  9191.                                  word 1, wo
  9192.  
  9193.    Width 40, Precision 20:
  9194.                        word 1, word 2, word
  9195.  
  9196.    Flush left, Width 40, Precision 20:
  9197.    word 1, word 2, word
  9198.  
  9199.  
  9200.  Using scanf for Keyboard Input
  9201.  
  9202.     Pass a variable address to scanf, not a variable value.
  9203.  
  9204.  While printf is the most widely used output function, scanf is the most
  9205.  popular for input. The arguments and format strings passed to scanf resemble
  9206.  the arguments for printf, except for one requirement: the scanf function
  9207.  always takes pointers. You never pass a variable value to scanf, you always
  9208.  pass the variable address so that scanf can store data in the memory
  9209.  location that contains the input variable.
  9210.  
  9211.  The first argument for scanf is always a format string. Additional arguments
  9212.  include the addresses of variables to which values will be assigned.
  9213.  
  9214.  The program below demonstrates several ways to use scanf and various other
  9215.  I/O functions:
  9216.  
  9217.    /* INPUT.C: Read keyboard. */
  9218.  
  9219.    #include <stdio.h>
  9220.    #include <conio.h>
  9221.    #include <ctype.h>
  9222.  
  9223.    main()
  9224.    {
  9225.       int num;
  9226.       char c;
  9227.       char name[80];
  9228.       float rb;
  9229.  
  9230.       puts( "** Type \"Name:\" and your name" );
  9231.       scanf( "Name: %40s", name );
  9232.       printf( "** You typed this:\n%s", name );
  9233.       puts( "\n\n** Try again, with the gets function." );
  9234.       fflush( stdin );
  9235.       gets( name );
  9236.       printf( "** You typed this:\n%s\n", name );
  9237.  
  9238.       printf( "\n** Now type an integer.\n" );
  9239.       scanf( "%i", &num );
  9240.       sprintf( name, "** You typed this number: %i\n", num );
  9241.       puts( name );
  9242.  
  9243.       fflush( stdin );
  9244.       printf( "** Enter a floating-point value.\n" );
  9245.       scanf( "%f", &rb );
  9246.       printf( "** The answer is %f or %e\n", rb, rb );
  9247.  
  9248.       printf( "** Continue? Y or N\n" );
  9249.       do
  9250.       {
  9251.          c = getch();
  9252.          c = tolower( c );
  9253.       } while( c != 'y' && c != 'n' );
  9254.    }
  9255.  
  9256.  First, the puts function prints a string that requests input from the user.
  9257.  Then scanf reads the input:
  9258.  
  9259.    puts( "** Type \"Name:\" and your name" );
  9260.    scanf( "Name: %40s", name );
  9261.  
  9262.  Unfortunately, the use of scanf for string input creates some difficulties.
  9263.  For one thing, you're forced to type  Name:  before typing the rest of the
  9264.  string. (If you don't type  Name:, scanf won't put a value into the  name
  9265.  variable.)
  9266.  
  9267.  A second problem is that scanf reads the input stream until it finds a
  9268.  white-space character: a SPACE, TAB, or ENTER.
  9269.  
  9270.  The prompt below appears on the screen:
  9271.  
  9272.    ** Type "Name:" and your name
  9273.  
  9274.  You might type this (you must begin the line with "Name:" ):
  9275.  
  9276.    Name: F. Scott Fitzgerald
  9277.  
  9278.  The next line takes effect:
  9279.  
  9280.    printf( "** You typed this:\n%s", name );
  9281.  
  9282.  Which prints the following line:
  9283.  
  9284.    ** You typed this:
  9285.    F.
  9286.  
  9287.  The string passed to the scanf function told it to expect  "Name:"  and then
  9288.  to read a string, storing it in the  name  variable.
  9289.  
  9290.  Since the scanf function reads strings until it finds a white-space
  9291.  character, the value of  name  is "  F." In addition, the words  Scott
  9292.  Fitzgerald  are waiting in the input stream. To clear any stream, use the
  9293.  fflush function:
  9294.  
  9295.    puts( "\n\n** Now try it again, with the gets function." );
  9296.    fflush( stdin );
  9297.    gets( name );
  9298.  
  9299.  To clear the buffer associated with a stream (including disk files), call
  9300.  fflush, passing the pointer to the file or stream. In the example above,
  9301.  stdin  is the standard input device, the keyboard.
  9302.  
  9303.  The puts function acts like a limited version of printf. It prints a string
  9304.  to the standard output device, but can't insert formatted variable values.
  9305.  You pass it a string constant or the name of a string. Also, it always adds
  9306.  a newline to the end of the string it prints.
  9307.  
  9308.   It is usually preferable to  use gets when working  with string input.
  9309.  
  9310.  The gets function receives an entire line from the standard input device and
  9311.  places the line in an array of characters. It does not include the newline
  9312.  character typed by the user. It does, however, add a null to the end of the
  9313.  line, to make the series of characters into a string. When you're working
  9314.  with string input, gets is generally preferable to scanf.
  9315.  
  9316.  For numeric values, scanf is the function of choice:
  9317.  
  9318.    printf( "\n** Now type an integer.\n" );
  9319.    scanf( "%i", &num );
  9320.    sprintf( name, "** You typed the number: %i\n", num );
  9321.    puts( name );
  9322.  
  9323.  The format string %i forces scanf to treat the input as an integer. The
  9324.  second argument is the address of the variable  num.
  9325.  
  9326.  The letter s in sprintf marks it as a string function. (There is also a
  9327.  sscanf function that handles strings, but we won't discuss it here.) Instead
  9328.  of printing the format string to the screen, as printf would do, sprintf
  9329.  prints the results to another string. Note that scanf requires the address
  9330.  of  num, but sprintf uses its value.
  9331.  
  9332.  The next scanf in program INPUT.C treats the input as a floating-point
  9333.  number:
  9334.  
  9335.    scanf( "%f", &rb );
  9336.    printf( "** The answer is %f or %e\n", rb, rb );
  9337.  
  9338.  If you enter -555.12, the computer responds:
  9339.  
  9340.    ** The answer is -555.119995 or -5.551200e+002
  9341.  
  9342.  Finally, the program uses getch to receive a character from the input
  9343.  stream:
  9344.  
  9345.    printf( "** Continue? Y or N\n" );
  9346.  
  9347.       do
  9348.       {
  9349.          c = getch();
  9350.          c = tolower( c );
  9351.       } while( c != 'y' && c != 'n' );
  9352.  
  9353.  The getch function returns a character. That value, in turn, is passed to
  9354.  tolower, which converts any uppercase characters to lowercase (in case the
  9355.  CAPS LOCK key is on). Then, the byte is assigned to the variable  c. The do
  9356.  loop continues processing characters until you press  y  or  n. The program
  9357.  then ends. This simple example ends no matter which key (  y  or  n ) you
  9358.  press. A real program would take some action based on the value returned by
  9359.  the getch function.
  9360.  
  9361.  
  9362.  Standard Disk I/O
  9363.  
  9364.  If you can read input from the keyboard and write output to the screen,
  9365.  you'll find standard disk files relatively easy to manipulate. There are
  9366.  three rules to remember:
  9367.  
  9368.  
  9369.    1.  You can't do anything with a disk file until you open it. The act of
  9370.        opening a file gives you a FILE pointer through which you can access
  9371.        the file.
  9372.  
  9373.    2.  While the file is open, you can use most of the screen and keyboard
  9374.        I/O functions if you precede them with the letter f (fprintf instead
  9375.        of printf, for example). The file-handling functions work the same as
  9376.        their counterparts, but you must add the FILE pointer.
  9377.  
  9378.    3.  When you're finished with a file, it's good programming practice to
  9379.        close it. When exit ends the execution of a program, all previously
  9380.        open files are closed (if you'd rather leave them open, use _exit
  9381.        instead of exit).
  9382.  
  9383.  
  9384.  
  9385.  Creating and Writing to a Text File
  9386.  
  9387.  The WRFILE.C program opens a text file, writes a string to it, and closes
  9388.  the file.
  9389.  
  9390.    /* WRFILE.C: Create and write to a disk file. */
  9391.  
  9392.    #include <stdio.h>
  9393.  
  9394.    main()
  9395.    {
  9396.       FILE *fp;
  9397.  
  9398.       if( (fp = fopen( "c:\\testfile.asc","w" )) != NULL )
  9399.       {
  9400.          fputs( "Example string", fp );
  9401.          fputc( '\n', fp );
  9402.          fclose( fp );
  9403.       }
  9404.       else
  9405.          printf( "error message\n" );
  9406.    }
  9407.  
  9408.  You must include the standard I/O header file ( #include <stdio.h> )
  9409.  whenever you plan to call input or output functions. It contains essential
  9410.  definitions and prototypes that you need.
  9411.  
  9412.  The only variable in this program is  fp  which is declared as a pointer to
  9413.  a FILE. FILE is defined in STDIO.H as a structure of _iobuf type, but we
  9414.  don't need to know the specifics. We will refer to the variable  fp  as a
  9415.  "FILE pointer."
  9416.  
  9417.  The first statement combines several operations in one line:
  9418.  
  9419.    if( (fp = fopen( "c:\\testfile.asc", "w" )) != NULL )
  9420.  
  9421.  The fopen function opens a file. It expects two parameters, both of which
  9422.  are literal strings or pointers to strings. You provide the name of the file
  9423.  to be opened and the type (read, write, or append). The six types of files
  9424.  are listed in Table 11.3.
  9425.  
  9426.  Table 11.3  Disk File Types
  9427.  
  9428. ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
  9429.  Type                              Action
  9430.  ────────────────────────────────────────────────────────────────────────────
  9431.  Type                              Action
  9432.  ────────────────────────────────────────────────────────────────────────────
  9433.  r                                 Open an existing file for reading.
  9434.  
  9435.  w                                 Create and open a file for writing. Any
  9436.                                    existing file is replaced. If the file
  9437.                                    doesn't exist, a new file is created.
  9438.  
  9439.  a                                 Open a file for appending. Data is added
  9440.                                    to the end of an existing file or
  9441.                                    a new file is created.
  9442.  
  9443.  r+                                Open an existing file for reading and
  9444.                                    writing.
  9445.  
  9446.  w+                                Create and open a file for reading and
  9447.                                    writing. An existing file is replaced.
  9448.  
  9449.  a+                                Open a file for reading and appending.
  9450.                                    Data is added to the end of an
  9451.                                    existing file or a new file is created.
  9452.  Type                              Action
  9453.  ────────────────────────────────────────────────────────────────────────────
  9454.                                   existing file or a new file is created.
  9455.  
  9456.  ────────────────────────────────────────────────────────────────────────────
  9457.  
  9458.  
  9459.  
  9460.  In WRFILE.C, the file called  c:\testfile.asc  is opened for writing with
  9461.  type "w"  (a string, not the character  'w'  in single quotes). We plan to
  9462.  write to it.
  9463.  
  9464.  Notice that the file-name string as it appears in the fopen statement
  9465.  contains two backslashes: "c:\\testfile.asc". If you tried to use the string
  9466.  "c:\testfile. asc", which looks correct, the character sequence  \t  would
  9467.  be incorrectly interpreted as a tab character. C automatically converts the
  9468.  two backslashes in the string to a single backslash.
  9469.  
  9470.  
  9471.  Getting a FILE Pointer
  9472.  
  9473.  The fopen function returns the address of a FILE. This value is assigned to
  9474.  fp, which is the FILE pointer used in all subsequent file operations.
  9475.  
  9476.  If something goes wrong─if the disk is full or not in the drive or
  9477.  write-protected or whatever─fopen doesn't return a FILE pointer. When fopen
  9478.  fails, it returns a null value.
  9479.  
  9480.  What we're looking for is any FILE pointer that's not null:
  9481.  
  9482.    if( (fp = fopen( "c:\\testfile.asc","w" )) != NULL )
  9483.  
  9484.  
  9485.  Writing to the File
  9486.  
  9487.  As we saw earlier, puts displays a string on the screen. Add an f to it and
  9488.  the result is fputs, which works similarly. It sends the string to a
  9489.  specified stream (a file) instead of to the standard output device:
  9490.  
  9491.    fputs( "Example string", fp );
  9492.  
  9493.  The function fputs takes two parameters: a pointer to the string and the
  9494.  FILE pointer. In this and other I/O functions, you refer to the file by name
  9495.  only once (when you use fopen). Thereafter, you use its FILE pointer.
  9496.  
  9497.  The fputs function writes the entire string to the file but does not include
  9498.  the null that marks the end of the string. Nor does it write a newline
  9499.  character─unless the string already contains a newline.
  9500.  
  9501.  The fputc function writes a character to a file. In the following line, the
  9502.  newline character is sent to the file:
  9503.  
  9504.    fputc( '\n', fp );
  9505.  
  9506.  
  9507.  Closing the File
  9508.  
  9509.  When the writing is done, fclose closes the file:
  9510.  
  9511.    fclose( fp );
  9512.  
  9513.  Conceptually, you can imagine that file I/O functions such as fputs and
  9514.  fputc write directly to the disk file. In reality, they're storing strings
  9515.  and characters in an intermediate area (called a "memory buffer"). When the
  9516.  buffer fills up, the entire chunk of memory is sent to the file. The process
  9517.  of emptying the buffer is called "flushing." You may forcibly flush the
  9518.  buffer with the fflush and fclose functions. If you do not close the file
  9519.  before exiting the program, the buffer is not flushed and you may lose data
  9520.  that might remain there.
  9521.  
  9522.  The else clause in WRFILE.C should execute only if something has gone wrong
  9523.  with the fopen function:
  9524.  
  9525.    else
  9526.       printf( "error message\n" );
  9527.  
  9528.  This line executes if an error occurs when fopen tries to create the file.
  9529.  Handling errors is covered in more detail later in this chapter.
  9530.  
  9531.  
  9532.  Reading a Text File in Binary Mode
  9533.  
  9534.  The WRFILE.C program that created and wrote to a file was fairly simple.
  9535.  Here's an equally simple program to read the file just created:
  9536.  
  9537.    /* RDFILE.C: Read a file and print characters to the screen. */
  9538.  
  9539.    #include <stdio.h>
  9540.  
  9541.    main()
  9542.    {
  9543.       int c;
  9544.       FILE *fp;
  9545.  
  9546.       if( fp = fopen( "c:\\testfile.asc", "rb" ) )
  9547.       {
  9548.          while( (c = fgetc( fp )) != EOF )
  9549.             printf( " %c\t%d\n", c, c );
  9550.          printf( "\nEnd of file marker: %d", c );
  9551.          fclose( fp );
  9552.       }
  9553.       else
  9554.          printf( "Error in opening file\n" );
  9555.    }
  9556.  
  9557.  Although we plan to read the characters as eight-bit entities, the variable
  9558.  c  should be declared as an int instead of a char. All of the incoming
  9559.  characters will be bytes the size of a char, except one.
  9560.  
  9561.  When the file has been read from beginning to end, the end-of-file (EOF)
  9562.  marker appears on the stream. Within QuickC, an integer value of -1 (0xFFFF)
  9563.  represents EOF. To correctly identify this value, the variable  c  must be
  9564.  an integer.
  9565.  
  9566.  
  9567.  Opening a File for Binary Reading
  9568.  
  9569.  In the line below, the fopen function attempts to open a file. The first
  9570.  argument is the file name; the second is the type and mode, both of which
  9571.  may be literal strings or pointers to strings:
  9572.  
  9573.    if( fp = fopen( "c:\\testfile.asc", "rb" ) )
  9574.  
  9575.  The single backslash character used in path specifications must once again
  9576.  be represented by two backslashes. The file type is r for read-only. The
  9577.  additional b character forces the file to be read in binary mode instead of
  9578.  text mode. The differences between binary and text files are discussed later
  9579.  in this chapter.
  9580.  
  9581.  The fopen function returns a pointer to a FILE. If fopen fails, it returns a
  9582.  NULL pointer.
  9583.  
  9584.  Finally, the if expression tests for a null value. The original WRFILE.C
  9585.  program included the  != NULL  test for inequality. Within the test
  9586.  expression of an if or a while, a 0 value is always false and any other
  9587.  value is considered true. In other words, should  fp  receive a valid
  9588.  nonzero address from fopen, the program continues. If something goes wrong,
  9589.  the remaining lines don't execute and the program drops through to the else.
  9590.  
  9591.  
  9592.  Note that the expression above uses an assignment operator (=), not an
  9593.  equality operator (==). The value returned by fopen is always assigned to
  9594.  fp ; they aren't being compared to each other. Then the if expression tests
  9595.  that value for truth or falsity.
  9596.  
  9597.  
  9598.  Getting a Character
  9599.  
  9600.  The key to the next line in RDFILE.C is the fgetc function, to which you
  9601.  pass a FILE pointer. It returns the next character from the given file:
  9602.  
  9603.    while( (c = fgetc( fp )) != EOF )
  9604.  
  9605.  The character is assigned to the integer variable  c. As long as the
  9606.  character doesn't equal EOF, the while loop continues.
  9607.  
  9608.  The end-of-file marker equals -1, but it's preferable to use the symbolic
  9609.  constant EOF. If the program is transported to another computer, you might
  9610.  find EOF has another value. Using the symbolic constant allows you to
  9611.  maintain compatibility between computers and operating systems.
  9612.  
  9613.  For the same reason, it's preferable to test for NULL instead of assuming
  9614.  that NULL will always equal 0.
  9615.  
  9616.  
  9617.  Viewing the File
  9618.  
  9619.  Since there's only one line inside the while loop, it's not necessary to
  9620.  enclose it in curly braces. The variable  c  contains the character read
  9621.  from the file. It then can be printed:
  9622.  
  9623.    printf( " %c\t%d\n", c, c );
  9624.  
  9625.  The characters from the file print twice, once as a character (%c) and once
  9626.  as a decimal number (%d), separated by a tab stop. This printf statement
  9627.  repeats until fgetc (inside the while loop) finds no more characters in the
  9628.  file.
  9629.  
  9630.  
  9631.  Binary and Text Files
  9632.  
  9633.  Normally, you wouldn't write a file in text mode and then read it in binary
  9634.  mode. As a general rule, you pick whichever mode is more appropriate (text
  9635.  mode for text or binary mode for data) and stick with it.
  9636.  
  9637.  A somewhat baffling thing happened in the example above, however. The
  9638.  WRFILE.C program wrote "Example string"  to a disk file and then added a
  9639.  newline character. That should be a total of 15 characters. But if you
  9640.  examine the directory, you'll see the file uses 16 bytes.
  9641.  
  9642.  Where did the extra byte come from?
  9643.  
  9644.  
  9645.  Testing Text Mode
  9646.  
  9647.  If you ran the RDFILE.C program, you probably noticed two characters
  9648.  followed the line: a carriage return (ASCII 13) and a linefeed (ASCII 10).
  9649.  If you make the following change to the program, the output of RDFILE.C is
  9650.  different:
  9651.  
  9652.    if( (fp = fopen( "c:\\testfile.asc","rt" )) != NULL )
  9653.  
  9654.  The only modification is that the second string is "rt"  instead of "rb".
  9655.  The t represents text mode; the b is binary mode. If you don't specify a
  9656.  mode, the fopen function defaults to text mode.
  9657.  
  9658.  The list below shows the output of the two programs.
  9659.  
  9660. ╓┌────────────────────────────────┌──────────────────────────────────────────╖
  9661.  RDFILE.C  (binary mode)          RDFILE.C  (text mode)
  9662.  RDFILE.C  (binary mode)          RDFILE.C  (text mode)
  9663.  ────────────────────────────────────────────────────────────────────────────
  9664.  E69                              E69
  9665.  x120                             x120
  9666.  a97                              a97
  9667.  m109                             m109
  9668.  p112                             p112
  9669.  l108                             l108
  9670.  e101                             e101
  9671.  32                               32
  9672.  s115                             s115
  9673.  t116                             t116
  9674.  r114                             r114
  9675.  i105                             i105
  9676.  n110                             n110
  9677.  g103                             g103
  9678.  13                               10
  9679.  10                               End-of-file marker: -1
  9680.  End-of-file marker: -1
  9681.  ────────────────────────────────────────────────────────────────────────────
  9682.  
  9683.  
  9684.  In binary mode there seems to be two characters after the string. In text
  9685.  mode there's only one.
  9686.  
  9687.  
  9688.  Ends-of-Lines, Ends-of-Files
  9689.  
  9690.  The two modes─binary and text─treat end-of-line (EOL) characters and
  9691.  end-of-file (EOF) characters in different ways.
  9692.  
  9693.  In DOS, a line of text ends with a carriage return (CR) and a linefeed (LF),
  9694.  which appear above as ASCII 13 plus ASCII 10. In the UNIX operating system,
  9695.  which has close ties to the C language, a single ASCII 10 (the newline
  9696.  character) marks the end of a line.
  9697.  
  9698.  The once-popular CP/M operating system signals the end of files with a
  9699.  CTRL+Z character (ASCII 26, 0x1A)─a tradition that carried forward to DOS.
  9700.  This is not the case with UNIX (and C), which don't use a unique EOF
  9701.  character.
  9702.  
  9703.  
  9704.  Text Mode Translations
  9705.  
  9706.  It's important to understand the differences between text mode and binary
  9707.  mode when writing and reading disk files. No translations are made in binary
  9708.  mode. In text mode, however, the end-of-line and end-of-file characters are
  9709.  translated.
  9710.  
  9711.  When you read a file in text mode and a CR-LF combination appears in the
  9712.  stream, the two characters are translated to one newline character. The
  9713.  opposite translation occurs when you write a file in text mode: each CR-LF
  9714.  combination is translated to one newline character. In other words, the
  9715.  newline is represented by two characters on disk and one character in
  9716.  memory. These translations do not occur when you read and write a file in
  9717.  binary mode.
  9718.  
  9719.  When you read a file in text mode and a CTRL+Z (0x1A) character appears in
  9720.  the stream, the character is interpreted as the end-of-file character.
  9721.  However, when you're in text mode and you close a file to which you've been
  9722.  writing, a CTRL+Z is not placed in the file as the last character. In binary
  9723.  mode, the CTRL+Z character has no special meaning (it is not interpreted as
  9724.  the end-of-file character).
  9725.  
  9726.  The difference between text mode and binary mode is relatively minor when
  9727.  you're handling strings, but it's important when you're writing numeric
  9728.  values to disk files.
  9729.  
  9730.  
  9731.  Text Format for Numeric Variables
  9732.  
  9733.  Many programs, of course, use numeric as well as character data. When you
  9734.  wish to save numbers, you have two choices: text mode or binary mode. The
  9735.  SVTEXT.C program below illustrates the less desirable way of creating files
  9736.  for numeric variables.
  9737.  
  9738.    /* SVTEXT.C: Save integer variables as text. */
  9739.  
  9740.    #include <stdio.h>
  9741.  
  9742.    int list[] = { 53, -23456, 50, 500, 5000, -99 };
  9743.    extern int errno;
  9744.    char fname[] = "numtext";
  9745.    char temp[81];
  9746.  
  9747.    main()
  9748.    {
  9749.       FILE *fptr;
  9750.       int i;
  9751.  
  9752.       if( (fptr = fopen( "numtext","wt" )) != NULL )
  9753.       {
  9754.          for( i=0; i<6; i++ )
  9755.             fprintf( fptr, "Item %d: %6d \n", i, list[i] );
  9756.          fclose( fptr );
  9757.       }
  9758.       else
  9759.          printf( "Error: Couldn't create file.\n" );
  9760.  
  9761.       if( (fptr = fopen( "badname", "rt" )) != NULL )
  9762.       {
  9763.          /* do nothing */
  9764.       }
  9765.       else
  9766.       {
  9767.          printf( "Error number: %d\n\t", errno );
  9768.          perror( "Couldn't open file BADNAME\n\t" );
  9769.       }
  9770.  
  9771.       if( (fptr = fopen( fname, "rt" )) != NULL )
  9772.       {
  9773.          list[0] = 0;
  9774.          fscanf( fptr, "Item %d: %d \n", &i, &list[0] );
  9775.          printf( "Values read from file:\t %d %d\n", i, list[0] );
  9776.          fgets( temp, 80, fptr );
  9777.          printf( "String from file: \t%s\n", temp );
  9778.          while( (i = fgetc( fptr )) != '\n' )
  9779.             printf( "char: %c \t ASCII: %d \n", i, i );
  9780.          rewind( fptr );
  9781.          printf( "Rewind to start -->\t%s", fgets( temp, 80, fptr ) );
  9782.          fclose( fptr );
  9783.       }
  9784.       else      printf( "Trouble opening %s \n", fname );
  9785.    }
  9786.  
  9787.  The SVTEXT.C program does three things:
  9788.  
  9789.  
  9790.    1.  First, it creates a text file called NUMTEXT. If you TYPE NUMTEXT from
  9791.        the DOS prompt or load the NUMTEXT file into a word processor, it
  9792.        looks like this:
  9793.  
  9794.        Item 0:     53
  9795.        Item 1: -23456
  9796.        Item 2:     50
  9797.        Item 3:    500
  9798.        Item 4:   5000
  9799.        Item 5:    -99
  9800.  
  9801.  
  9802.    2.  Next, SVTEXT.C deliberately attempts to open a nonexistent file called
  9803.        BADNAME, to cause a disk error. This section serves no purpose except
  9804.        to illustrate error handling.
  9805.  
  9806.    3.  Finally, it reads parts of NUMTEXT, using several file-input
  9807.        functions.
  9808.  
  9809.  
  9810.  
  9811.  Opening the File for Writing
  9812.  
  9813.  By now, the fopen function should look familiar to you. The only change in
  9814.  the block below is the "wt"  mode. The fopen function returns a NULL if any
  9815.  errors occur, so the block after the if should execute if fopen succeeds.
  9816.  
  9817.    if( (fptr = fopen( "numtext","wt" )) != NULL )
  9818.    {
  9819.       for( i=0; i<6; i++ )
  9820.          fprintf( fptr, "Item %d: %6d \n", i, list[i] );
  9821.       fclose( fptr );
  9822.    }
  9823.    else
  9824.       printf( "Error: Couldn't create file.\n" );
  9825.  
  9826.  The for loop counts from 0 to 5, printing 6 strings to the file. The fprintf
  9827.  function works the same as printf with one change. You must place the FILE
  9828.  pointer before the format string.
  9829.  
  9830.  
  9831.  Error Handling
  9832.  
  9833.  To illustrate what happens when something goes wrong, the next line creates
  9834.  a disk error (as long as you don't have a file called BADNAME in your
  9835.  working directory).
  9836.  
  9837.    if( (fptr = fopen( "badname", "rt" )) != NULL )
  9838.  
  9839.  The if block is empty, because we expect the program to drop through to the
  9840.  else clause that handles errors:
  9841.  
  9842.    else
  9843.    {
  9844.       printf( "Error number: %d\n\t", errno );
  9845.       perror( "Couldn't open file BADNAME\n\t" );
  9846.    }
  9847.  
  9848.  The else block shows two ways you can deal with errors. Note that the errno
  9849.  variable, which was declared as an external integer, has never been assigned
  9850.  a value. QuickC automatically puts error numbers into errno. In this
  9851.  program, the error number is printed to the screen. In your own programs,
  9852.  you might wish to branch to various error-handling routines, based on the
  9853.  value in the system variable errno. For a list of values for errno, see the
  9854.  individual online help entries for file-handling functions.
  9855.  
  9856.  It's important to remember that the standard output device is the screen and
  9857.  that printf sends messages to stdout. However, if you redirect output to a
  9858.  disk file, using a command line such as  SVTEXT > MYFILE, the printf
  9859.  statement prints the error message to MYFILE. In most cases, you'd prefer to
  9860.  see the error message on the screen.
  9861.  
  9862.  The second, and better, way to handle I/O errors is the perror function,
  9863.  which prints two strings: one that you pass to it and one that spells out─in
  9864.  English─the error message. This message goes to the standard error stream
  9865.  (stderr), which is always the screen, regardless of whether you've
  9866.  redirected output or not. For this reason, perror is preferable to printf
  9867.  for printing error messages.
  9868.  
  9869.  The error messages should look like this on your screen:
  9870.  
  9871.    Error number: 2
  9872.       Couldn't open file BADNAME
  9873.       : No such file or directory
  9874.  
  9875.  
  9876.  Reading Text with fscanf
  9877.  
  9878.  The final fopen in SVTEXT.C opens the file created earlier:
  9879.  
  9880.    if( (fptr = fopen( fname, "rt" )) != NULL )
  9881.  
  9882.  Note that we passed the name of a string rather than a literal string.
  9883.  
  9884.  Below, fscanf reads in two numeric variables from the first string in the
  9885.  file. Note that it works the same as scanf, but you add the FILE pointer as
  9886.  the first argument:
  9887.  
  9888.    fscanf( fptr, "Item %d: %d \n", &i, &list[0] );
  9889.    printf( "Values read from file:\t %d %d\n", i, list[0] );
  9890.  
  9891.  
  9892.  Reading Text with fgets and fgetc
  9893.  
  9894.  At this point, the first line in the file has been read and converted to two
  9895.  integer values. The file is straight text, so you can treat the second line
  9896.  as a string:
  9897.  
  9898.    fgets( temp, 80, fptr );
  9899.    printf( "String from file: \t%s\n", temp );
  9900.  
  9901.  The fgets function requires three arguments: a pointer to a string, the
  9902.  maximum number of characters to read, and the FILE pointer. The function
  9903.  stops reading characters when it encounters a newline character or when it
  9904.  reaches the maximum number of characters or the end of the file.
  9905.  
  9906.  If you prefer, you can input the characters one by one:
  9907.  
  9908.    while( (i = fgetc( fptr )) != '\n' )
  9909.       printf( "char: %c \t ASCII: %d \n", i, i );
  9910.  
  9911.  The printf inside the while loop prints each character as a character (%c)
  9912.  and also as a decimal value (%d). The while loop continues reading
  9913.  characters until it finds the end of the line.
  9914.  
  9915.  
  9916.  Back to the Beginning
  9917.  
  9918.  The rewind function resets the position pointer to the beginning of the
  9919.  file. In the program line below, the first line from the file is printed:
  9920.  
  9921.    rewind( fptr );
  9922.    printf( "Rewind to start -->\t%s", fgets( temp, 80, fptr ) );
  9923.  
  9924.  The screen output looks like this:
  9925.  
  9926.    Error number: 2
  9927.            Couldn't open file BADNAME
  9928.            : No such file or directory
  9929.    Values read from file:         0 53
  9930.    String from file:         Item 1: -23456
  9931.  
  9932.    char: I          ASCII: 73
  9933.    char: t          ASCII: 116
  9934.    char: e          ASCII: 101
  9935.    char: m          ASCII: 109
  9936.    char:            ASCII: 32
  9937.    char: 2          ASCII: 50
  9938.    char: :          ASCII: 58
  9939.    char:            ASCII: 32
  9940.    char:            ASCII: 32
  9941.    char:            ASCII: 32
  9942.    char:            ASCII: 32
  9943.    char:            ASCII: 32
  9944.    char: 5          ASCII: 53
  9945.    char: 0          ASCII: 48
  9946.    char:            ASCII: 32
  9947.    Rewind to start -->        Item 0:     53
  9948.  
  9949.   It is inefficient to store  numeric data in text format.
  9950.  
  9951.  There seem to be quite a few white-space characters in the text file. Text
  9952.  files are great for text, but they store numeric values in a wasteful way.
  9953.  Binary format offers several advantages.
  9954.  
  9955.  
  9956.  Using Binary Format
  9957.  
  9958.  When you're processing strings of ASCII characters and writing them to disk
  9959.  files, it matters little whether you use text mode or binary mode, as long
  9960.  as you're consistent. The advantage of text mode is that it translates
  9961.  newlines to the carriage-return-line-feed combination, making it possible to
  9962.  use the DOS TYPE command to view the file.
  9963.  
  9964.  When you're processing numeric values (integers and floating-point numbers),
  9965.  however, you may wish to save your variables in binary mode files, in binary
  9966.  format, for the following reasons:
  9967.  
  9968.  
  9969.    ■   Binary format almost always saves disk space. In text mode, the number
  9970.        12345.678 would require eight bytes for the ASCII numerals, one byte
  9971.        for the decimal point, and one or more bytes for a separator between
  9972.        variables. In binary format, a floating-point number uses four bytes,
  9973.        regardless of its value. Short integers use only two bytes.
  9974.  
  9975.    ■   Binary format generally saves computer time. When you use fprintf to
  9976.        print a numeric value to disk, the computer must translate the
  9977.        internal binary representation to a series of characters. Likewise,
  9978.        when fscanf reads characters into memory, the ASCII values must be
  9979.        translated to the internal binary format. In binary format, none of
  9980.        these translations takes place.
  9981.  
  9982.    ■   Binary format preserves the precision of floating-point numbers. The
  9983.        translation from binary to decimal ASCII and back to binary affects
  9984.        the precision of the value.
  9985.  
  9986.    ■   A binary save of arrays or structures is fast. It's not necessary to
  9987.        read through an array of 100 items and print each one to the disk
  9988.        file. Instead, you call the fwrite function (discussed below) once,
  9989.        passing it the size of the array to be saved.
  9990.  
  9991.        NOTE  Binary mode is separate from binary format. The modes (binary
  9992.        and text) are parameters you pass to the fopen function. They affect
  9993.        the translation of newlines and the placing of EOF markers. The
  9994.        formats (binary and text) are ways of representing numeric values. An
  9995.        integer in binary format always occupies two bytes on disk. An integer
  9996.        in text format uses a variable number of bytes: it might contain one
  9997.        character (5) or six (-10186).
  9998.  
  9999.  
  10000.  
  10001.  Opening a Binary File
  10002.  
  10003.  The SVBIN.C program below creates two binary mode files with the variables
  10004.  saved in binary format:
  10005.  
  10006.    /* SVBIN.C: Save integer variables in binary format. */
  10007.  
  10008.    #include <stdio.h>
  10009.    #define ASIZE 10
  10010.  
  10011.    main()
  10012.    {
  10013.       FILE *ap;
  10014.       int zebra[ASIZE], acopy[ASIZE], bcopy[ASIZE];
  10015.       int i;
  10016.  
  10017.       for( i = 0; i < ASIZE; i++ )
  10018.          zebra[i] = 7700 + i;
  10019.  
  10020.       if( (ap = fopen( "binfile", "wb" )) != NULL )
  10021.       {
  10022.          fwrite( zebra, sizeof(zebra), 1, ap );
  10023.          fclose( ap );
  10024.       }
  10025.       else
  10026.          perror( "Write error" );
  10027.  
  10028.       if( (ap = fopen( "morebin", "wb" )) != NULL )
  10029.       {
  10030.          fwrite( &zebra[0], sizeof(zebra[0]), ASIZE, ap );
  10031.          fclose( ap );
  10032.       }
  10033.       else
  10034.          perror( "Write error" );
  10035.  
  10036.       if( (ap = fopen( "binfile", "rb" )) != NULL )
  10037.       {
  10038.          printf( "Hexadecimal values in binfile:\n" );
  10039.          while( (i = fgetc( ap )) != EOF )
  10040.             printf( "%02X ", i );
  10041.          rewind( ap );
  10042.          fread( acopy, sizeof(acopy), 1, ap );
  10043.          rewind( ap );
  10044.          fread( &bcopy[0], sizeof( bcopy[0] ), ASIZE, ap);
  10045.          for( i=0; i<ASIZE; i++ )
  10046.             printf( "\nItem %d = %d\t%d", i, acopy[i], bcopy[i] );
  10047.          fclose( ap );
  10048.  
  10049.       }
  10050.       else
  10051.          perror( "Read error" );
  10052.  
  10053.    }
  10054.  
  10055.  Focus your attention on the  zebra  array. It contains 10 integers, because
  10056.  the array size  ASIZE  was defined as 10. First, some values are stored in
  10057.  zebra  (in a moment, we'll see why 7700-7709 are significant):
  10058.  
  10059.    for( i = 0; i < ASIZE; i++ )
  10060.       zebra[i] = 7700 + i;
  10061.  
  10062.  Next, we open a file and use fwrite to write the entire array to disk:
  10063.  
  10064.    if( (ap = fopen( "binfile", "wb" )) != NULL )
  10065.    {
  10066.       fwrite( zebra, sizeof(zebra), 1, ap );
  10067.       fclose( ap );
  10068.    }
  10069.  
  10070.  
  10071.  Writing an Array in One Line
  10072.  
  10073.  The fwrite function requires four pieces of information:
  10074.  
  10075.  
  10076.    1.  The address of the item (a variable, array, or structure)
  10077.  
  10078.    2.  The size of the item in bytes
  10079.  
  10080.    3.  The number of items to be written
  10081.  
  10082.    4.  The FILE pointer for a previously opened binary mode file
  10083.  
  10084.  
  10085.  In this example, the first argument,  zebra  is an array and, as you may
  10086.  remember from Chapter 8, "Pointers," the name of an array is the address of
  10087.  the array.
  10088.  
  10089.  To provide the second argument for fwrite, SVBIN.C uses the sizeof operator,
  10090.  which returns the number of bytes a variable requires. Because  zebra  is an
  10091.  array of 10 integers and integers use 2 bytes each, the size of  zebra
  10092.  should be 20. If you view a directory of your disk after running this
  10093.  program, you'll notice that the file BINFILE is exactly 20 bytes long.
  10094.  
  10095.  The third argument tells fwrite how many items to write to the file. We have
  10096.  1 array, so this parameter is 1.
  10097.  
  10098.  The fourth argument is the FILE pointer returned by fopen.
  10099.  
  10100.  There's another way to copy the 20 bytes of  zebra  to the file. After
  10101.  writing to BINFILE, the program uses the fopen function to create a second
  10102.  file called MOREBIN. The following fwrite line writes 10 integers instead of
  10103.  1 array:
  10104.  
  10105.    fwrite( &zebra[0], sizeof(zebra[0]), ASIZE, ap );
  10106.  
  10107.  The second and third arguments have changed. Instead of passing the size of
  10108.  the array (20) and writing 1 copy of the array, we're accessing the size of
  10109.  1 element (2 bytes) and writing 10 of them (using the symbolic constant
  10110.  ASIZE). The contents of this disk file should match, byte for byte, the
  10111.  contents of BINFILE.
  10112.  
  10113.  
  10114.  Examining the Binary Contents
  10115.  
  10116.  Finally, we look at what's inside the file BINFILE. It is opened for reading
  10117.  as a binary file:
  10118.  
  10119.    if( (ap = fopen( "binfile", "rb" )) != NULL )
  10120.  
  10121.  A short while loop reads the bytes from BINFILE and displays them in
  10122.  hexadecimal notation:
  10123.  
  10124.    printf( "Hexadecimal values in binfile:\n" );
  10125.    while( (i = fgetc( ap )) != EOF )
  10126.       printf( "%02X ", i );
  10127.  
  10128.  After running SVBIN.C, the screen displays these values:
  10129.  
  10130.    14 1E 15 1E 16 1E 17 1E 18 1E
  10131.    19 1E 1A 1E 1B 1E 1C 1E 1D 1E
  10132.  
  10133.  The low byte precedes the high byte, so the first two bytes represent the
  10134.  number 0x1E14, which is 7700 in decimal. The next two bytes equal 7701, and
  10135.  so on.
  10136.  
  10137.  A curious thing happens when you run SVBIN.C and then try to treat the
  10138.  20-byte file as text. If you TYPE BINFILE from the DOS command line, the
  10139.  file appears as gibberish (of course), and you see only 12 of the 20
  10140.  characters on the screen. Where did the other characters go? Recall the
  10141.  previous discussion of binary and text files. In DOS, a CTRL+Z (0x1A) marks
  10142.  the end of a text file. And in the midst of our binary file is one of those
  10143.  EOF characters. It's not acting as an EOF; it's part of the number 0x1E1A.
  10144.  But if you ever open this file in text mode, you'll be unable to read past
  10145.  the twelfth byte.
  10146.  
  10147.  
  10148.  Retrieving the Values from Disk
  10149.  
  10150.  Most of the time, you won't want to read a binary file one byte at a time.
  10151.  Instead, you call fread, which reads a disk file and stores the values in a
  10152.  variable, an array, or a structure. The fread function complements fwrite.
  10153.  It takes four parameters:
  10154.  
  10155.  
  10156.    1.  The address of the variable
  10157.  
  10158.    2.  The size of the variable in bytes
  10159.  
  10160.    3.  The number of values to read
  10161.  
  10162.    4.  The FILE pointer that references a binary file opened for reading
  10163.  
  10164.  
  10165.  Here's one way to read values into an array:
  10166.  
  10167.    rewind( ap );
  10168.    fread( acopy, sizeof( acopy ), 1, ap );
  10169.  
  10170.  The rewind command is necessary because we've already read through the file
  10171.  once. The  acopy  and  bcopy  arrays are the same size as our original
  10172.  zebra array. To fill an array with this technique, pass the address, the
  10173.  size of the entire array, a number 1, and the FILE pointer.
  10174.  
  10175.  A second way to fill an array is to pass the size of a single element and
  10176.  the number of elements you want to read:
  10177.  
  10178.    rewind( ap );
  10179.    fread( &bcopy[0], sizeof( bcopy[0] ), ASIZE, ap );
  10180.  
  10181.  In the first example of fread, we pass the information that the array  acopy
  10182.   is 20 bytes long and we want to read it once. In the second example, we
  10183.  pass the size of an integer (2 bytes) and ask for 10 of them. In either
  10184.  case, 20 bytes are transferred.
  10185.  
  10186.  Just to make sure both arrays are equal, we can print them out:
  10187.  
  10188.    for( i = 0; i < ASIZE; i++ )
  10189.    printf( "\nItem %d = %d\t%d", i, acopy[i], bcopy[i] );
  10190.    fclose( ap );
  10191.  
  10192.  The screen displays the values 7700 through 7709, which survived the trek
  10193.  from  zebra  to BINFILE and back again. These values were stored in the
  10194.  zebra  array, written to a binary file, then read back into the  acopy  and
  10195.  bcopy  arrays.
  10196.  
  10197.  
  10198.  Low-Level Input and Output
  10199.  
  10200.  The file-handling routines such as fopen, fprintf, and fclose are called
  10201.  "standard" because they're defined in the ANSI standard. Code that uses the
  10202.  standard routines will generally be portable from one machine to another.
  10203.  
  10204.  In addition to the standard file-handling functions, the QuickC library
  10205.  includes some low-level I/O functions, which allow more direct access to
  10206.  disk files.
  10207.  
  10208.  The low-level I/O routines (also called "system-level") are generally not
  10209.  portable. They work in DOS and OS/2, but they may not work elsewhere.
  10210.  They're also a little more difficult to use. Instead of declaring a pointer
  10211.  to a FILE structure, you must allocate your own buffer and manage transfer
  10212.  of the bytes yourself. You move values into the buffer, then send the
  10213.  contents of the buffer to disk.
  10214.  
  10215.   Low-level routines can be  more efficient, but they  usually aren't
  10216.  portable.
  10217.  
  10218.  Low-level routines have some advantages, though. One is that you have more
  10219.  control over the machine. Another is that low-level I/O can be faster than
  10220.  standard I/O, if you know what you're doing. The choice is up to you:
  10221.  portability versus efficiency. You should choose one or the other; it's not
  10222.  a good idea to mix standard and system-level routines.
  10223.  
  10224.  
  10225.  Low-Level Reading and Writing
  10226.  
  10227.  The program RWFILE.C illustrates some of the low-level, file-handling
  10228.  commands. It creates a file, writes to it, and closes it. Then the file is
  10229.  opened for reading and the contents of the file are displayed on the screen.
  10230.  
  10231.  
  10232.    /* RWFILE.C: Read and write a file. */
  10233.  
  10234.    #include <stdio.h>
  10235.    #include <string.h>
  10236.    #include <fcntl.h>
  10237.    #include <sys\types.h>
  10238.    #include <sys\stat.h>
  10239.    #include <io.h>
  10240.  
  10241.    #define BUFF 512
  10242.  
  10243.    main()
  10244.    {
  10245.       char inbuffer[BUFF];
  10246.       char outbuffer[BUFF];
  10247.       int infile, outfile, length, num;
  10248.  
  10249.       strcpy( outbuffer, "Happy Birthday." );
  10250.       length = strlen( outbuffer );
  10251.       length++;
  10252.  
  10253.       if( (outfile = open( "testfile.bin",
  10254.          O_CREAT | O_WRONLY | O_BINARY,  S_IWRITE )) != -1 )
  10255.       {
  10256.          if( (num = write( outfile, outbuffer, length )) == -1 )
  10257.             perror( "Error in writing" );
  10258.          printf( "\nBytes written to file: %d\n", num );
  10259.          close( outfile );
  10260.       }
  10261.       else
  10262.          perror( "Error opening outfile" );
  10263.  
  10264.    if( (infile = open( "testfile.bin", O_RDONLY | O_BINARY )) != -1  )
  10265.       {
  10266.          while( length = read( infile, inbuffer, BUFF ) )
  10267.             printf( "%d bytes received so far.\n", length );
  10268.          close( infile );
  10269.          printf( "%s\n", inbuffer );
  10270.       }
  10271.       else
  10272.          perror( "Error opening infile" );
  10273.    }
  10274.  
  10275.  Several header files must be included:
  10276.  
  10277.    #include <stdio.h>
  10278.    #include <fcntl.h>
  10279.    #include <sys\types.h>
  10280.    #include <sys\stat.h>
  10281.    #include <io.h>
  10282.  
  10283.  The symbolic constant  BUFF  is defined as 512. This value is used
  10284.  immediately in the declaration of two buffers:
  10285.  
  10286.    char inbuffer[BUFF];
  10287.    char outbuffer[BUFF];
  10288.  
  10289.  Note that we don't need FILE structures anywhere in the program. The
  10290.  standard I/O routines automatically allocated space for a buffer. Since
  10291.  we're operating closer to the DOS level, we must allocate our own buffers,
  10292.  instead of relying on the system. If you set the buffer size to a
  10293.  sufficiently large value, QuickC will run out of stack space. When this
  10294.  happens, you may either make the buffers global variables or use the malloc
  10295.  function to allocate an additional chunk of memory.
  10296.  
  10297.  The open function takes three parameters:
  10298.  
  10299.    if( (outfile = open( "testfile.bin",
  10300.       O_CREAT | O_WRONLY | O_BINARY, S_IWRITE )) != -1 )
  10301.  
  10302.  The first parameter is the file name. The second is a sequence of "oflags"
  10303.  that are combined with the OR operator. The oflags determine which type of
  10304.  file will be opened: it will be created ( O_CREAT ), it will be write-only (
  10305.  O_WRONLY ), and it will be a binary─not a text─file ( O_BINARY ). When you
  10306.  create a new file, you must include the third parameter:  S_IWRITE.
  10307.  
  10308.  The open function returns a file handle, which is assigned to the integer
  10309.  variable  outfile. Note that this is an integer, not a pointer to a FILE
  10310.  structure. If anything goes wrong, a value of -1 is returned by open, and we
  10311.  should test for this.
  10312.  
  10313.  Table 11.4 summarizes the differences between fopen and open.
  10314.  
  10315.  Table 11.4  Standard vs. Low-Level
  10316.  
  10317. ╓┌─────────┌──────────────────────────┌─────────────────┌────────────────────╖
  10318.  Function  Error Parameters           Returns           Condition
  10319.  ────────────────────────────────────────────────────────────────────────────
  10320.  fopen     File name,  type           Pointer to FILE   NULL
  10321.            (r, w, a), and mode
  10322.            (t, b)
  10323.  
  10324.  open      File name, oflags          File handle       -1
  10325.                                       (integer)
  10326.  
  10327.  ────────────────────────────────────────────────────────────────────────────
  10328.  
  10329.  
  10330.  
  10331.  
  10332.  Low-Level Writing
  10333.  
  10334.  The write function takes three parameters:
  10335.  
  10336.  
  10337.    1.  The file handle returned by open
  10338.  
  10339.    2.  The address of the buffer
  10340.  
  10341.    3.  The number of bytes to write
  10342.  
  10343.  
  10344.  You, the programmer, are responsible for filling up the buffer. The write
  10345.  function returns the number of bytes actually written to the file.
  10346.  
  10347.    if( (num = write( outfile, outbuffer, length )) == -1 )
  10348.       perror( "Error in writing" );
  10349.    printf( "\nBytes written to file: %d\n", num );
  10350.    close( outfile );
  10351.  
  10352.  
  10353.  Low-Level Reading
  10354.  
  10355.  Next, we open the file for reading. Again, the oflags are required:
  10356.  
  10357.    if( (infile = open( "testfile.bin", O_RDONLY | O_BINARY )) != -1 )
  10358.    {
  10359.       while( length = read( infile, inbuffer, BUFF ) )
  10360.          printf( "%d bytes received so far.\n", length );
  10361.       close( infile );
  10362.       printf( "%s\n", inbuffer );
  10363.    }
  10364.  
  10365.  The read function takes three parameters:
  10366.  
  10367.  
  10368.    1.  The file handle
  10369.  
  10370.    2.  The address of the buffer
  10371.  
  10372.    3.  The size of the buffer
  10373.  
  10374.  
  10375.  The value returned is the number of bytes read. The while loop continues as
  10376.  long as there are characters in the stream. In a real application, you'll
  10377.  have to handle the bytes stored in the buffer.
  10378.  
  10379.  The low-level file functions are unbuffered. When you call write, the bytes
  10380.  are written directly to the disk file. The standard file function fwrite
  10381.  doesn't write data to disk; it writes to a buffer. The buffer is transferred
  10382.  to disk when the buffer fills up, when the fflush function is called, or
  10383.  when the file is closed. As a gen-eral rule, you should not mix buffered and
  10384.  unbuffered routines. Use the standard routines or the low-level routines,
  10385.  but not both.
  10386.  
  10387.  This chapter started with keyboard input and screen output and led into
  10388.  discussions of file I/O. The following chapters cover in greater depth
  10389.  assembly language routines and some specialized types of screen output,
  10390.  including high-resolution graphics, fonts, and presentation graphics.
  10391.  
  10392.  
  10393.  
  10394.  
  10395.  
  10396.  
  10397.  Chapter 12  Dynamic Memory Allocation
  10398.  ────────────────────────────────────────────────────────────────────────────
  10399.  
  10400.  A program that allocates memory "dynamically" (as it runs) can respond
  10401.  flexibly to a user's needs, creating new data structures when the need
  10402.  arises and discarding them when their job is done.
  10403.  
  10404.  As you read this chapter you'll learn how to allocate memory with the malloc
  10405.  library function and free memory with the free function. We'll also look at
  10406.  two related functions, calloc and realloc.
  10407.  
  10408.  Memory allocation requires the use of pointers. If you're not familiar with
  10409.  pointers, read Chapter 8, "Pointers," before tackling this chapter.
  10410.  
  10411.  
  10412.  Why Allocate?
  10413.  
  10414.   The malloc family of library functions can allocate memory during run time.
  10415.  
  10416.  
  10417.  The malloc (memory allocate) family of library functions enables you to
  10418.  allocate blocks of memory dynamically. The capability to create new data
  10419.  structures on the fly lets you tailor a program's behavior precisely to the
  10420.  user's needs.
  10421.  
  10422.  For simple programs, such as the examples in Part 1, memory allocation is
  10423.  largely automatic. When you declare variables, as in the lines
  10424.  
  10425.    int count;
  10426.    char buffer[160];
  10427.  
  10428.  QuickC allocates enough memory to store each variable (2 bytes for the first
  10429.  variable and 160 for the second). This method works fine if you know each
  10430.  vari-able's size in advance. Some program memory needs aren't easy to
  10431.  predict, however.
  10432.  
  10433.  To take a simple example, say you write an address-book program that stores
  10434.  addresses in an array of structures. A novice programmer might begin by
  10435.  declaring an array of, say, 100 structures, in the following manner,
  10436.  
  10437.    struct address list[100];
  10438.  
  10439.  but this approach is needlessly limiting. If your list contains only a few
  10440.  addresses, most of the memory in the array is wasted. And if you want to
  10441.  enter more than 100 addresses, you're out of luck.
  10442.  
  10443.  A better approach is to allocate memory for the array dynamically. This way,
  10444.  the program can use only as much memory as needed for the current address
  10445.  list. Each time you add an address, or delete one, the program can expand or
  10446.  shrink the array as needed.
  10447.  
  10448.  
  10449.  Memory Allocation Basics
  10450.  
  10451.  We'll use a simple example program, COPYFILE.C, to demonstrate the basics of
  10452.  dynamic memory allocation─how to allocate a memory block, access its
  10453.  contents, and free the block when its purpose is served.
  10454.  
  10455.  The COPYFILE.C program, shown below, dynamically allocates a buffer that it
  10456.  uses to store file data.
  10457.  
  10458.    /* COPYFILE.C: Demonstrate malloc and free functions. */
  10459.  
  10460.    #include <stdio.h>     /* printf function and NULL */
  10461.    #include <io.h>        /* low-level I/O functions */
  10462.    #include <conio.h>     /* getch function */
  10463.    #include <sys\types.h> /* struct members used in stat.h */
  10464.    #include <sys\stat.h>  /* S_ constants */
  10465.    #include <fcntl.h>     /* O_ constants */
  10466.    #include <malloc.h>    /* malloc function */
  10467.    #include <errno.h>     /* errno global variable */
  10468.  
  10469.    int copyfile( char *source, char *destin );
  10470.  
  10471.    main( int argc, char *argv[] )
  10472.    {
  10473.       if( argc == 3 )
  10474.          if( copyfile( argv[1], argv[2] ) )
  10475.             printf( "Copy failed\n" );
  10476.          else
  10477.             printf( "Copy successful\n" );
  10478.       else
  10479.          printf( "  SYNTAX: COPYFILE <source> <target>\n" );
  10480.  
  10481.       return 0;
  10482.    }
  10483.  
  10484.    int copyfile( char *source, char *target )
  10485.    {
  10486.       char *buf;
  10487.       int hsource, htarget, ch;
  10488.       unsigned count = 50000;
  10489.  
  10490.       if( (hsource = open( source, O_BINARY | O_RDONLY )) == - 1 )
  10491.          return errno;
  10492.       htarget = open( target, O_BINARY | O_WRONLY | O_CREAT | O_EXCL,
  10493.                               S_IREAD | S_IWRITE );
  10494.       if( errno == EEXIST )
  10495.       {
  10496.          cputs( "Target exists. Overwrite? " );
  10497.          ch = getch();
  10498.          if( (ch == 'y') || (ch == 'Y') )
  10499.             htarget = open( target, O_BINARY | O_WRONLY | O_CREAT | O_TRUNC,
  10500.                                     S_IREAD | S_IWRITE );
  10501.          printf( "\n" );
  10502.       }
  10503.       if( htarget == -1 )
  10504.          return errno;
  10505.  
  10506.       if( filelength( hsource ) < count )
  10507.          count = (int)filelength( hsource );
  10508.  
  10509.       buf = (char *)malloc( (size_t)count );
  10510.  
  10511.       if( buf == NULL )
  10512.       {
  10513.          count = _memmax();
  10514.          buf = (char *)malloc( (size_t)count );
  10515.          if( buf == NULL )
  10516.             return ENOMEM;
  10517.       }
  10518.  
  10519.       while( !eof( hsource ) )
  10520.       {
  10521.          if( (count = read( hsource, buf, count )) == -1 )
  10522.             return errno;
  10523.          if( (count = write( htarget, buf, count )) == - 1 )
  10524.             return errno;
  10525.       }
  10526.  
  10527.       close( hsource );
  10528.       close( htarget );
  10529.       free( buf );
  10530.       return 0;
  10531.    }
  10532.  
  10533.  Before we look at how COPYFILE.C works, let's note what it does. Unlike the
  10534.  DOS COPY command, the COPYFILE.C program asks for confirmation before
  10535.  overwriting an existing file. The program expects to receive two file names
  10536.  as command-line parameters: the name of the file to copy and the name of the
  10537.  new file. For instance, the following command copies the file SAMPLE.EXE to
  10538.  the new file EXAMPLE.EXE:
  10539.  
  10540.    copyfile sample.exe example.exe
  10541.  
  10542.  If the target file already exists, COPYFILE.C displays:
  10543.  
  10544.    Target exists. Overwrite?
  10545.  
  10546.  COPYFILE.C overwrites an existing file only if the user presses the Y key in
  10547.  response.
  10548.  
  10549.  
  10550.  Preparing to Allocate Memory
  10551.  
  10552.  The COPYFILE.C program copies the source file in chunks, using an allocated
  10553.  memory block as a buffer for file data. The following program lines are the
  10554.  ones involved in allocating and freeing the memory block. (These are taken
  10555.  from the program in order, but are not consecutive.)
  10556.  
  10557.    #include <malloc.h>    /* malloc function */
  10558.    char *buf;
  10559.    unsigned count = 50000;
  10560.    buf = (char *)malloc( (size_t)count );
  10561.    free( buf );
  10562.  
  10563.  The first of these,
  10564.  
  10565.    #include <malloc.h>  /* malloc function */
  10566.  
  10567.  includes the standard include file MALLOC.H, which contains declarations for
  10568.  malloc and other memory-allocating functions.
  10569.  
  10570.  The malloc function, which the program will call to allocate a memory block,
  10571.  returns the address where the block begins. COPYFILE.C declares the pointer
  10572.  variable  buf  to store this address:
  10573.  
  10574.    char *buf;
  10575.  
  10576.  As you'll see shortly, the pointer  buf  will be initialized to point to the
  10577.  allocated block. Once this is done, the program can access the block's
  10578.  contents through the pointer.
  10579.  
  10580.  The COPYFILE.C program declares another variable,  count, which is used to
  10581.  tell malloc how much memory (in bytes) to allocate. The program initially
  10582.  sets this value to 50,000:
  10583.  
  10584.    unsigned count = 50000;
  10585.  
  10586.  If the source file is smaller than 50,000 bytes, COPYFILE.C later resets
  10587.  count  to the smaller value.
  10588.  
  10589.  
  10590.  Specifying the Size of the Allocated Block
  10591.  
  10592.  Now we're ready to allocate the block. The statement
  10593.  
  10594.    buf = (char *)malloc( (size_t)count) );
  10595.  
  10596.  in COPYFILE.C calls the malloc function, passing the value of  count  as an
  10597.  argument. This argument indicates the size of the desired block in bytes. In
  10598.  COPYFILE.C this value is 50,000 or the size of the source file, whichever is
  10599.  smaller.
  10600.  
  10601.  Look at the type cast preceding the function argument:
  10602.  
  10603.    (size_t)
  10604.  
  10605.  The cast is performed for ANSI compatibility (malloc is part of the ANSI
  10606.  standard). Under ANSI, malloc is declared as taking an argument of the type
  10607.  size_t. To ensure the portability of your programs, the value passed to
  10608.  malloc should be either declared or cast as type  size_t.
  10609.  
  10610.  
  10611.  A Graphic Illustration
  10612.  
  10613.  Figures 12.1 and 12.2 show how the COPYFILE.C program allocates a memory
  10614.  block. The figures are simplified and are not drawn to scale. They represent
  10615.  the program's "data segment," which is the memory area available for the
  10616.  program's data storage.
  10617.  
  10618.  ────────────────────────────────────────────────────────────────────────────
  10619.  NOTE
  10620.  
  10621.  The details of data storage differ depending on the current "memory model,"
  10622.  an advanced concept that goes beyond the scope of this book. For purposes of
  10623.  discussion, this book assumes the small memory model, which is the default
  10624.  for QuickC.
  10625.  ────────────────────────────────────────────────────────────────────────────
  10626.  
  10627.  Figure 12.1 represents the program's data segment before COPYFILE.C
  10628.  allocates a block of memory. The shaded area labeled "Declared data"
  10629.  contains the program's declared variables and "stack," which is used for
  10630.  temporary storage. The unshaded area labeled "Heap" contains the memory
  10631.  available for allocation by COPYFILE.C.
  10632.  
  10633.  (This figure may be found in the printed book.)
  10634.  
  10635.  Figure 12.2 shows COPYFILE.C immediately after the program calls the malloc
  10636.  function to allocate a block of memory. The allocated block is taken from
  10637.  heap memory and lies directly above the program. If COPYFILE.C allocated a
  10638.  second memory block, that block would lie above the first, further
  10639.  diminishing heap memory.
  10640.  
  10641.  (This figure may be found in the printed book.)
  10642.  
  10643.  While it's common to say the malloc function "creates" a memory block, that
  10644.  terminology is a bit misleading. As Figures 12.1 and 12.2 show, malloc
  10645.  simply gives your program control over memory that's already present.
  10646.  
  10647.   The malloc function does not initialize the  memory it allocates.
  10648.  
  10649.  Since the allocated block has been present in memory all along, it may
  10650.  contain random values or values left over from some previous use. The malloc
  10651.  function doesn't initialize allocated memory. Substitute the calloc function
  10652.  for malloc if you want to clear an allocated block before use. (See the
  10653.  section "The calloc Function" below.)
  10654.  
  10655.  
  10656.  Assigning the Address that malloc Returns
  10657.  
  10658.  If the call to malloc succeeds, malloc returns the address of the memory
  10659.  block it allocates. COPYFILE.C assigns that return value to the pointer
  10660.  variable  buf  and then accesses the allocated block through  buf.
  10661.  
  10662.  Before assigning the address that  malloc returns, COPYFILE.C performs a
  10663.  type cast on the address
  10664.  
  10665.    (char *)
  10666.  
  10667.  The type cast indicates which type of memory you are allocating. Prior to
  10668.  the ANSI standard, malloc was declared as returning a pointer to type char,
  10669.  so it was necessary to cast the return value when assigning the value to any
  10670.  other pointer type.
  10671.  
  10672.  Under ANSI, malloc returns a pointer to type void. Since a void pointer can
  10673.  be converted to any pointer type, it's not strictly necessary to cast the
  10674.  return from malloc. (If you omit the cast, QuickC does a silent type
  10675.  conversion.) The type cast improves readability, however.
  10676.  
  10677.  
  10678.  Checking the Return from malloc
  10679.  
  10680.  If a call to malloc fails─usually because not enough memory is available─the
  10681.  function returns a null pointer (defined as  NULL  in the standard include
  10682.  file STDIO.H). You should always test this return value, even if you're
  10683.  confident the allocation will succeed. If you ignore the return value and
  10684.  access memory through a null pointer, your program may stop with a run-time
  10685.  error or overwrite unpredictable memory addresses.
  10686.  
  10687.  Thus, before attempting to use the allocated memory block, COPYFILE.C checks
  10688.  to make sure the call to malloc succeeded:
  10689.  
  10690.    if( buf == NULL )
  10691.    {
  10692.    .
  10693.    .
  10694.    .
  10695.    }
  10696.  
  10697.  The if statement tests whether the pointer  buf  has been set to  NULL,
  10698.  which would signal failure. In that case, the program executes the code
  10699.  within the braces of the if statement.
  10700.  
  10701.  Sometimes there may be enough free memory to satisfy only part of your
  10702.  memory request. Look at how COPYFILE.C handles this situation:
  10703.  
  10704.    buf = (char *)malloc( (size_t)count );
  10705.  
  10706.    if( buf == NULL )
  10707.    {
  10708.       count = _memmax();
  10709.       buf = (char *)malloc( (size_t)count );
  10710.       if( buf == NULL )
  10711.          return ENOMEM;
  10712.    }
  10713.  
  10714.  If fewer than  count  bytes of memory are available, the initial call to
  10715.  malloc returns  NULL, indicating failure. In that event, COPYFILE.C calls
  10716.  the _memmax library routine to find how much memory is available and assigns
  10717.  that value to the variable  count:
  10718.  
  10719.    count = _memmax();
  10720.  
  10721.  Then COPYFILE.C calls malloc again, requesting a smaller amount of memory.
  10722.  This request is bound to succeed unless no memory is available.
  10723.  
  10724.  
  10725.  Accessing an Allocated Memory Block
  10726.  
  10727.  Once you have allocated a block of memory, you can access it through its
  10728.  pointer ( buf, in this example). COPYFILE.C uses its allocated block as a
  10729.  file buffer, alternately reading in data from the source file, through the
  10730.  statement
  10731.  
  10732.    if( (count = read( hsource, buf, count )) == -1 )
  10733.       return errno;
  10734.  
  10735.  and writing it to the target file, through the statement
  10736.  
  10737.    if( (count = write( htarget, buf, count )) == - 1 )
  10738.       return errno;
  10739.  
  10740.  The read and write function calls occur within if statements that compare
  10741.  the function return values to -1, which would indicate failure.
  10742.  
  10743.  COPYFILE.C treats its allocated block as a single chunk of memory. To access
  10744.  individual data items in an allocated block, you can use either pointer or
  10745.  array notation. Both of the following statements, for instance, refer to the
  10746.  third byte in the block that  buf  points to:
  10747.  
  10748.    buf[2] = 'x';
  10749.    *(buf+2) = 'x';
  10750.  
  10751.  
  10752.  Allocating Memory for Different Data Types
  10753.  
  10754.  Since COPYFILE.C accesses its allocated block through a char pointer, the
  10755.  program must treat the items in that block as char types. If you need to use
  10756.  a different type of memory, simply change the pointer declaration and cast
  10757.  the return from malloc accordingly. For instance, you could use the
  10758.  following statements to allocate a block large enough to store 30 int
  10759.  values:
  10760.  
  10761.    int *buf;
  10762.  
  10763.    buf = (int *)malloc( (size_t)sizeof( int ) * 30 );
  10764.  
  10765.  Here, the sizeof operator eliminates the need to calculate how many bytes of
  10766.  storage 30 integers require. The expression
  10767.  
  10768.    sizeof( int )
  10769.  
  10770.  returns the size of an int type, which we then multiply by the desired
  10771.  number of int items.
  10772.  
  10773.  If the above call to malloc succeeds, you have, in effect, a 30-element
  10774.  array of integers. And since pointer notation and array notation are
  10775.  interchangeable, you can access any element of the array using the pointer
  10776.  name and array notation. For instance, the expression
  10777.  
  10778.    ptr[2] = 50;
  10779.  
  10780.  assigns the value 50 to the third element of the array. Note that this
  10781.  statement accesses the third int element in the array, not the third byte.
  10782.  Pointer references, as explained in Chapter 8, "Pointers," are always scaled
  10783.  by the size of the type used to declare the pointer.
  10784.  
  10785.  Allocating memory for structures is equally straightforward. Say that you
  10786.  want to allocate memory to store 10 structures of the type  employee, which
  10787.  is declared in the EMPLOYEE.C program in Chapter 4, "Data Types." The
  10788.  EMPLOYEE.C program uses the following structure type:
  10789.  
  10790.    struct employee
  10791.    {
  10792.       char name[10];
  10793.       int months;
  10794.       float wage;
  10795.    };
  10796.  
  10797.  You could use the statement
  10798.  
  10799.    struct employee *e_ptr;
  10800.  
  10801.  to declare a pointer to an item of the  employee  type. Once you have a
  10802.  suitable pointer, you could use the following statement to allocate enough
  10803.  memory to store 10 structures of the same type:
  10804.  
  10805.    e_ptr = (struct employee *) malloc( (size_t)sizeof( struct employee ) * 10
  10806.    );
  10807.  
  10808.  Here, the sizeof operator
  10809.  
  10810.    sizeof( struct employee )
  10811.  
  10812.  returns the size of a structure of the  employee  type.
  10813.  
  10814.  If the allocation succeeds, you have, in effect, an array of structures of
  10815.  type employee. Using structure notation, you can access any structure member
  10816.  in the block. The following statements, for instance, initialize the members
  10817.  of the third structure in the array:
  10818.  
  10819.    strcpy( e_ptr[2].name, "Isaac, N." );
  10820.    e_ptr[2].months = 54;
  10821.    e_ptr[2].wage = (float) 12.21;
  10822.  
  10823.  
  10824.  Deallocating Memory with the free Function
  10825.  
  10826.   The free function deallocates an allocated memory block.
  10827.  
  10828.  When you have finished using an allocated memory block, you should free
  10829.  (deallocate) the block with the free library function. The free function
  10830.  takes one argument: the address of the block you wish to free. The
  10831.  COPYFILE.C program frees its allocated block with the statement:
  10832.  
  10833.    free( buf );
  10834.  
  10835.  It's your responsibility to pass a valid address to free. Unlike most
  10836.  library functions, free doesn't return any value to indicate success or
  10837.  failure. If you pass an invalid address, the memory block remains allocated
  10838.  and can't be used for any other purpose.
  10839.  
  10840.  Figure 12.3 shows COPYFILE.C after the program frees its allocated block.
  10841.  The free function releases the block from the program's control, returning
  10842.  it to the heap. The same memory is still present, of course. But since your
  10843.  program no longer has control of that memory, you shouldn't attempt to use
  10844.  it. (See "Using Dangling Pointers" in Chapter 10, "Programming Pitfalls,"
  10845.  for more information on this point.)
  10846.  
  10847.  (This figure may be found in the printed book.)
  10848.  
  10849.  
  10850.  Specialized Memory-Allocating Functions
  10851.  
  10852.  The C library contains two specialized versions of malloc that you may find
  10853.  useful. The calloc function allocates memory for an array and sets the
  10854.  block's contents to 0. The realloc function can expand or shrink an existing
  10855.  memory block.
  10856.  
  10857.  
  10858.  The calloc Function
  10859.  
  10860.  The calloc (calculated allocate) function is especially useful for
  10861.  allocating memory for an array. It works like malloc but takes two
  10862.  arguments:
  10863.  
  10864.  
  10865.    ■   The number of data items for which you wish to allocate memory
  10866.  
  10867.    ■   The size of each data item
  10868.  
  10869.  
  10870.  This scheme eliminates the need for you to calculate the number of bytes
  10871.  needed to store the desired array. For instance, the statement
  10872.  
  10873.    ptr = (int *) calloc( (size_t)30, (size_t)sizeof( int ) );
  10874.  
  10875.  allocates enough memory for a 30-element integer array, and
  10876.  
  10877.    e_ptr = (struct employee *) calloc( (size_t)30, sizeof( struct employee )
  10878.    );
  10879.  
  10880.  allocates enough memory for a 30-element array of structures of type
  10881.  employee.
  10882.  
  10883.   The calloc library function allocates memory and sets every byte in the
  10884.  block to 0.
  10885.  
  10886.  The calloc function also sets every byte in the requested block to 0. The
  10887.  malloc function, as we noted earlier, doesn't change the contents of an
  10888.  allocated block. If the block contained garbage values before allocation, it
  10889.  contains garbage after allocation, too.
  10890.  
  10891.  
  10892.  The realloc Function
  10893.  
  10894.  Sometimes you may need to adjust the size of an allocated memory block. The
  10895.  realloc (reallocate) function can expand or shrink an existing memory block.
  10896.  The function takes two arguments:
  10897.  
  10898.  
  10899.    ■   The address of an existing allocated block
  10900.  
  10901.    ■   The size (in bytes) you want to give the block
  10902.  
  10903.  
  10904.   The realloc library function expands or shrinks an  existing allocated
  10905.  block.
  10906.  
  10907.  If enough memory is available to accommodate the resized block, realloc
  10908.  allocates sufficient memory and copies as much of the existing block as the
  10909.  new block will hold. If the new block is smaller than the original, data is
  10910.  truncated.
  10911.  
  10912.  For instance, if you had allocated a 30-element int array with the statement
  10913.  
  10914.  
  10915.    ptr = (int *) calloc( (size_t)30, (size_t)sizeof( int ) );
  10916.  
  10917.  the following statement would expand the block to contain 20 extra elements,
  10918.  for a total of 50:
  10919.  
  10920.    ptr = (int *)realloc( ptr, (size_t)sizeof( int ) * 50 );
  10921.  
  10922.  The address you pass to realloc can be the address returned from a previous
  10923.  call to any memory-allocation function: malloc, calloc, or realloc itself.
  10924.  
  10925.  Like malloc, both calloc and realloc return a null address if they fail.
  10926.  Remember to check the return value whenever you call a memory-allocating
  10927.  function.
  10928.  
  10929.  
  10930.  Keeping Out of Trouble
  10931.  
  10932.  Here are a few rules to help you avoid trouble when allocating memory
  10933.  dynamically:
  10934.  
  10935.  
  10936.    ■   Always check the return value when allocating memory.
  10937.  
  10938.    ■   Be careful not to index past the boundaries of an allocated memory
  10939.        block.
  10940.  
  10941.    ■   Free allocated memory as soon as you have finished using it.
  10942.  
  10943.    ■   Make sure that the address you pass to the free function is valid.
  10944.  
  10945.    ■   Don't use a pointer to an allocated block after freeing the block.
  10946.  
  10947.  
  10948.  Most of these points were mentioned earlier, but the second deserves a
  10949.  little elaboration. As you may recall from earlier chapters, the C language
  10950.  doesn't check array subscripts or pointer references for validity. It's
  10951.  important to remember this rule when using a pointer to access an allocated
  10952.  block.
  10953.  
  10954.  For instance, suppose that you allocate a 30-element integer array with the
  10955.  statement
  10956.  
  10957.    ptr = (int *) malloc( (size_t)sizeof( int ) * 30 );
  10958.  
  10959.  and then execute either of these statements:
  10960.  
  10961.    ptr[32] = 80;
  10962.    *(ptr+32) = 80;
  10963.  
  10964.  Since the array has only 30 elements, both of the latter statements
  10965.  overwrite memory outside the allocated memory block. The statements store
  10966.  the value 80 in the address four bytes (two int elements) above the highest
  10967.  element in the array.
  10968.  
  10969.  While uncontrolled pointer operations always carry the potential for
  10970.  disaster, they can create especially tricky program bugs if you write just
  10971.  beyond an allocated memory block.
  10972.  
  10973.  Near the beginning of each allocated block is a tiny "link" containing
  10974.  information about the block. The memory-allocating functions use these links
  10975.  to keep track of allocated memory, and the more blocks you have allocated,
  10976.  the more important it is to keep all the links intact. If a bad pointer
  10977.  reference overwrites a link, it can cause problems in an entirely unexpected
  10978.  part of your program.
  10979.  
  10980.  
  10981.  
  10982.  
  10983.  
  10984.  
  10985.  Chapter 13  Graphics
  10986.  ────────────────────────────────────────────────────────────────────────────
  10987.  
  10988.  This chapter explains how to call graphics functions that set points, draw
  10989.  lines, change colors, and draw shapes such as rectangles and circles. The
  10990.  first section lists the three steps to using high-resolution graphics,
  10991.  defines important graphics terms, and works through an example program step
  10992.  by step, showing how to use the basic functions. The next sections explain
  10993.  coordinate systems and show how to display graphics inside viewports and
  10994.  windows.
  10995.  
  10996.  
  10997.  Graphics Mode
  10998.  
  10999.  There are three steps to displaying graphics in QuickC:
  11000.  
  11001.  
  11002.    1.  Use the _getvideoconfig function to determine which video adapter is
  11003.        installed. (See the section "Checking the Current Video Mode.")
  11004.  
  11005.    2.  Use the _setvideomode function to set the desired graphics mode for
  11006.        the installed video adapter. (See the section "Setting the Video
  11007.        Mode.")
  11008.  
  11009.    3.  Draw the graphics on the screen. (See the section "Writing a Graphics
  11010.        Program.")
  11011.  
  11012.  
  11013.  There are several definitions you need to know before you can create
  11014.  graphics programs. The following list explains the most useful terms:
  11015.  
  11016.  
  11017.    ■   The "x axis" determines the horizontal position on the screen. The
  11018.        "origin" (point 0, 0) is in the upper left corner. The maximum number
  11019.        of horizontal "pixels" (picture elements) varies from 320 to 640 to
  11020.        720, depending on the graphics card installed and the graphics mode in
  11021.        effect.
  11022.  
  11023.    ■   The "y axis" is the vertical position. The origin is the upper left
  11024.        corner. The number of vertical pixels ranges from 200 to 480.
  11025.  
  11026.    ■   Each graphics mode offers a "palette" from which you may choose the
  11027.        colors to be displayed. You may have access to 2, 4, 8, 16, or 256
  11028.        "color indexes," depending on the graphics card in the computer and
  11029.        the graphics mode in effect.
  11030.  
  11031.    ■   The CGA (Color Graphics Adapter) modes offer four fixed palettes
  11032.        containing predefined colors that may not be changed. In EGA (Enhanced
  11033.        Graphics Adapter), MCGA (Multicolor Graphics Array), and VGA (Video
  11034.        Graphics Array) graphics modes, you may change any of the color
  11035.        indexes by providing a color value that describes the mix of colors
  11036.        you wish to use.
  11037.  
  11038.    ■   A color index is always a short integer. A color value is always a
  11039.        long integer. When you're calling graphics functions that require
  11040.        color-related parameters, you should be aware of the difference
  11041.        between color indexes and color values.
  11042.  
  11043.  
  11044.  
  11045.  Checking the Current Video Mode
  11046.  
  11047.  Before or after entering graphics mode, you may inquire about the current
  11048.  video configuration. This requires a special structure type called
  11049.  videoconfig, which is defined in the GRAPH.H header file. You pass the
  11050.  address of the structure to the function _getvideoconfig, which returns the
  11051.  current video configuration information.
  11052.  
  11053.  All graphics programs should include the graphics header file and declare a
  11054.  structure of type videoconfig. The structure contains the following
  11055.  elements:
  11056.  
  11057.    short numxpixels;   /*number of pixels on x axis*/
  11058.    short numypixels;   /*number of pixels on y axis*/
  11059.    short numtextcols;  /*number of text columns available*/
  11060.    short numtextrows;  /*number of text rows available*/
  11061.    short numcolors;    /*number of color indexes*/
  11062.    short bitsperpixel; /*number of bits per pixel*/
  11063.    short numvideopages;/*number of available video pages*/
  11064.    short mode;         /*current video mode*/
  11065.    short adapter;      /*active display adapter*/
  11066.    short monitor;      /*active display monitor*/
  11067.    short memory;       /*adapter video memory in K bytes*/
  11068.  
  11069.  These variables within the videoconfig structure are initialized when you
  11070.  call _getvideoconfig.
  11071.  
  11072.  
  11073.  Setting the Video Mode
  11074.  
  11075.  Before you can start drawing pictures on the screen, your program must tell
  11076.  the graphics adapter to switch from video text mode to graphics mode. To do
  11077.  this, call _setvideomode, passing it a single integer that tells it which
  11078.  mode to display. The following constants are defined in the GRAPH.H file.
  11079.  The dimensions are listed in pixels for graphics mode and in columns for
  11080.  video text modes.
  11081.  
  11082. ╓┌───────────────┌─────────────────────────────┌─────────────────────────────╖
  11083.  Constant        Video Mode                    Mode Type/Hardware
  11084.  ────────────────────────────────────────────────────────────────────────────
  11085.  _DEFAULTMODE    Restores to original mode     Both/All
  11086.  
  11087.  _ERESCOLOR      640 x  350, 4 or 16 color     Graphics/EGA
  11088.  
  11089.  _ERESNOCOLOR    640 x  350, BW                Graphics/EGA
  11090.  Constant        Video Mode                    Mode Type/Hardware
  11091.  ────────────────────────────────────────────────────────────────────────────
  11092. _ERESNOCOLOR    640 x  350, BW                Graphics/EGA
  11093.  
  11094.  _HERCMONO       720 x 348, BW for HGC         Graphics/HGC
  11095.  
  11096.  _HRES16COLOR    640 x  200, 16 color          Graphics/EGA
  11097.  
  11098.  _HRESBW         640 x  200, BW                Graphics/CGA
  11099.  
  11100.  _MRES4COLOR     320 x  200, 4 color           Graphics/CGA
  11101.  
  11102.  _MRES16COLOR    320 x  200, 16 color          Graphics/EGA
  11103.  
  11104.  _MRES256COLOR   320 x  200, 256 color         Graphics/VGA/
  11105.                                                MCGA
  11106.  
  11107.  _MRESNOCOLOR    320 x  200, 4 gray            Graphics/CGA
  11108.  
  11109.  _ORESCOLOR      640 x  400, 1 of 16 colors    Graphics/
  11110.                                                Olivetti(R)
  11111.  Constant        Video Mode                    Mode Type/Hardware
  11112.  ────────────────────────────────────────────────────────────────────────────
  11113.                                               Olivetti(R)
  11114.  
  11115.  _TEXTBW40       40-column text, 16 gray       Text/CGA
  11116.  
  11117.  _TEXTBW80       80-column text, 16 gray       Text/CGA
  11118.  
  11119.  _TEXTC40        40-column text, 16/8 color    Text/CGA
  11120.  
  11121.  _TEXTC80        80-column text, 16/8 color    Text/CGA
  11122.  
  11123.  _TEXTMONO       80-column text, BW            Text/MDA
  11124.  
  11125.  _VRES2COLOR     640 x  480, BW                Graphics/VGA/
  11126.                                                MCGA
  11127.  
  11128.  _VRES16COLOR    640 x  480, 16 color          Graphics/VGA
  11129.  
  11130.  ────────────────────────────────────────────────────────────────────────────
  11131.  
  11132.  Constant        Video Mode                    Mode Type/Hardware
  11133.  ────────────────────────────────────────────────────────────────────────────
  11134. 
  11135.  
  11136.  
  11137.  If _setvideomode returns a 0, it means the hardware does not support the
  11138.  selected mode. You may continue to select alternate video modes until a
  11139.  nonzero value is returned. If the hardware configuration doesn't support any
  11140.  of the selected video modes, take the appropriate exit action.
  11141.  
  11142.  
  11143.  Writing a Graphics Program
  11144.  
  11145.  The SINE.C program below graphs a sine curve. The program illustrates how to
  11146.  call many of the important graphics functions. The main function calls five
  11147.  other functions, which are defined later in this chapter. To view the
  11148.  complete program, use online help.
  11149.  
  11150.  ────────────────────────────────────────────────────────────────────────────
  11151.  WARNING
  11152.  
  11153.  When you installed QuickC on your system, you may have chosen not to include
  11154.  the graphics library. If this is the case, the programs in this chapter
  11155.  won't compile unless you explicitly link the graphics library. See the
  11156.  Microsoft QuickC Tool Kit for information about linking libraries.
  11157.  ────────────────────────────────────────────────────────────────────────────
  11158.  
  11159.  
  11160.    /* SINE.C: Basic graphics commands. */
  11161.  
  11162.    #include <stdio.h>
  11163.    #include <stdlib.h>
  11164.    #include <graph.h>
  11165.    #include <math.h>
  11166.    #include <conio.h>
  11167.    #define PI 3.14159
  11168.  
  11169.    void graphics_mode( void );
  11170.    void draw_lines( void );
  11171.    void sine_wave( void );
  11172.    void draw_shapes( void );
  11173.    void end_program( void );
  11174.    int newx( int );
  11175.    int newy( int );
  11176.  
  11177.    struct videoconfig myscreen;
  11178.    int maxx, maxy;
  11179.    unsigned char diagmask[8] =
  11180.    { 0x93, 0xC9, 0x64, 0xB2, 0x59, 0x2C, 0x96, 0x4B };
  11181.    unsigned char linemask[8] =
  11182.    { 0xFF, 0x00, 0x7F, 0xFE, 0x00, 0x00, 0x00, 0xCC };
  11183.  
  11184.  
  11185.    main()
  11186.    {
  11187.       graphics_mode();
  11188.       draw_lines();
  11189.       sine_wave();
  11190.       draw_shapes();
  11191.       end_program();
  11192.    }
  11193.    /*
  11194.    Definitions of functions go here
  11195.    */
  11196.  
  11197.  The SINE.C program's output is shown in Figure 13.1.
  11198.  
  11199.  (This figure may be found in the printed book.)
  11200.  
  11201.  
  11202.  Turning on Graphics Mode
  11203.  
  11204.  Before you can display graphics, you must put the graphics adapter into a
  11205.  graphics mode. The _setvideomode function performs this task. Before calling
  11206.  _setvideomode, you must decide which graphics modes are acceptable for your
  11207.  purposes. The first function in SINE.C is named  graphics_mode. It selects
  11208.  the highest possible resolution available, based on the graphics card
  11209.  currently in use.
  11210.  
  11211.  Four header files are included in the SINE.C program:
  11212.  
  11213.    #include <stdio.h>
  11214.  
  11215.    #include <stdlib.h>
  11216.  
  11217.    #include <graph.h>
  11218.  
  11219.    #include <math.h>
  11220.  
  11221.  Although the MATH.H file is not required for graphics programs, we include
  11222.  it in the SINE.C program because it contains floating-point math functions
  11223.  such as sin.
  11224.  
  11225.  Later in the program we'll need to get information about the screen size, so
  11226.  the videoconfig structure called  myscreen  is declared:
  11227.  
  11228.    struct videoconfig myscreen;
  11229.  
  11230.  The functions called by main aren't in the standard library; they're defined
  11231.  within SINE.C.
  11232.  
  11233.  The first function is  graphics_mode, which turns on graphics capabilities:
  11234.  
  11235.  
  11236.    void graphics_mode( void )
  11237.    {
  11238.       _getvideoconfig( &myscreen );
  11239.       switch( myscreen.adapter )
  11240.       {
  11241.          case _CGA:
  11242.             _setvideomode( _HRESBW );
  11243.             break;
  11244.          case _OCGA:
  11245.             _setvideomode( _ORESCOLOR );
  11246.             break;
  11247.          case _EGA:
  11248.          case _OEGA:
  11249.             if( myscreen.monitor == _MONO )
  11250.                _setvideomode( _ERESNOCOLOR );
  11251.             else
  11252.                _setvideomode( _ERESCOLOR );
  11253.             break;
  11254.          case _VGA:
  11255.          case _OVGA:
  11256.          case _MCGA:
  11257.             _setvideomode( _VRES2COLOR );
  11258.             break;
  11259.          case _HGC:
  11260.             _setvideomode( _HERCMONO );
  11261.             break;
  11262.          default:
  11263.             printf( "This program requires a CGA, EGA, VGA, or Hercules
  11264.  card\n" );
  11265.             exit( 0 );
  11266.       }
  11267.       _getvideoconfig( &myscreen );
  11268.       maxx = myscreen.numxpixels - 1;
  11269.       maxy = myscreen.numypixels - 1;
  11270.    }
  11271.  
  11272.  ────────────────────────────────────────────────────────────────────────────
  11273.  NOTE
  11274.  
  11275.  If you use a Hercules(R) adapter, you must run the MSHERC.COM program before
  11276.  attempting to display any graphics. Always run MSHERC.COM before running
  11277.  QuickC (do not run it from QuickC's DOS shell).
  11278.  ────────────────────────────────────────────────────────────────────────────
  11279.  
  11280.  The function begins by calling _getvideoconfig, passing the address of the
  11281.  videoconfig structure. Within the structure a member called adapter tells us
  11282.  the type of adapter currently in use. With that knowledge, and a switch
  11283.  statement, we can enter the appropriate graphics mode.
  11284.  
  11285.  But how much screen do we have to work with? The screen might be 720 x 348,
  11286.  640 x 480, 640 x 400, 640 x 350, or 640 x 200. Whenever you call
  11287.  _setvideomode, you can ask for information about the currently displayed
  11288.  screen with _getvideoconfig. Just pass it the address of the videoconfig
  11289.  structure that was declared earlier:
  11290.  
  11291.    _getvideoconfig( &myscreen );
  11292.    maxx = myscreen.numxpixels - 1;
  11293.    maxy = myscreen.numypixels - 1;
  11294.  
  11295.  Let's say your computer has an EGA card, which means that at this point,
  11296.  _ERESNOCOLOR is in effect. The horizontal screen size is 640 pixels and
  11297.  vertical screen size is 350. The two assignments above assign these values
  11298.  to  maxx  and  maxy, less 1. The horizontal resolution might be 640, but the
  11299.  pixels are numbered 0-639. Thus, the  maxx  variable─the highest available
  11300.  pixel number─must be 1 less than the total number of pixels:
  11301.  
  11302.    myscreen.numxpixels - 1
  11303.  
  11304.  Two short functions perform conversions from an imaginary 1000 x 1000 screen
  11305.  to whatever graphics mode is in effect. From this point forward, the program
  11306.  will assume it has 1000 pixels in each direction, passing the values to
  11307.  newx  and  newy  for conversion to actual coordinates:
  11308.  
  11309.    int newx( int xcoord )
  11310.    {
  11311.       int nx;
  11312.       float tempx;
  11313.       tempx = ((float)maxx)/ 1000.0;
  11314.       tempx = ((float)xcoord) * tempx + 0.5;
  11315.       return( (int)tempx );
  11316.    }
  11317.  
  11318.    int newy( int ycoord )
  11319.    {
  11320.       int ny;
  11321.       float tempy;
  11322.       tempy = ((float)maxy)/ 1000.0;
  11323.       tempy = ((float)ycoord) * tempy + 0.5;
  11324.       return( (int)tempy );
  11325.    }
  11326.  
  11327.  
  11328.  Drawing Rectangles and Lines
  11329.  
  11330.  The next function called in SINE.C is  draw_lines. As the name implies, the
  11331.  draw_lines  function draws several lines on the screen: a rectangle around
  11332.  the outer edges of the screen and three horizontal lines that cut the screen
  11333.  into quarters.
  11334.  
  11335.    void draw_lines( void )
  11336.    {
  11337.       _rectangle( _GBORDER, 0, 0, maxx, maxy );
  11338.       /* _setcliprgn( 20, 20, maxx - 20, maxy - 20 ); */
  11339.       _setvieworg( 0, newy( 500 ) );
  11340.  
  11341.       _moveto( 0, 0 );
  11342.       _lineto( newx( 1000 ), 0 );
  11343.       _setlinestyle( 0xAA3C );
  11344.       _moveto( 0, newy( -250) );
  11345.       _lineto( newx( 1000 ), newy( -250 ) );
  11346.       _setlinestyle( 0x8888 );
  11347.       _moveto( 0, newy( 250 ) );
  11348.       _lineto( newx( 1000 ), newy( 250 ) );
  11349.    }
  11350.  
  11351.  The call to the _rectangle function has five arguments. The first argument
  11352.  is the fill flag, which may be either _GBORDER or _GFILLINTERIOR. Choose
  11353.  _GBORDER if you want a rectangle of four lines (a border only, in the
  11354.  current line style). Or you can choose _GFILLINTERIOR if you want a solid
  11355.  rectangle (filled in with the current color and fill pattern). We will
  11356.  discuss how to choose the color and fill pattern later in this chapter.
  11357.  
  11358.  The second and third arguments are the x and y coordinates of one corner of
  11359.  the rectangle. The fourth and fifth arguments are the coordinates of the
  11360.  opposite corner. Since the coordinates for the two corners are  ( 0, 0 ) and
  11361.  ( maxx, maxy ) , the call to _rectangle frames the screen.
  11362.  
  11363.    _rectangle( _GBORDER, 0, 0, maxx, maxy );
  11364.  
  11365.  Drawing lines is a two-step process. Move to one location on the screen and
  11366.  draw the line to another location, using the _moveto and _lineto functions:
  11367.  
  11368.  
  11369.    _setlinestyle( 0xAA3C );
  11370.    _moveto( 0, newy(-250) );
  11371.    _lineto( newx(1000), newy(-250) );
  11372.  
  11373.  Use the _setlinestyle function to change from a solid line to a dashed line
  11374.  by passing it one integer value. In the example above, the number 0xAA3C
  11375.  causes the line to become the graphics equivalent of binary 1010 1010 0011
  11376.  1100.
  11377.  
  11378.  The _moveto function positions an imaginary pixel cursor at a spot on the
  11379.  screen. Nothing visible appears on the screen. The _lineto function draws a
  11380.  line. The negative value -250 might seem to be an impossible screen
  11381.  coordinate. It would be, but the program has changed the viewport
  11382.  organization of the screen with the _setvieworg function. The top half of
  11383.  the screen now contains negative y coordinates, and the bottom half contains
  11384.  positive y coordinates. Viewports are explained in more detail later in this
  11385.  chapter.
  11386.  
  11387.  
  11388.  Setting a Pixel
  11389.  
  11390.  The next step in the SINE.C program is to draw the sine curve. This requires
  11391.  the  sine_wave  function which is shown below. This function calculates
  11392.  positions for two sine waves and plots them on the screen:
  11393.  
  11394.    void sine_wave( void )
  11395.    {
  11396.     int locx, locy;
  11397.      double i, rad;
  11398.  
  11399.     for( i = 0; i < 1000; i += 3 )
  11400.       {
  11401.          rad = -sin( (PI * (float) i) / 250.0 );
  11402.          locx = newx( (int) i );
  11403.          locy = newy( (int) (rad * 250.0) );
  11404.          _setpixel( locx, locy );
  11405.       }
  11406.    }
  11407.  
  11408.  The only graphics function called is _setpixel, which takes two parameters,
  11409.  an x and a y coordinate. The function turns on the pixel at that location.
  11410.  
  11411.  
  11412.  Drawing Shapes
  11413.  
  11414.  After the sine curve is drawn, the SINE.C program calls the  draw_shapes
  11415.  function to draw two rectangles and two ellipses on the screen. The fill
  11416.  mask alternates between _GBORDER and _GFILLINTERIOR:
  11417.  
  11418.    void draw_shapes( void )
  11419.    {
  11420.       _setlinestyle( 0xFFFF );
  11421.       _setfillmask( diagmask );
  11422.       _rectangle( _GBORDER, newx( 50 ), newy( -325 ), newx( 200 ), newy( -425
  11423.  ) );
  11424.       _rectangle(_GFILLINTERIOR,newx(550),newy(-325),newx(700),newy(-425));
  11425.  
  11426.       _setfillmask( linemask );
  11427.       _ellipse( _GBORDER, newx( 50 ), newy( 325 ), newx( 200 ), newy( 425 )
  11428.  );
  11429.       _ellipse( _GFILLINTERIOR,newx( 550 ),newy( 325 ),newx( 700 ),newy( 425
  11430.  ) );
  11431.    }
  11432.  
  11433.  Note that _setlinestyle resets the line pattern to solid. If you omit this
  11434.  function (or comment it out), the first rectangle would be drawn with dashes
  11435.  instead of a solid line.
  11436.  
  11437.  The _ellipse function draws an ellipse on the screen. Its parameters
  11438.  resemble the parameters for _rectangle. Both functions require a fill flag
  11439.  and two corners of a "bounding rectangle." When the ellipse is drawn, four
  11440.  points touch the edges of the bounding rectangle.
  11441.  
  11442.  The _GFILLINTERIOR flag fills the shape with the current fill pattern. To
  11443.  select a pattern, you must first use the _setfillmask function, passing the
  11444.  address of an eight-byte array of unsigned characters. Earlier in the
  11445.  program  diagmask  was defined as the shape shown in Table 13.1 below.
  11446.  
  11447.  Table 13.1  Fill Patterns
  11448.  
  11449. ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
  11450.  Bit Pattern                       Value in diagmask
  11451.  ────────────────────────────────────────────────────────────────────────────
  11452.    ∙  ∙    ∙  ∙                diagmask[0] = 0x93
  11453.      ∙  ∙    ∙  ∙              diagmask[1] = 0xC9
  11454.  ∙      ∙  ∙    ∙  ∙            diagmask[2] = 0x64
  11455.    ∙      ∙  ∙    ∙            diagmask[3] = 0xB2
  11456.  ∙    ∙      ∙  ∙              diagmask[4] = 0x59
  11457.  ∙  ∙    ∙      ∙  ∙            diagmask[5] = 0x2C
  11458.    ∙  ∙    ∙      ∙            diagmask[6] = 0x96
  11459.  ∙    ∙  ∙    ∙                diagmask[7] = 0x4B
  11460.  ────────────────────────────────────────────────────────────────────────────
  11461.  
  11462.  
  11463.  
  11464.  Exiting Graphics Mode
  11465.  
  11466.  The final function to be called by the SINE.C program is  end_program, which
  11467.  waits for a key press and then sets the screen back to normal:
  11468.  
  11469.    void end_program( void )
  11470.    {
  11471.       getch();
  11472.       _setvideomode( _DEFAULTMODE );
  11473.    }
  11474.  
  11475.  
  11476.  Using Color Graphics Modes
  11477.  
  11478.  In this example, the program COLOR.C sets a mode with as many color choices
  11479.  as possible for the available hardware:
  11480.  
  11481.    /* COLOR.C: Sets a medium resolution mode
  11482.       with maximum color choices. */
  11483.  
  11484.    #include <stdio.h>
  11485.    #include <stdlib.h>
  11486.    #include <graph.h>
  11487.    #include <conio.h>
  11488.    struct videoconfig vc;
  11489.  
  11490.    main()
  11491.    {
  11492.       if( _setvideomode( _MRES256COLOR ) );
  11493.       else if( _setvideomode( _MRES16COLOR ) );
  11494.       else if( _setvideomode( _MRES4COLOR ) );
  11495.       else
  11496.       {
  11497.          printf( "Error: No color graphics capability\n" );
  11498.          exit( 0 );
  11499.       }
  11500.  
  11501.       _getvideoconfig( &vc );
  11502.  
  11503.       printf( "%d available colors\n", vc.numcolors );
  11504.       printf( "%d horizontal pixels\n", vc.numxpixels );
  11505.       printf( "%d vertical pixels\n", vc.numypixels );
  11506.  
  11507.       getch();
  11508.       _clearscreen( _GCLEARSCREEN );
  11509.       _setvideomode( _DEFAULTMODE );
  11510.    }
  11511.  
  11512.  Although color graphics are an improvement over black and white, if you use
  11513.  color you must make a compromise. When you request the maximum number of
  11514.  colors, you sacrifice some resolution─a 320 x 200 screen instead of a higher
  11515.  resolution. Thus, the COLORS.C program always creates a screen 320 pixels
  11516.  wide and 200 pixels high. Note also the use of the function _clearscreen,
  11517.  which clears the screen in any video mode (text or graphics).
  11518.  
  11519.  To view every possible graphics mode, you can run the program GRAPHIC.C
  11520.  shown below. Explanations of the various color graphics modes─CGA, EGA, and
  11521.  VGA─follow.
  11522.  
  11523.    /* GRAPHIC.C: Display every graphics mode. */
  11524.    #include <stdio.h>
  11525.    #include <graph.h>
  11526.    #include <conio.h>
  11527.  
  11528.    struct videoconfig screen;
  11529.    int modes[12] =
  11530.    {
  11531.       _MRES4COLOR, _MRESNOCOLOR, _HRESBW, _HERCMONO,
  11532.       _MRES16COLOR, _HRES16COLOR, _ERESNOCOLOR, _ERESCOLOR,
  11533.       _VRES2COLOR, _VRES16COLOR, _MRES256COLOR, _ORESCOLOR
  11534.    };
  11535.  
  11536.    void print_menu( void );
  11537.    void show_mode( char );
  11538.  
  11539.    main()
  11540.    {
  11541.       char key;
  11542.       print_menu();
  11543.       while( (key = getch()) != 'x' )
  11544.          show_mode( key );
  11545.    }
  11546.  
  11547.    void print_menu( void )
  11548.    {
  11549.       _setvideomode( _DEFAULTMODE );
  11550.       _clearscreen( _GCLEARSCREEN );
  11551.       printf( "Please choose a graphics mode\nType 'x' to exit.\n\n" );
  11552.       printf( "0 _MRES4COLOR\n1 _MRESNOCOLOR\n2 _HRESBW\n" );
  11553.       printf( "3 _HERCMONO\n4 _MRES16COLOR\n5 _HRES16COLOR\n" );
  11554.       printf( "6 _ERESNOCOLOR\n7 _ERESCOLOR\n" );
  11555.       printf( "8 _VRES2COLOR\n9 _VRES16COLOR\na _MRES256COLOR\n" );
  11556.       printf( "b _ORESCOLOR\n" );
  11557.    }
  11558.  
  11559.    void show_mode( char which )
  11560.    {
  11561.       int nc, i;
  11562.       int height, width;
  11563.       int mode = which;
  11564.  
  11565.       if( mode < '0' || mode > '9' )
  11566.          if( mode == 'a' )
  11567.        mode = '9' + 1;
  11568.          else if( mode == 'b' )
  11569.        mode = '9' + 2;
  11570.  
  11571.    else
  11572.        return;
  11573.  
  11574.       if( _setvideomode( modes[mode - '0'] ) )
  11575.       {
  11576.          _getvideoconfig( &screen );
  11577.          nc = screen.numcolors;
  11578.          width = screen.numxpixels/nc;
  11579.          height = screen.numypixels/2;
  11580.          for( i = 0; i < nc; i++ )
  11581.          {
  11582.        _setcolor( i );
  11583.        _rectangle( _GFILLINTERIOR, i * width, 0, (i + 1) * width, height );
  11584.          }
  11585.       }
  11586.       else
  11587.       {
  11588.          printf( " \nVideo mode %c is not available.\n", which );
  11589.          printf( "Please press a key.\n" );
  11590.       }
  11591.       getch();
  11592.       _setvideomode( _DEFAULTMODE );
  11593.       print_menu();
  11594.    }
  11595.  
  11596.  
  11597.  CGA Color Graphics Modes
  11598.  
  11599.  The CGA color graphics modes _MRES4COLOR and _MRESNOCOLOR display four
  11600.  colors selected from one of several predefined palettes of colors. They
  11601.  display these foreground colors against a background color which can be any
  11602.  one of the 16 available colors. With the CGA hardware, the palette of
  11603.  foreground colors is predefined and cannot be changed. Each palette number
  11604.  is an integer as shown in Table 13.2.
  11605.  
  11606.  Table 13.2  Available CGA Colors
  11607.  
  11608. ╓┌─────────────────┌─────────────┌───────────────┌───────────────────────────╖
  11609.  Palette Number    Color Index
  11610.                    1             2               3
  11611.  ────────────────────────────────────────────────────────────────────────────
  11612.  0                 Green         Red             Brown
  11613.  1                 Cyan          Magenta         Light gray
  11614.  2                 Light green   Light red       Yellow
  11615.  Palette Number    Color Index
  11616.                    1             2               3
  11617.  ────────────────────────────────────────────────────────────────────────────
  11618. 2                 Light green   Light red       Yellow
  11619.  3                 Light cyan    Light magenta   White
  11620.  ────────────────────────────────────────────────────────────────────────────
  11621.  
  11622.  
  11623.  The _MRESNOCOLOR graphics mode produces palettes containing various shades
  11624.  of gray on black-and-white monitors. The _MRESNOCOLOR mode displays colors
  11625.  when used with a color display. However, only two palettes
  11626.  
  11627.  are available with a color display. You can use the _selectpalette function
  11628.  to select one of these predefined palettes. Table 13.3 shows the
  11629.  correspondence between the color indexes and the palettes.
  11630.  
  11631.  Table 13.3  CGA Colors:  _MRESNOCOLOR Mode
  11632.  
  11633. ╓┌─────────────────┌────────────┌───────────┌────────────────────────────────╖
  11634.  Palette Number    Color Index
  11635.                    1            2           3
  11636.  Palette Number    Color Index
  11637.                    1            2           3
  11638.  ────────────────────────────────────────────────────────────────────────────
  11639.  0                 Blue         Red         Light gray
  11640.  1                 Light blue   Light red   White
  11641.  ────────────────────────────────────────────────────────────────────────────
  11642.  
  11643.  
  11644.  You may use the _selectpalette function only with the _MRES4COLOR and
  11645.  _MRESNOCOLOR graphics modes. To change palettes in other graphics modes, use
  11646.  the _remappalette or _remapallpalette functions.
  11647.  
  11648.  The following program sets the video mode to _MRES4COLOR and then cycles
  11649.  through background colors and palette combinations. It works on computers
  11650.  equipped with CGA, EGA, MCGA, or VGA cards. A color monitor is required.
  11651.  
  11652.    /* CGA.C: Demonstrate CGA colors. */
  11653.  
  11654.    #include <stdio.h>
  11655.    #include <graph.h>
  11656.    #include <conio.h>
  11657.  
  11658.    long bkcolor[8] =
  11659.    {
  11660.       _BLACK, _BLUE, _GREEN, _CYAN,
  11661.      _RED, _MAGENTA, _BROWN, _WHITE
  11662.    };
  11663.  
  11664.    char *bkcolor_name[] =
  11665.    {
  11666.       "_BLACK", "_BLUE", "_GREEN", "_CYAN",
  11667.       "_RED", "_MAGENTA", "_BROWN", "_WHITE"
  11668.    };
  11669.  
  11670.    main()
  11671.    {
  11672.       int i, j, k;
  11673.       _setvideomode( _MRES4COLOR );
  11674.       for( i=0; i<= 3; i++ )
  11675.       {
  11676.          _selectpalette( i );
  11677.          for( k=0; k <= 7; k++ )
  11678.          {
  11679.             _setbkcolor( bkcolor[k] );
  11680.             for( j=0; j<=3; j++ )
  11681.             {
  11682.                _settextposition( 1, 1 );
  11683.                printf( "background color: %8s\n", bkcolor_name[k] );
  11684.                printf( "palette: %d\ncolor: %d\n", i, j );
  11685.                _setcolor( j );
  11686.                _rectangle( _GFILLINTERIOR, 160, 100, 320, 200 );
  11687.                 getch();
  11688.             }
  11689.          }
  11690.       }
  11691.       _setvideomode( _DEFAULTMODE );
  11692.    }
  11693.  
  11694.  
  11695.  EGA, MCGA, and VGA Palettes
  11696.  
  11697.  At the beginning of this chapter, we mentioned the difference between color
  11698.  indexes and color values. An analogy might make things clearer. Imagine a
  11699.  painter who owns 64 tubes of paint and a painter's palette that has room for
  11700.  only 16 globs of paint at any one time. A painting created under these
  11701.  constraints could contain only 16 colors (selected from a total of 64). One
  11702.  of the EGA graphics modes (_ERESCOLOR) is similar: 16 color indexes chosen
  11703.  from a total of 64 color values. (Color indexes are sometimes called "color
  11704.  attributes," or "pixel values." Color values are sometimes called "actual
  11705.  colors.")
  11706.  
  11707.  VGA Color Mixing - VGA offers the widest variety of color values: 262,144
  11708.  (256K). Depending on the graphics mode, the VGA palette size may be 2, 16,
  11709.  or 256. When you select a color value, you specify a level of intensity
  11710.  ranging from 0-63 for each of the red, green, and blue color values. The
  11711.  long integer that defines a color value consists of four bytes (32 bits):
  11712.  
  11713.    MSB                             LSB
  11714.    zzzzzzzz zzBBBBBB zzGGGGGG zzRRRRRR
  11715.  
  11716.  The most-significant byte must contain all zeros. The two high bits in the
  11717.  remaining three bytes must also be 0. To mix a light red (pink), turn red
  11718.  all the way up, and mix in some green and blue:
  11719.  
  11720.    00000000 00100000 00100000 00111111
  11721.  
  11722.  To represent this value in hexadecimal, use the number  0x0020203FL (the  L
  11723.  marks it as a long value). You could also use the following macro:
  11724.  
  11725.    #define RGB ( r, g, b ) (0x3F3F3FL & ((long)(b) << 16 | (g) << 8 | (r)))
  11726.  
  11727.  To create pure yellow (100% red plus 100% green) and assign it to a variable
  11728.   y1, use this line:
  11729.  
  11730.    y1 = RGB( 63, 63, 0 );
  11731.  
  11732.  For white, turn all the colors on:  RGB( 63, 63, 63 ). For black, set all
  11733.  colors to 0:  RGB( 0, 0, 0 ).
  11734.  
  11735.  EGA Color Mixing - Mixing colors in EGA modes is similar to the mixing
  11736.  described above, but there are fewer intensities for the red, green, and
  11737.  blue components. In the modes that offer 64 colors, the R, G, and B values
  11738.  cover 2 bits and can range from 0 to 3. The long integer that defines an RGB
  11739.  color looks like this:
  11740.  
  11741.    MSB                             LSB
  11742.    zzzzzzzz zzBB???? zzGG???? zzRR????
  11743.  
  11744.  The bits marked  z  must be zeros and the bits marked with question marks
  11745.  can be any value. To form a pure red color value, you would use the constant
  11746.   0x00000030L. For cyan (blue plus green), use  0x00303000L. The RGB macro
  11747.  defined above is easily modified for EGA monitors:
  11748.  
  11749.    #define EGARGB( r, g, b ) (0x3F3F3FL & ((long)(b) << 20 | (g) << 12 | (r
  11750.    << 4)))
  11751.  
  11752.  In this macro, you would pass values in the range 0-3 instead of 0-63.
  11753.  
  11754.  
  11755.  EGA Color Graphics Modes
  11756.  
  11757.  The _MRES16COLOR, _HRES16COLOR, or _ERESCOLOR video modes display the best
  11758.  color graphics with an EGA adapter. The CGA modes will also display on the
  11759.  EGA but with the lower CGA resolution and decreased color options.
  11760.  
  11761.  The _remappalette function assigns a new color value to a color index. For
  11762.  example, when you first enter an EGA graphics mode, color index 1 equals the
  11763.  color value blue. To reassign the pure red color value to color index 1, you
  11764.  could use this line:
  11765.  
  11766.    _remappalette( 1, 0x000030L );
  11767.  
  11768.  Or, use the symbolic constant _RED, which is defined in the  GRAPH.H  file:
  11769.  
  11770.  
  11771.    _remappalette( 1, _RED );
  11772.  
  11773.  After this function call, any object currently drawn in color index 1 will
  11774.  instantly switch from blue to red.
  11775.  
  11776.  For EGA graphics, the first value is an integer in the range 0-15 and the
  11777.  second value is a long int defined as a mixture of red, green, and blue (you
  11778.  may also use the symbolic constants such as _RED).
  11779.  
  11780.  The _remapallpalette function changes all of the color indexes
  11781.  simultaneously. You pass it an array of color values. The first color value
  11782.  in the list becomes the new color associated with the color index 0.
  11783.  
  11784.  The number in a function call to set the color (such as _setcolor) is an
  11785.  index into the palette of available colors. In the default text palette, an
  11786.  index of 1 refers to blue but the palette could be remapped to change index
  11787.  1 to any other available color. As a result, the color produced by that
  11788.  pixel value also changes. The number of color indexes depends on the number
  11789.  of colors supported by the current video mode.
  11790.  
  11791.  The _remappalette and _remapallpalette functions work in all modes but only
  11792.  with the EGA, MCGA, or VGA hardware. The _remappalette and _remapallpalette
  11793.  functions fail and return a value of -1 when you attempt to remap a palette
  11794.  without the EGA, MCGA, or VGA hardware.
  11795.  
  11796.  The following program draws a rectangle with a red interior. In the default
  11797.  EGA palette, color index 4 is red. This color index is changed to _BLUE in
  11798.  this program.
  11799.  
  11800.    /* EGA.C: EGA palettes. */
  11801.  
  11802.    #include <stdio.h>
  11803.    #include <conio.h>
  11804.    #include <graph.h>
  11805.  
  11806.    main()
  11807.    {
  11808.       _setvideomode( _ERESCOLOR );
  11809.       _setcolor( 4 );
  11810.       _rectangle( _GFILLINTERIOR, 50, 50, 200, 200 );
  11811.  
  11812.       _settextposition( 1, 1 );
  11813.       printf( "Normal palette\n" );
  11814.       printf( "Press a key" );
  11815.       getch();
  11816.  
  11817.       _remappalette( 4, _BLUE );
  11818.  
  11819.       _settextposition( 1, 1 );
  11820.       printf( "Remapped palette\n" );
  11821.       printf( "Press a key" );
  11822.       getch();
  11823.  
  11824.       _remappalette( 4, _RED );
  11825.  
  11826.       _settextposition( 1, 1 );
  11827.       printf( "Restored palette\n" );
  11828.       printf( "Press a key to clear the screen" );
  11829.       getch();
  11830.  
  11831.       _clearscreen( _GCLEARSCREEN );
  11832.       _setvideomode( _DEFAULTMODE );
  11833.    }
  11834.  
  11835.  
  11836.  VGA Color Graphics Modes
  11837.  
  11838.  The VGA card adds graphics modes _VRES2COLOR, _VRES16COLOR, and
  11839.  _MRES256COLOR to your repertoire. EGA and CGA modes can also be used with
  11840.  the VGA hardware, but with either lower resolution or fewer color choices.
  11841.  
  11842.  The VGA color graphics modes operate with a range of 262,144 (256K)  color
  11843.  values. The _VRES2COLOR graphics mode displays two colors, the _VRES16COLOR
  11844.  graphics mode displays 16, and the _MRES256COLOR graphics mode displays 256
  11845.  colors from the available VGA colors.
  11846.  
  11847.  Changing the Palette - The _remappalette function changes a color index to a
  11848.  specified color value. The function below remaps the color index 1 to the
  11849.  color value given by the symbolic constant _RED (which represents red).
  11850.  After this statement is executed, whatever was displayed as blue will now
  11851.  appear as red:
  11852.  
  11853.    _remappalette( 1, _RED );  /*reassign color index 1
  11854.                                 to VGA red */
  11855.  
  11856.  Use the _remapallpalette function to remap all of the available color
  11857.  indexes simultaneously. The function's argument references an array of color
  11858.  values that reflects the remapping. The first color number in the list
  11859.  becomes the new color associated with color index 0.
  11860.  
  11861.  Symbolic constants for the default color numbers are supplied so that the
  11862.  remapping of VGA colors is compatible with EGA practice. The names of these
  11863.  constants are self-explanatory. For example, the color numbers for black,
  11864.  red, and light yellow are represented by the symbolic constants _BLACK,
  11865.  _RED, and _LIGHTYELLOW.
  11866.  
  11867.  All of the VGA display modes operate with any VGA video monitor. Colors are
  11868.  displayed as shades of gray when the monochrome analog display is connected.
  11869.  
  11870.  
  11871.  If you have a VGA card, the HORIZON.C program illustrates what can be done
  11872.  with the range of 256 colors:
  11873.  
  11874.    /* HORIZON.C: VGA graphics with cycling of 256 colors. */
  11875.  
  11876.    #include <stdio.h>
  11877.    #include <stdlib.h>
  11878.    #include <conio.h>
  11879.    #include <graph.h>
  11880.  
  11881.    #define RED 0x0000003FL
  11882.    #define GRN 0x00003F00L
  11883.    #define BLU 0x003F0000L
  11884.    #define WHT 0x003F3F3FL
  11885.    #define STEP 21
  11886.  
  11887.    struct videoconfig screen;
  11888.    long int rainbow[512];
  11889.  
  11890.    main()
  11891.    {
  11892.       int i;
  11893.       long int col, gray;
  11894.  
  11895.       if( _setvideomode( _MRES256COLOR ) == 0 )
  11896.       {
  11897.          printf( "This program requires a VGA card.\n" );
  11898.          exit( 0 );
  11899.       }
  11900.       for( col = 0; col < 64; col++ )
  11901.       {
  11902.          gray = col | (col << 8) | (col << 16);
  11903.          rainbow[col] = rainbow[col + 256] = BLU & gray;
  11904.          rainbow[col + 64] = rainbow[col + 64 + 256] = BLU | gray;
  11905.          rainbow[col + 128] = rainbow[col + 128 + 256] = RED | (WHT & ~gray);
  11906.          rainbow[col + 192] = rainbow[col + 192 + 256] = RED & ~gray;
  11907.       }
  11908.       _setvieworg( 160, 85 );
  11909.  
  11910.       for( i = 0; i < 255; i++ )
  11911.       {
  11912.          _setcolor( 255 - i );
  11913.          _moveto( i, i - 255 );
  11914.          _lineto( -i, 255 - i );
  11915.          _moveto( -i, i - 255 );
  11916.          _lineto( i, 255 - i );
  11917.          _ellipse( _GBORDER, -i, -i / 2, i, i / 2 );
  11918.       }
  11919.       for( i = 0; !kbhit(); i += STEP, i %= 256 )
  11920.          _remapallpalette( &(rainbow[i]) );
  11921.  
  11922.       _setvideomode( _DEFAULTMODE );
  11923.    }
  11924.  
  11925.  
  11926.  Using the Color Video Text Modes
  11927.  
  11928.  Two color video text modes, _TEXTC40 and _TEXTC80, can be used with the CGA,
  11929.  EGA, and VGA displays. These modes display steady or blinking text in any of
  11930.  16 foreground colors with any one of 8 background colors.
  11931.  
  11932.  
  11933.  Basics of Text Color Selection
  11934.  
  11935.  In a video text mode, each displayed character requires two bytes of video
  11936.  memory. The first byte contains the ASCII code representing the character
  11937.  and the second byte contains the display attribute. In the CGA color video
  11938.  text modes, the attribute byte determines the color and whether it will
  11939.  blink. Sixteen colors are available: the CGA pixel values, and the default
  11940.  EGA and VGA pixel values. Since the EGA and VGA palette can be remapped,
  11941.  these values can be made to correspond to any set of 16 colors with the
  11942.  appropriate palette mapping.
  11943.  
  11944.  
  11945.  Using Text Colors
  11946.  
  11947.  Use the _gettextcolor and _getbkcolor functions to find the current text
  11948.  foreground and background colors.
  11949.  
  11950.  Values in the range 0-15 are interpreted as normal color. Values in the
  11951.  range 16-31 are the same colors as those in the range 0-15 but with blinking
  11952.  text.
  11953.  
  11954.  Use the _settextcolor and _setbkcolor functions to set foreground and
  11955.  background colors in video text mode. These functions use a single argument
  11956.  that specifies the pixel value to be used for text displayed with the
  11957.  _outtext function. The color indexes for color video text modes are defined
  11958.  in Table 13.4.
  11959.  
  11960.  Table 13.4  Text Colors
  11961.  
  11962. ╓┌───────┌─────────┌───────┌─────────────────────────────────────────────────╖
  11963.  Number  Color     Number  Color
  11964.  ────────────────────────────────────────────────────────────────────────────
  11965.  0       Black     8       Dark gray
  11966.  1       Blue      9       Light blue
  11967.  2       Green     10      Light green
  11968.  3       Cyan      11      Light cyan
  11969.  4       Red       12      Light red
  11970.  5       Magenta   13      Light magenta
  11971.  6       Brown     14      Light brown
  11972.  Number  Color     Number  Color
  11973.  ────────────────────────────────────────────────────────────────────────────
  11974. 6       Brown     14      Light brown
  11975.  7       White     15      Light white
  11976.  ────────────────────────────────────────────────────────────────────────────
  11977.  
  11978.  
  11979.  
  11980.  Displaying Color Text
  11981.  
  11982.  The _settextposition function moves the cursor to a row and column for
  11983.  displaying color text. The _outtext function displays the text.
  11984.  
  11985.  
  11986.  Example: Viewing Text Colors
  11987.  
  11988.  The following program displays a chart showing all possible combinations of
  11989.  text and background colors:
  11990.  
  11991.    /* COLTEXT.C: Display text in color. */
  11992.  
  11993.    #include <stdio.h>
  11994.    #include <conio.h>
  11995.    #include <graph.h>
  11996.  
  11997.    char buffer [80];
  11998.  
  11999.    main()
  12000.    {
  12001.       int blink,fgd;
  12002.       long bgd;
  12003.  
  12004.       _clearscreen( _GCLEARSCREEN );
  12005.       printf( "Text color attributes:\n" );
  12006.  
  12007.       for( blink=0; blink<=16; blink+=16 )
  12008.       {
  12009.          for( bgd=0; bgd<8; bgd++ )
  12010.          {
  12011.             _setbkcolor( bgd );
  12012.             _settextposition( bgd + ((blink / 16) * 9) + 3, 1 );
  12013.             _settextcolor( 7 );
  12014.             sprintf( buffer, "Bgd: %d Fgd:", bgd );
  12015.             _outtext( buffer );
  12016.  
  12017.             for( fgd=0; fgd<16; fgd++ )
  12018.             {
  12019.                _settextcolor( fgd+blink );
  12020.                sprintf( buffer, " %2d ", fgd+blink );
  12021.                _outtext( buffer );
  12022.             }
  12023.          }
  12024.       }
  12025.       getch();
  12026.       _setvideomode( _DEFAULTMODE );
  12027.    }
  12028.  
  12029.  
  12030.  Text Coordinates
  12031.  
  12032.  Before you can write a program to print a word over there on the screen, you
  12033.  need a system that describes to the compiler where there really is. QuickC
  12034.  divides the text screen into rows and columns. See Figure 13.2.
  12035.  
  12036.  (This figure may be found in the printed book.)
  12037.  
  12038.  Two important conventions to keep in mind about video text mode are:
  12039.  
  12040.  
  12041.    1.  Numbering starts at 1, not 0. An 80-column screen contains columns
  12042.        1-80.
  12043.  
  12044.    2.  The row is always listed before the column.
  12045.  
  12046.  
  12047.  If the screen is in a video text mode that displays 25 rows and 80 columns
  12048.  (as in Figure 13.2), the rows are numbered 1-25 and the columns are numbered
  12049.  1-80. In functions such as _settextposition, which is called in the next
  12050.  example program, the parameters you pass are row and column (in that order).
  12051.  
  12052.  
  12053.  
  12054.  Graphics Coordinates
  12055.  
  12056.  A similar (but slightly different) system is used for locating pixels on a
  12057.  graphics screen. There are three ways of describing the location of pixels
  12058.  on the screen:
  12059.  
  12060.  
  12061.    1.  The physical screen coordinates
  12062.  
  12063.    2.  The viewport coordinates
  12064.  
  12065.    3.  The window coordinates
  12066.  
  12067.  
  12068.  Each method is explained in the following sections.
  12069.  
  12070.  
  12071.  The Physical Screen
  12072.  
  12073.  Suppose you write a program that calls _setvideomode and puts the screen
  12074.  into the VGA graphics mode _VRES16COLOR. This gives you a screen containing
  12075.  640 horizontal pixels and 480 vertical pixels. The individual pixels are
  12076.  named by their location relative to the x axis and y axis, as shown in
  12077.  Figure 13.3.
  12078.  
  12079.  (This figure may be found in the printed book.)
  12080.  
  12081.  Two important differences between text coordinates and pixel coordinates
  12082.  are:
  12083.  
  12084.  
  12085.    1.  Numbering starts at 0, not 1. If there are 640 pixels, they're
  12086.        numbered 0-639.
  12087.  
  12088.    2.  The x coordinate (equivalent to a text column) is listed before the y
  12089.        coordinate.
  12090.  
  12091.  
  12092.  The upper left corner is called the "origin." The x and y coordinates for
  12093.  the origin are always (0, 0). If you use variables to refer to pixel
  12094.  locations, declare them as integers.
  12095.  
  12096.  
  12097.  Changing the Origin with _setvieworg
  12098.  
  12099.  The _setvieworg function changes the current location of the viewport's
  12100.  origin. When you first enter graphics mode, the "viewport" is equivalent to
  12101.  the physical
  12102.  
  12103.  screen. You pass two integers, which represent the x and y coordinates of a
  12104.  physical screen location. For example, the following line would move the
  12105.  origin to the physical screen location (50, 100):
  12106.  
  12107.    _setvieworg( 50, 100 );
  12108.  
  12109.  The effect on the screen is illustrated in Figure 13.4.
  12110.  
  12111.  (This figure may be found in the printed book.)
  12112.  
  12113.  The number of pixels hasn't changed, but the names given to the points have
  12114.  changed. The x axis now ranges from -50 to +589 instead of 0 to 639. The y
  12115.  axis now covers the values -100 to +379. (If you own an adapter other than
  12116.  the VGA, the numbers are different but the effect is the same.)
  12117.  
  12118.  All standard graphics functions are affected by the new origin, including
  12119.  _arc, _ellipse, _lineto, _moveto, _pie, and _rectangle.
  12120.  
  12121.  For example, if you call the _rectangle function after relocating the
  12122.  viewport origin, and pass it the values (0, 0) and (40, 40), the rectangle
  12123.  would be drawn 50 pixels from the left edge of the screen and 100 pixels
  12124.  from the top. It would not appear in the upper left corner.
  12125.  
  12126.  The values passed to _setvieworg are always physical screen locations.
  12127.  Suppose you called the same function twice:
  12128.  
  12129.    _setvieworg( 50, 100 );
  12130.    _setvieworg( 50, 100 );
  12131.  
  12132.  The viewport origin would not move to (100, 200). It would remain at the
  12133.  phys-ical screen location (50, 100).
  12134.  
  12135.  
  12136.  Defining a Clipping Region with _setcliprgn
  12137.  
  12138.  The _setcliprgn function creates an invisible rectangular area on the screen
  12139.  called a "clipping region." Attempts to draw inside the clipping region are
  12140.  successful, while attempts to draw outside the region are not.
  12141.  
  12142.  When you first enter a graphics mode, the default clipping region occupies
  12143.  the entire screen. QuickC ignores any attempts to draw outside the screen.
  12144.  
  12145.  Changing the clipping region requires one call to _setcliprgn. Suppose
  12146.  you've entered the CGA graphics mode  _MRES4COLOR, which has a screen
  12147.  resolution of 320 x 200. If you draw a diagonal line from (0, 0) to (319,
  12148.  199), from the top left to the bottom right corner, the screen looks like
  12149.  Figure 13.5.
  12150.  
  12151.  (This figure may be found in the printed book.)
  12152.  
  12153.  You could create a clipping region with this line:
  12154.  
  12155.    _setcliprgn( 10, 10, 309, 189 )
  12156.  
  12157.  With the clipping region in effect, the same _lineto command would put the
  12158.  line shown in Figure 13.6 on the screen.
  12159.  
  12160.  (This figure may be found in the printed book.)
  12161.  
  12162.  The broken lines don't actually print on the screen. They indicate the outer
  12163.  bounds of the clipping region.
  12164.  
  12165.  
  12166.  Viewport Coordinates
  12167.  
  12168.  The _setviewport function establishes a new viewport within the boundaries
  12169.  of the physical screen. A standard viewport has two distinguishing features:
  12170.  
  12171.  
  12172.  
  12173.    1.  The origin of a viewport is in the upper left corner.
  12174.  
  12175.    2.  The clipping region matches the outer boundaries of the viewport.
  12176.  
  12177.  
  12178.  The _setviewport function does the same thing as calling the _setvieworg and
  12179.  the _setcliprgn functions.
  12180.  
  12181.  
  12182.  Real Coordinates in a Window
  12183.  
  12184.  Functions that refer to coordinates on the physical screen and within the
  12185.  viewport require integer values. In real-life graphing applications, you
  12186.  might wish to use floating-point values─stock prices, the price of wheat,
  12187.  average rainfall, and so on. The _setwindow function allows you to scale the
  12188.  screen to almost any size. In addition, the window-related functions take
  12189.  double-precision, floating-point values instead of integers.
  12190.  
  12191.  For example, say you want to graph 12 months of average temperatures that
  12192.  range from -40 to +100. You could add the following line to your program:
  12193.  
  12194.    _setwindow( TRUE, 1.0, -40.0, 12.0, 100.0 );
  12195.  
  12196.  The first argument is the invert flag, which puts the lowest y value in the
  12197.  bottom left corner. The minimum and maximum Cartesian coordinates follow
  12198.  (the decimal point marks them as floating-point values). The new
  12199.  organization of the screen is shown in Figure 13.7.
  12200.  
  12201.  (This figure may be found in the printed book.)
  12202.  
  12203.  Note that January and December are plotted on the left and right edges of
  12204.  the screen. In an application like this, it might be better to number the x
  12205.  axis from 0.0 to 13.0, to provide some extra space.
  12206.  
  12207.  If you next plot a point with _setpixel_w or draw a line with _lineto_w, the
  12208.  values are automatically scaled to the established window.
  12209.  
  12210.  Follow these four steps to use real-coordinate graphics:
  12211.  
  12212.  
  12213.    1.  Enter a graphics mode with _setvideomode.
  12214.  
  12215.    2.  Use _setviewport to create a viewport area. (This step is optional if
  12216.        you plan to use the entire screen.)
  12217.  
  12218.    3.  Create a real-coordinate window with _setwindow, passing an int invert
  12219.        flag and four double x and y coordinates for the minimum and maximum
  12220.        values.
  12221.  
  12222.    4.  Draw graphics shapes with _rectangle_w and other functions. Do not
  12223.        confuse _rectangle (the viewport function) with _rectangle_w (the
  12224.        window function for drawing rectangles). All window functions end with
  12225.        an underscore and a letter w or an underscore and wxy.
  12226.  
  12227.  
  12228.  Real-coordinate graphics can give you a lot of flexibility. For example, you
  12229.  can fit either axis into a small range (such as 151.25 to 151.45) or into a
  12230.  large range (-50,000 to +80,000), depending on the type of data you're
  12231.  graphing. In addition, by changing the window coordinates, you can create
  12232.  the effects of zooming in or panning across a figure.
  12233.  
  12234.  
  12235.  Example Program
  12236.  
  12237.  The program below illustrates some ways to use the real-coordinate windowing
  12238.  functions.
  12239.  
  12240.    /* REALG.C: Real-coordinate graphics. */
  12241.  
  12242.    #include <stdio.h>
  12243.    #include <conio.h>
  12244.    #include <graph.h>
  12245.  
  12246.    #define TRUE 1
  12247.    #define FALSE 0
  12248.  
  12249.    int four_colors( void );
  12250.    void three_graphs( void );
  12251.    void grid_shape( void );
  12252.  
  12253.    int halfx, halfy;
  12254.    struct videoconfig screen;
  12255.    double bananas[] =
  12256.      {
  12257.        -0.3, -0.2, -0.224, -0.1, -0.5, +0.21, +2.9,
  12258.        +0.3, +0.2, 0.0, -0.885, -1.1, -0.3, -0.2,
  12259.        +.001, +.005, +0.14, 0.0, -0.9, -0.13, +0.3
  12260.      };
  12261.  
  12262.    main()
  12263.    {
  12264.      if( four_colors() )
  12265.         three_graphs();
  12266.      else
  12267.         printf( "This program requires a CGA, EGA,\
  12268.                 or VGA graphics card.\n" );
  12269.    }
  12270.    /*
  12271.    . Additional functions defined below
  12272.    .
  12273.    .
  12274.    */
  12275.  
  12276.  The main function is very short. It calls the  four_colors  function
  12277.  (defined below), which attempts to enter a graphics mode where at least four
  12278.  colors are available. If it succeeds, the  three_graphs  function is called,
  12279.  which uses the numbers in the  bananas  array to draw three graphs. The
  12280.  REALG.C screen output is shown in Figure 13.8.
  12281.  
  12282.  (This figure may be found in the printed book.)
  12283.  
  12284.  It's worth noting that the  grid_shape  function (defined below) that draws
  12285.  the graphs is using the same numbers in each case. However, the program uses
  12286.  three different real-coordinate windows. The two windows in the top half are
  12287.  the same size in physical coordinates, but they have different window sizes.
  12288.  In all three cases, the grid is 2 units wide. In the upper left corner, the
  12289.  window is 4 units wide; in the upper right, the window is 6 units wide,
  12290.  which makes the graph appear smaller.
  12291.  
  12292.  In two of the three graphs, one of the lines goes off the edge, outside the
  12293.  clipping region. The lines do not intrude into the other windows, since
  12294.  defining a window creates a clipping region.
  12295.  
  12296.  Finally, note that the graph on the bottom of the screen seems to be upside
  12297.  down with respect to the two graphs above it.
  12298.  
  12299.  
  12300.  Checking the Adapter
  12301.  
  12302.  The first step in any graphics program is to enter a graphics mode. The
  12303.  four_colors  function performs this step:
  12304.  
  12305.    /* four_colors function from REALG.C. */
  12306.  
  12307.    int four_colors( void )
  12308.    {
  12309.       _getvideoconfig( &screen );
  12310.       switch( screen.adapter )
  12311.       {
  12312.          case _CGA:
  12313.          case _OCGA:
  12314.             _setvideomode( _MRES4COLOR );
  12315.             break;
  12316.          case _EGA:
  12317.          case _OEGA:
  12318.             _setvideomode( _ERESCOLOR );
  12319.             break;
  12320.          case _VGA:
  12321.          case _OVGA:
  12322.             _setvideomode( _VRES16COLOR );
  12323.             break;
  12324.          default:
  12325.             return( FALSE );
  12326.       }
  12327.       _getvideoconfig( &screen );
  12328.       return( TRUE );
  12329.    }
  12330.  
  12331.  The _getvideoconfig function places some information into the videoconfig
  12332.  structure called  screen. Then we use the member  screen.adapter  in a
  12333.  switch statement construct to turn on the matching graphics mode. The
  12334.  symbolic constants _CGA and the rest are defined in the GRAPH.H file. The
  12335.  modes that begin with the letter O are Olivetti modes.
  12336.  
  12337.  If the computer is equipped with a color card, _getvideoconfig returns a
  12338.  TRUE. If it is not, it returns a FALSE, which causes main to skip the
  12339.  three_graphs  function.
  12340.  
  12341.  
  12342.  Three Windows, Three Graphs
  12343.  
  12344.  If the  four_colors  function works properly, main calls the function below,
  12345.  which prints the three graphs.
  12346.  
  12347.    /* three_graphs function from REALG.C. */
  12348.  
  12349.    void three_graphs( void )
  12350.    {
  12351.       int xwidth, yheight, cols, rows;
  12352.       struct _wxycoord upleft, botright;
  12353.  
  12354.       _clearscreen( _GCLEARSCREEN );
  12355.       xwidth = screen.numxpixels;
  12356.       yheight = screen.numypixels;
  12357.       halfx = xwidth/2;
  12358.       halfy = yheight/2;
  12359.       cols = screen.numtextcols;
  12360.       rows = screen.numtextrows;
  12361.  
  12362.       /* first window */
  12363.       _setviewport( 0, 0, halfx-1, halfy-1 );
  12364.       _settextwindow( 1, 1, rows/2, cols/2 );
  12365.       _setwindow( FALSE, -2.0, -2.0, 2.0, 2.0 );
  12366.       grid_shape();
  12367.       _rectangle( _GBORDER, 0, 0, halfx-1, halfy-1 );
  12368.  
  12369.       /* second window */
  12370.       _setviewport( halfx, 0, xwidth-1, halfy-1 );
  12371.       _settextwindow( 1, cols/2+1, rows/2, cols );
  12372.       _setwindow( FALSE, -3.0, -3.0, 3.0, 3.0 );
  12373.       grid_shape();
  12374.       _rectangle_w( _GBORDER, -3.0, -3.0, 3.0, 3.0 );
  12375.  
  12376.       /* third window */
  12377.       _setviewport( 0, halfy, xwidth-1, yheight-1 );
  12378.       _settextwindow( rows/2+1, 1, rows, cols );
  12379.       _setwindow( TRUE, -3.0, -1.5, 1.5, 1.5 );
  12380.       grid_shape();
  12381.       upleft.wx = -3.0;
  12382.       upleft.wy = -1.5;
  12383.       botright.wx = 1.5;
  12384.       botright.wy = 1.5;
  12385.       _rectangle_wxy( _GBORDER, &upleft, &botright );
  12386.  
  12387.       getch();
  12388.       _setvideomode( _DEFAULTMODE );
  12389.    }
  12390.  
  12391.  Clearing the Screen - Although entering a graphics mode automatically clears
  12392.  the screen, it doesn't hurt to be sure, so  three_graphs  calls the
  12393.  _clearscreen function:
  12394.  
  12395.    _clearscreen( _GCLEARSCREEN );
  12396.  
  12397.  The _GCLEARSCREEN constant causes the entire physical screen to clear. Other
  12398.  options include _GVIEWPORT and _GWINDOW, which clear the current viewport
  12399.  and the current text window, respectively.
  12400.  
  12401.  The First Window - After assigning values to some variables, the
  12402.  three_graphs  function creates the first window:
  12403.  
  12404.    _setviewport( 0, 0, halfx - 1, halfy - 1 );
  12405.    _settextwindow( 1, 1, rows / 2, cols / 2 );
  12406.    _setwindow( FALSE, -2.0, -2.0, 2.0, 2.0 );
  12407.  
  12408.  First a viewport is defined to cover the upper left quarter of the screen.
  12409.  Next, a text window is defined within the boundaries of that border. (Note
  12410.  the numbering starts at 1 and the row location precedes the column.)
  12411.  Finally, a window is defined. The FALSE constant forces the y axis to
  12412.  increase from top to bottom. The corners of the window are (-2.0, -2.0) in
  12413.  the upper left and (2.0, 2.0) in the bottom right corner.
  12414.  
  12415.  Next, the function  grid_shape  is called, and a border is added to the
  12416.  window:
  12417.  
  12418.    grid_shape();
  12419.    _rectangle( _GBORDER, 0, 0, halfx-1, halfy-1 );
  12420.  
  12421.  Note that this is the standard _rectangle function, which takes coordinates
  12422.  relative to the viewport (not window coordinates).
  12423.  
  12424.  Two More Windows - The two other windows are similar to the first. All three
  12425.  call  grid_shape  (defined below), which draws a grid from location (-1.0,
  12426.  -1.0) to (+1.0, +1.0). The grid appears in different sizes because the
  12427.  coordinates in the windows vary. The second window ranges from (-3.0, -3.0)
  12428.  to (+3.0, +3.0), so the width of the grid is one-third the width of the
  12429.  second window, while it is one-half the width of the first.
  12430.  
  12431.  Note also that the third window contains a TRUE as the first argument. This
  12432.  causes the y axis to increase from bottom to top, instead of top to bottom.
  12433.  As a result, this graph appears to be upside down in relation to the other
  12434.  two.
  12435.  
  12436.  After calling  grid_shape, the program frames each window with one of the
  12437.  following functions:
  12438.  
  12439.    _rectangle( _GBORDER, 0, 0, halfx -1, halfy -1 );
  12440.  
  12441.    _rectangle_w( _GBORDER, -3.0, -3.0, 3.0, 3.0 );
  12442.  
  12443.    _rectangle_wxy( _GBORDER, &upleft, &botright );
  12444.  
  12445.  All three functions contain a fill flag as the first argument. The
  12446.  _rectangle function takes integer arguments that refer to the viewport
  12447.  screen coordinates. The function _rectangle_w takes four double-precision,
  12448.  floating-point values referring to window coordinates: upper left x, upper
  12449.  left y, lower right x, and lower right y. The function _rectangle_wxy takes
  12450.  two arguments: the addresses of two structures of type _wxycoord, which
  12451.  contains two double types named wx and wy. The structure is defined in
  12452.  GRAPH.H. The values are assigned just before _rectangle_wxy is called.
  12453.  
  12454.  Text, Colors, and Lines - The  grid_shape  function is shown below:
  12455.  
  12456.    /* grid_shape from the REALG.C program. */
  12457.  
  12458.    void grid_shape( void )
  12459.    {
  12460.       int i, numc, x1, y1, x2, y2;
  12461.       double x, y;
  12462.       char txt[80];
  12463.  
  12464.    numc = screen.numcolors;
  12465.       for( i = 1; i <numc; i++ )
  12466.       {
  12467.          _settextposition( i, 2 );
  12468.          _settextcolor( i );
  12469.          sprintf( txt, "Color %d", i );
  12470.          _outtext( txt );
  12471.       }
  12472.       _setcolor( 1 );
  12473.       _rectangle_w( _GBORDER, -1.0, -1.0, 1.0, 1.0 );
  12474.       _rectangle_w( _GBORDER, -1.02, -1.02, 1.02, 1.02 );
  12475.  
  12476.    for( x = -0.9, i = 0; x <0.9; x += 0.1 )
  12477.       {
  12478.          _setcolor( 2 );
  12479.          _moveto_w( x, -1.0 );
  12480.          _lineto_w( x, 1.0 );
  12481.          _moveto_w( -1.0, x );
  12482.          _lineto_w( 1.0, x );
  12483.  
  12484.          _setcolor( 3 );
  12485.          _moveto_w( x - 0.1, bananas[i++] );
  12486.          _lineto_w( x, bananas[i] );
  12487.       }
  12488.       _moveto_w( 0.9, bananas[i++] );
  12489.       _lineto_w( 1.0, bananas[i] );
  12490.    }
  12491.  
  12492.  First, the number of available color indexes is assigned to the  numc
  12493.  variable and a for loop displays all of the available colors:
  12494.  
  12495.    numc = screen.numcolors;
  12496.    for( i = 1; i < numc; i++ )
  12497.    {
  12498.       _settextposition( i, 2 );
  12499.       _settextcolor( i );
  12500.       sprintf( txt, "Color %d", i );
  12501.       _outtext( txt );
  12502.    }
  12503.  
  12504.  The names of the functions are self-explanatory. The advantage of using
  12505.  _outtext in graphics mode is that, unlike printf, you can control the text
  12506.  color.
  12507.  
  12508.  The function names that end with _w work the same as their viewport
  12509.  equivalents, except you pass double-precision, floating-point values instead
  12510.  of integers. For example, you pass integers to _lineto but floating-point
  12511.  values to _lineto_w.
  12512.  
  12513.  If you're interested in further explorations of graphics, Chapters 14 and 15
  12514.  introduce Presentation Graphics and fonts, both of which offer even more
  12515.  graphics options.
  12516.  
  12517.  
  12518.  
  12519.  
  12520.  
  12521.  
  12522.  Chapter 14  Presentation Graphics
  12523.  ────────────────────────────────────────────────────────────────────────────
  12524.  
  12525.  Presentation Graphics is the name given to a library of chart-generating
  12526.  functions included with the QuickC package. With these functions your QuickC
  12527.  programs can display data as a variety of graphs such as pie charts, bar and
  12528.  column charts, line graphs, and scatter diagrams. Whole columns of
  12529.  unintelligible numbers can be reduced to a single expressive picture with
  12530.  Presentation Graphics.
  12531.  
  12532.  This chapter shows you how to use the Presentation Graphics library in your
  12533.  QuickC programs. The first section is an introduction to Presentation
  12534.  Graphics. It explains terminology and describes some of the library's many
  12535.  capabilities. The middle sections of this chapter list the steps involved in
  12536.  writing a charting program and illustrate them with short examples.
  12537.  
  12538.  The concluding portions of the chapter delve more deeply into Presentation
  12539.  Graphics. Here you'll learn about the Presentation Graphics default data
  12540.  structures and how to manipulate them. The final section presents a short
  12541.  reference list of all the functions that comprise the Presentation Graphics
  12542.  library.
  12543.  
  12544.  To use Presentation Graphics you need a graphics adapter and a monitor
  12545.  capable of bit-mapped display─the same equipment mentioned in Chapter 13,
  12546.  "Graphics." Support is provided for CGA, EGA, VGA, MCGA, Hercules monochrome
  12547.  graphics, and Olivetti Color Board.
  12548.  
  12549.  
  12550.  Terminology
  12551.  
  12552.  Certain terms and phrases pertaining to Presentation Graphics and its
  12553.  functions are used throughout this chapter. The following description of
  12554.  Presentation Graphics terminology will help you better understand this
  12555.  chapter.
  12556.  
  12557.  
  12558.  Data Series
  12559.  
  12560.   Groups or series of data can be graphed on the same chart.
  12561.  
  12562.  Data that are related by a common idea or purpose constitutes a "series."
  12563.  For example, the prices of a futures commodity over the course of a year
  12564.  form a single series of data. The commodity's volume and open interest form
  12565.  two more series for the same period of time. Presentation Graphics allows
  12566.  you to plot multiple series on the same graph. In theory only your system's
  12567.  memory capacity restricts the number of data series that can appear on a
  12568.  graph. However, there are practical considerations.
  12569.  
  12570.  Characteristics such as color and pattern help distinguish one series from
  12571.  an-other. You can more readily differentiate series on a color monitor than
  12572.  you can on a monochrome monitor. The number of series that can comfortably
  12573.  appear on the same chart depends on the chart type and the number of
  12574.  available colors. Only experimentation can tell you what is best for your
  12575.  system.
  12576.  
  12577.  
  12578.  Categories
  12579.  
  12580.  Categories are non-numeric data. A set of categories forms a frame of
  12581.  reference for the comparisons of numeric data. For example, the months of
  12582.  the year are categories against which numeric data such as rainfall can be
  12583.  plotted.
  12584.  
  12585.  Regional sales provide another example. A chart can show comparisons of a
  12586.  company's sales in different parts of the country. Each region forms a
  12587.  category. The sales within each region are numeric data that have meaning
  12588.  only within the context of a particular category.
  12589.  
  12590.  
  12591.  Values
  12592.  
  12593.  Values are numeric data. Sales, stock prices, air temperatures,
  12594.  populations─all are series of values that can be plotted against categories
  12595.  or against other values.
  12596.  
  12597.  Presentation Graphics allows you to overlay different series of value data
  12598.  on a single graph. For example, average monthly temperatures or monthly
  12599.  sales of heating oil during different years─or a combination of temperatures
  12600.  and sales─can be plotted together on the same graph.
  12601.  
  12602.  
  12603.  Pie Charts
  12604.  
  12605.  (Please refer to the printed book.)
  12606.  
  12607.  "Pie charts" are used to represent data by showing the relationship of each
  12608.  part to the whole. A good example is a company's monthly sales figures. The
  12609.  sales to the company's various accounts can be represented as slices of the
  12610.  pie.
  12611.  
  12612.  Presentation Graphics can display either a standard or an "exploded" pie
  12613.  chart. The exploded view shows the pie with one or more pieces separated for
  12614.  emphasis. Presentation Graphics optionally labels each slice of a pie chart
  12615.  with a percentage figure.
  12616.  
  12617.  
  12618.  Bar and Column Charts
  12619.  
  12620.  (Please refer to the printed book.)
  12621.  
  12622.  As the name implies, a "bar chart" shows data as horizontal bars. Bar charts
  12623.  show comparisons among items rather than absolute value.
  12624.  
  12625.  "Column charts"
  12626.  
  12627.  (Please refer to the printed book.)
  12628.  
  12629.  are vertical bar charts. Column charts are frequently used to show
  12630.  variations over a period of time, since they suggest time flow better than a
  12631.  bar chart
  12632.  Line Graphs
  12633.  
  12634.  (Please refer to the printed book.)
  12635.  
  12636.  "Line graphs" illustrate trends or changes in data. They show how a series
  12637.  of values varies against some category─for example, average temperatures
  12638.  throughout a particular year.
  12639.  
  12640.  Traditionally, line graphs show a collection of data points connected by
  12641.  lines; hence the name. However, Presentation Graphics can also plot points
  12642.  that are not connected by lines.
  12643.  
  12644.  
  12645.  Scatter Diagrams
  12646.  
  12647.  (Please refer to the printed book.)
  12648.  
  12649.  A "scatter diagram" is the only type of graph available in Presentation
  12650.  Graphics that compares values with values. A scatter diagram simply plots
  12651.  points. One value may correspond to several other values.
  12652.  
  12653.  Scatter diagrams illustrate the relationship between numeric values in
  12654.  different groups of data. They graphically show trends and correlations not
  12655.  easily detected from rows and columns of raw numbers. This explains why
  12656.  scatter diagrams are a favorite tool of statisticians and forecasters.
  12657.  
  12658.  They are most useful with relatively large populations of data. Consider,
  12659.  for example, the relationship between personal income and family size. If
  12660.  you poll one thousand wage earners for their income and family size, you
  12661.  have a scatter diagram with one thousand points. If you combine your results
  12662.  so that you're left with one average income for each family size, you have a
  12663.  line graph.
  12664.  
  12665.  
  12666.  Axes
  12667.  
  12668.  All Presentation Graphics charts except pie charts are displayed with two
  12669.  perpendicular reference lines called "axes." The vertical or y axis runs
  12670.  from top to bottom of the chart and is placed against the left side of the
  12671.  screen. The horizontal or x axis runs from left to right across the bottom
  12672.  of the screen.
  12673.  
  12674.   The chart type determines which axes are used for category and value data.
  12675.  
  12676.  
  12677.  The x axis is the category axis for column and line charts and the value
  12678.  axis for bar charts. The y axis is the value axis for column and line charts
  12679.  and the category axis for bar charts.
  12680.  
  12681.  
  12682.  Chart Windows
  12683.  
  12684.  The "chart window" defines that part of the screen on which the chart is
  12685.  drawn. Normally the window fills the entire screen, but Presentation
  12686.  Graphics allows you to resize the window for smaller graphs. By redefining
  12687.  the chart window to different screen locations, you can view separate graphs
  12688.  together on the same screen.
  12689.  
  12690.  
  12691.  Data Windows
  12692.  
  12693.  While the chart window defines the entire graph including axes and labels,
  12694.  the "data window" defines only the actual plotting area. This is the portion
  12695.  of the graph to the right of the y axis and above the x axis. You cannot
  12696.  directly specify the size of the data window. Presentation Graphics
  12697.  automatically determines its size based on the dimensions of the chart
  12698.  window.
  12699.  
  12700.  
  12701.  Chart Styles
  12702.  
  12703.  Each of the five types of Presentation Graphics charts can appear in two
  12704.  different chart styles, as described in Table 14.1.
  12705.  
  12706.  Table 14.1  Presentation Graphics Chart Styles
  12707.  
  12708. ╓┌───────────┌───────────────────┌───────────────────────────────────────────╖
  12709.  Chart Type  Chart Style #1      Chart Style #2
  12710.  ────────────────────────────────────────────────────────────────────────────
  12711.  Pie         With percentages    Without percentages
  12712.  Bar         Side-by-side        Stacked
  12713.  Column      Side-by-side        Stacked
  12714.  Line        Points with lines   Points only
  12715.  Scatter     Points with lines   Points only
  12716.  ────────────────────────────────────────────────────────────────────────────
  12717.  
  12718.  
  12719.  Bar and column charts have only one style when displaying a single series of
  12720.  data. The styles "side-by-side" and "stacked" are applicable when more than
  12721.  one series appear on the same chart. The first style arranges the bars or
  12722.  columns for the different series side by side, showing relative heights or
  12723.  lengths. The stacked style, illustrated in Figure 14.1 for a column chart,
  12724.  emphasizes relative sizes between bars or columns.
  12725.  
  12726.  (This figure may be found in the printed book.)
  12727.  
  12728.  
  12729.  Legends
  12730.  
  12731.   Legends help identify  individual data series.
  12732.  
  12733.  When displaying more than one data series on a chart, Presentation Graphics
  12734.  uses different colors, line styles, or patterns to differentiate the series.
  12735.  Presentation Graphics also can display a "legend" that labels the different
  12736.  series of a chart. For a pie chart, the legend labels individual slices of
  12737.  the pie.
  12738.  
  12739.  The format is similar to the legends found on printed graphs and maps. A
  12740.  sample of the color and pattern used to graph the series appears next to the
  12741.  series label. This identifies which set of data the labels belong to. The
  12742.  "Palettes" section later in this chapter explains how different data series
  12743.  are identified by color and pattern.
  12744.  
  12745.  
  12746.  Presentation Graphics Program Structure
  12747.  
  12748.  QuickC programs that use Presentation Graphics typically follow seven steps:
  12749.  
  12750.  
  12751.  Step                              Comments
  12752.  ────────────────────────────────────────────────────────────────────────────
  12753.  Include required header files.    Along with other header files your
  12754.                                    program may need, you must include the
  12755.                                    files GRAPH.H and PGCHART.H.
  12756.  
  12757.  Set video mode to graphics.       Refer to Chapter 13, "Graphics," for a
  12758.                                    discussion
  12759.                                    of video modes supported by QuickC. This
  12760.                                    chapter explains how to change modes
  12761.                                    within a QuickC program.
  12762.  
  12763.  Initialize Presentation Graphics  Presentation Graphics places charting
  12764.  chart                             parameters in a data structure. These
  12765.  environment.                      parameters determine how a graph will
  12766.                                    appear on the screen. Collectively they
  12767.                                    make up the "chart environment,"
  12768.                                    described in the section "Customizing
  12769.                                    Presentation Graphics."  Presentation
  12770.                                    Graphics sets the environment parameters
  12771.                                    to default values. The amount of
  12772.                                    initialization that must be done by your
  12773.                                    program depends on how extensively it
  12774.                                    relies on defaults.
  12775.  
  12776.  Assemble plot data.               Data can be collected in a variety of
  12777.                                    ways:  by calculating it elsewhere in
  12778.                                    the program, reading it from files, or
  12779.                                    entering it from the keyboard. All plot
  12780.                                    data
  12781.                                    must be assembled in arrays because the
  12782.                                    Presentation Graphics functions locate
  12783.                                    them through
  12784.                                    pointers.
  12785.  
  12786.  Call Presentation Graphics        Display your chart.
  12787.  functions.
  12788.  
  12789.  Pause while chart is on the       Your program should pause after a chart
  12790.  screen.                           is displayed. This step allows
  12791.                                    sufficient time to read the chart. A
  12792.                                    common method is to wait for a keyboard
  12793.                                    entry before resuming.
  12794.  
  12795.  Reset video mode.                 When your program detects the signal to
  12796.                                    continue,
  12797.                                    it should normally reset the video to
  12798.                                    its original
  12799.                                    mode.
  12800.  
  12801.  Once your program successfully compiles, you must link it to the library
  12802.  modules PGCHART.LIB and GRAPHICS.LIB. Use the Microsoft Overlay Linker
  12803.  
  12804.  QLINK.EXE or the QCL command-line interface to link programs outside the
  12805.  QuickC environment. For descriptions of QLINK and QCL, see the Microsoft
  12806.  QuickC Tool Kit, Chapter 1, "Creating Executable Programs."
  12807.  
  12808.  
  12809.  Five Example Chart Programs
  12810.  
  12811.  You'll have a better idea of Presentation Graphics capabilities once you've
  12812.  seen what it can do. To that end some simple examples are presented in this
  12813.  section. The sample programs that follow use only five of the 22
  12814.  Presentation Graphics functions: _pg_initchart, _pg_defaultchart,
  12815.  _pg_chartpie, _pg_chart, and _pg_chartscatter. Appendix B, "C Library
  12816.  Guide," and online help document these functions and their arguments. But
  12817.  the example code is straightforward, and you should be able to follow easily
  12818.  for now. Each program is commented so that you can recognize the seven steps
  12819.  given above.
  12820.  
  12821.  
  12822.  A Sample Data Set
  12823.  
  12824.  Suppose a grocer wants to graph the sales of orange juice over the course of
  12825.  a single year. Sales figures are on a monthly basis, so the grocer selects
  12826.  as category data the months of the year from January through December. The
  12827.  sales figures are shown below.
  12828.  
  12829. ╓┌─────────────────────────┌─────────────────────────────────────────────────╖
  12830.  Month                     Quantity (cases)
  12831.  ────────────────────────────────────────────────────────────────────────────
  12832.  January                   33
  12833.  Month                     Quantity (cases)
  12834.  ────────────────────────────────────────────────────────────────────────────
  12835.  January                   33
  12836.  February                  27
  12837.  March                     42
  12838.  April                     64
  12839.  May                       106
  12840.  June                      157
  12841.  July                      182
  12842.  August                    217
  12843.  September                 128
  12844.  October                   62
  12845.  November                  43
  12846.  December                  36
  12847.  ────────────────────────────────────────────────────────────────────────────
  12848.  
  12849.  
  12850.  
  12851.  Example: Pie Chart
  12852.  
  12853.  The following program uses Presentation Graphics to display a pie chart for
  12854.  the grocer's data. The chart, which is shown in Figure 14.2, remains on the
  12855.  screen until a key is pressed.
  12856.  
  12857.  The Presentation Graphics functions return values that identify error
  12858.  conditions. A return value of 0 indicates that the function has completed
  12859.  its work without error. Refer to the header file PGCHART.H and online help
  12860.  for descriptions of the nonzero error codes.
  12861.  
  12862.    /* PIE.C:  Create sample pie chart.  */
  12863.  
  12864.    #include <conio.h>
  12865.    #include <string.h>
  12866.    #include <graph.h>
  12867.    #include <pgchart.h>
  12868.  
  12869.    #define MONTHS 12
  12870.  
  12871.    typedef enum {FALSE, TRUE} boolean;
  12872.  
  12873.    float far value[MONTHS] =
  12874.    {
  12875.       33.0, 27.0, 42.0, 64.0,106.0,157.0,
  12876.      182.0,217.0,128.0, 62.0, 43.0, 36.0
  12877.    };
  12878.    char far *category[MONTHS] =
  12879.    {
  12880.      "Jan", "Feb", "Mar", "Apr",
  12881.      "May", "Jun", "Jly", "Aug",
  12882.      "Sep", "Oct", "Nov", "Dec"
  12883.    };
  12884.    short far explode[MONTHS] = {0};
  12885.  
  12886.    main()
  12887.    {
  12888.      chartenv env;
  12889.      int mode = _VRES16COLOR;
  12890.  
  12891.      /* Set highest video mode available */
  12892.      while(!_setvideomode( mode ))
  12893.         mode--;
  12894.      if(mode == _TEXTMONO)
  12895.         return( 0 );
  12896.  
  12897.      /* Initialize chart library and a default pie chart */
  12898.      _pg_initchart();
  12899.      _pg_defaultchart( &env, _PG_PIECHART, _PG_PERCENT );
  12900.  
  12901.      /* Add titles and some chart options */
  12902.      strcpy( env.maintitle.title, "Good Neighbor Grocery" );
  12903.      env.maintitle.titlecolor = 6;
  12904.      env.maintitle.justify = _PG_RIGHT;
  12905.      strcpy( env.subtitle.title, "Orange Juice Sales" );
  12906.      env.subtitle.titlecolor = 6;
  12907.      env.subtitle.justify = _PG_RIGHT;
  12908.      env.chartwindow.border = FALSE;
  12909.  
  12910.      /* Parameters for call to _pg_chartpie are:
  12911.       *
  12912.       *    env        - Environment variable
  12913.       *    category   - Category labels
  12914.       *    value      - Data to chart
  12915.       *    explode    - Separated pieces
  12916.       *    MONTHS     - Number of data values
  12917.       */
  12918.      if(_pg_chartpie( &env, category, value,
  12919.                        explode, MONTHS ))
  12920.      {
  12921.         _setvideomode( _DEFAULTMODE );
  12922.         _outtext( "Error:  can't draw chart" );
  12923.      }
  12924.      else
  12925.      {
  12926.         getch();
  12927.         _setvideomode( _DEFAULTMODE );
  12928.      }
  12929.      return( 0 );
  12930.    }
  12931.  
  12932.  (This figure may be found in the printed book.)
  12933.  
  12934.  
  12935.  Example: Bar Chart
  12936.  
  12937.  The code for the PIE.C program needs only minor alterations to produce bar,
  12938.  column, and line charts for the same data:
  12939.  
  12940.  
  12941.    ■   Replace the call to _pg_chartpie with _pg_chart. This function
  12942.        produces bar, column, and line charts depending on the value of the
  12943.        second argument for _pg_defaultchart.
  12944.  
  12945.    ■   Give new arguments to _pg_defaultchart that specify chart type and
  12946.        style.
  12947.  
  12948.    ■   Assign titles for the x axis and y axis in the structure  env .
  12949.  
  12950.    ■   Remove references to array  explode (applicable only to pie charts).
  12951.  
  12952.  
  12953.  The following example produces the bar chart shown in Figure 14.3.
  12954.  
  12955.    /* BAR.C:  Create sample bar chart. */
  12956.    #include <conio.h>
  12957.    #include <string.h>
  12958.    #include <graph.h>
  12959.    #include <pgchart.h>
  12960.    #define MONTHS 12
  12961.    typedef enum {FALSE, TRUE} boolean;
  12962.    float far value[MONTHS] =
  12963.    {
  12964.       33.0, 27.0, 42.0, 64.0,106.0,157.0,
  12965.      182.0,217.0,128.0, 62.0, 43.0, 36.0
  12966.    };
  12967.    char far *category[MONTHS] =
  12968.    {
  12969.      "Jan", "Feb", "Mar", "Apr",
  12970.      "May", "Jun", "Jly", "Aug",
  12971.      "Sep", "Oct", "Nov", "Dec"
  12972.    };
  12973.  
  12974.    main()
  12975.    {
  12976.      chartenv env;
  12977.      int mode = _VRES16COLOR;
  12978.      /* Set highest video mode available */
  12979.      while(!_setvideomode( mode ))
  12980.         mode--;
  12981.      if(mode == _TEXTMONO)
  12982.         return(0);
  12983.  
  12984.      /* Initialize chart library and a default bar chart */
  12985.      _pg_initchart();
  12986.      _pg_defaultchart( &env, _PG_BARCHART, _PG_PLAINBARS );
  12987.  
  12988.      /* Add titles and some chart options */
  12989.      strcpy( env.maintitle.title, "Good Neighbor Grocery" );
  12990.      env.maintitle.titlecolor = 6;
  12991.      env.maintitle.justify = _PG_RIGHT;
  12992.      strcpy( env.subtitle.title, "Orange Juice Sales" );
  12993.      env.subtitle.titlecolor = 6;
  12994.      env.subtitle.justify = _PG_RIGHT;
  12995.      strcpy( env.yaxis.axistitle.title, "Months" );
  12996.      strcpy( env.xaxis.axistitle.title, "Quantity (cases)" );
  12997.      env.chartwindow.border = FALSE;
  12998.  
  12999.      /* Parameters for call to _pg_chart are:
  13000.       *    env        - Environment variable
  13001.       *    category   - Category labels
  13002.       *    value      - Data to chart
  13003.       *    MONTHS     - Number of data values */
  13004.      if(_pg_chart( &env, category, value, MONTHS ))
  13005.      {
  13006.         _setvideomode( _DEFAULTMODE );
  13007.         _outtext( "Error:  can't draw chart" );
  13008.      }
  13009.      else
  13010.      {
  13011.          getch();
  13012.          _setvideomode( _DEFAULTMODE );
  13013.       }
  13014.       return(0);
  13015.    }
  13016.  
  13017.  (This figure may be found in the printed book.)
  13018.  
  13019.  
  13020.  Example: Column Chart
  13021.  
  13022.  The grocer's bar chart becomes a column chart in two easy steps. Simply
  13023.  specify the new chart type when calling _pg_defaultchart and switch the axis
  13024.  titles. To produce a column chart for the data, replace the call to
  13025.  _pg_defaultchart with:
  13026.  
  13027.    _pg_defaultchart( &env, _PG_COLUMNCHART, _PG_PLAINBARS );
  13028.  
  13029.  and replace the last two calls to strcpy with:
  13030.  
  13031.    strcpy( env.xaxis.axistitle.title, "Months" );
  13032.    strcpy( env.yaxis.axistitle.title, "Quantity (cases)" );
  13033.  
  13034.  Notice that now the x axis is labeled "Months" and the y axis is labeled
  13035.  "Quantity (cases)." Figure 14.4 shows the resulting column chart.
  13036.  
  13037.  (This figure may be found in the printed book.)
  13038.  
  13039.  
  13040.  Example: Line Chart
  13041.  
  13042.  Creating an equivalent line chart requires only one change. Use the same
  13043.  code as for the column chart and replace the call to _pg_defaultchart with:
  13044.  
  13045.  
  13046.    _pg_defaultchart( &env, _PG_LINECHART, _PG_POINTANDLINE );
  13047.  
  13048.  Figure 14.5 shows the line chart for the grocer's data.
  13049.  
  13050.  (This figure may be found in the printed book.)
  13051.  
  13052.  
  13053.  Example: Scatter Diagram
  13054.  
  13055.  Now suppose that the store owner wants to compare the sales of orange juice
  13056.  to the sales of another product, say hot chocolate. Possible monthly sales
  13057.  are shown below.
  13058.  
  13059. ╓┌───────────┌─────────────────────┌─────────────────────────────────────────╖
  13060.  Months      Orange Juice (cases)  Hot Chocolate (cases)
  13061.  ────────────────────────────────────────────────────────────────────────────
  13062.  January     33                    37
  13063.  February    27                    37
  13064.  Months      Orange Juice (cases)  Hot Chocolate (cases)
  13065.  ────────────────────────────────────────────────────────────────────────────
  13066. February    27                    37
  13067.  March       42                    30
  13068.  April       64                    19
  13069.  May         106                   10
  13070.  June        157                   5
  13071.  July        182                   2
  13072.  August      217                   1
  13073.  September   128                   7
  13074.  October     62                    15
  13075.  November    43                    28
  13076.  December    36                    39
  13077.  ────────────────────────────────────────────────────────────────────────────
  13078.  
  13079.  
  13080.  The program SCATTER.C displays a scatter diagram that illustrates the
  13081.  relationship between the sales of orange juice and hot chocolate throughout
  13082.  a 12-month period.
  13083.  
  13084.    /* SCATTER.C:  Create sample scatter diagram. */
  13085.  
  13086.    #include <conio.h>
  13087.    #include <string.h>
  13088.    #include <graph.h>
  13089.    #include <pgchart.h>
  13090.  
  13091.    #define MONTHS 12
  13092.    typedef enum {FALSE, TRUE} boolean;
  13093.  
  13094.    /* Orange juice sales */
  13095.  
  13096.    float far xvalue[MONTHS] =
  13097.    {
  13098.       33.0, 27.0, 42.0, 64.0,106.0,157.0,
  13099.      182.0,217.0,128.0, 62.0, 43.0, 36.0
  13100.    };
  13101.    /* Hot chocolate sales */
  13102.  
  13103.    float far yvalue[MONTHS] =
  13104.    {
  13105.      37.0, 37.0, 30.0, 19.0, 10.0,  5.0,
  13106.       2.0,  1.0,  7.0, 15.0, 28.0, 39.0
  13107.    };
  13108.  
  13109.    main()
  13110.    {
  13111.      chartenv env;
  13112.      int mode = _VRES16COLOR;
  13113.  
  13114.      /* Set highest video mode available */
  13115.  
  13116.      while(!_setvideomode( mode ))
  13117.         mode--;
  13118.      if(mode == _TEXTMONO)
  13119.         return(0);
  13120.  
  13121.      /* Initialize chart library and default
  13122.       * scatter diagram
  13123.       */
  13124.      _pg_initchart();
  13125.      _pg_defaultchart( &env, _PG_SCATTERCHART,
  13126.                        _PG_POINTONLY );
  13127.  
  13128.      /* Add titles and some chart options */
  13129.  
  13130.      strcpy( env.maintitle.title, "Good Neighbor Grocery" );
  13131.      env.maintitle.titlecolor = 6;
  13132.      env.maintitle.justify = _PG_RIGHT;
  13133.      strcpy( env.subtitle.title,
  13134.              "Orange Juice vs Hot Chocolate" );
  13135.      env.subtitle.titlecolor = 6;
  13136.      env.subtitle.justify = _PG_RIGHT;
  13137.      env.yaxis.grid = TRUE;
  13138.      strcpy( env.xaxis.axistitle.title,
  13139.              "Orange Juice Sales" );
  13140.      strcpy( env.yaxis.axistitle.title,
  13141.              "Hot Chocolate Sales" );
  13142.      env.chartwindow.border = FALSE;
  13143.  
  13144.      /* Parameters for call to _pg_chartscatter are:
  13145.       *    env        - Environment variable
  13146.       *    xvalue     - X-axis data
  13147.       *    yvalue     - Y-axis data
  13148.       *    MONTHS     - Number of data values
  13149.       */
  13150.  
  13151.      if(_pg_chartscatter( &env, xvalue,
  13152.                            yvalue, MONTHS ))
  13153.      {
  13154.         _setvideomode( _DEFAULTMODE );
  13155.         _outtext( "Error:  can't draw chart" );
  13156.      }
  13157.      else
  13158.      {
  13159.         getch();
  13160.         _setvideomode( _DEFAULTMODE );
  13161.      }
  13162.      return(0);
  13163.    }
  13164.  
  13165.  Figure 14.6 shows the results of SCATTER.C. Notice that the scatter points
  13166.  form a slightly curved line, indicating a correlation exists between the
  13167.  sales of the two products. The store owner can conclude from the scatter
  13168.  diagram that the demand for orange juice is roughly inverse to the demand
  13169.  for hot chocolate.
  13170.  
  13171.  (This figure may be found in the printed book.)
  13172.  
  13173.  
  13174.  Palettes
  13175.  
  13176.  Presentation Graphics displays each data series in a way that makes it
  13177.  discernible from other series. It does this by defining a separate "palette"
  13178.  for every data series in a chart. Palettes consist of entries that determine
  13179.  color, line style, fill pattern, and plot character used to graph the
  13180.  series.
  13181.  
  13182.  Presentation Graphics maintains its palettes as an array of structures. The
  13183.  header file PGCHART.H defines the palette structures as:
  13184.  
  13185.    /* Typedef for pattern bitmap */
  13186.    typedef unsigned char fillmap[8];
  13187.  
  13188.    /* Typedef for palette entry definition */
  13189.    typedef struct
  13190.    {
  13191.      unsigned short color;
  13192.      unsigned short style;
  13193.      fillmap        fill;
  13194.      char           plotchar;
  13195.    } paletteentry;
  13196.  
  13197.    /* Typedef for palette definition */
  13198.    typedef paletteentry palettetype[_PG_PALETTELEN];
  13199.  
  13200.  It's important not to confuse the Presentation Graphics palettes with the
  13201.  adapter display palettes, which are register values kept by the video
  13202.  controller. The function _selectpalette described in Chapter 13, "Graphics,"
  13203.  sets the display palette. It does not define the data series palettes used
  13204.  by Presentation Graphics.
  13205.  
  13206.  
  13207.  Color Pool
  13208.  
  13209.  Presentation Graphics organizes all chart colors into a "color pool." The
  13210.  color pool consists of pixel values valid for the current graphics mode.
  13211.  (Refer to Chapter 13, "Graphics," or the Glossary for a definition of pixel
  13212.  values.) Palette structures contain color codes that refer to the color
  13213.  pool. A palette's color code determines the color used to graph the data
  13214.  series associated with the palette. Colors of labels, titles, legends, and
  13215.  axes are also determined by the contents of the color pool.
  13216.  
  13217.  The first element of the color pool is always 0, which is the pixel value
  13218.  for the screen background color. The second element is always the highest
  13219.  pixel value available for the graphics mode. The remaining elements are
  13220.  repeating sequences of available pixel values, beginning with 1.
  13221.  
  13222.  As shown above, the first member of a palette data structure is:
  13223.  
  13224.    unsigned short color;
  13225.  
  13226.  This variable defines the color code for the data series associated with the
  13227.  palette. The color code is neither a display attribute nor a pixel value. It
  13228.  is an index number of the color pool.
  13229.  
  13230.  An example should make this clearer. A graphics mode of _MRES4COLOR  (320 x
  13231.  200 graphics) provides four colors for display. Pixel values from 0 to 3
  13232.  determine the possible pixel colors─say, black, green, red, and brown
  13233.  respectively. In this case the first 8 elements of the color pool would be
  13234.  the following:
  13235.  
  13236. ╓┌─────────────────┌────────────┌────────────────────────────────────────────╖
  13237.  Color Pool Index  Pixel Value  Color
  13238.  ────────────────────────────────────────────────────────────────────────────
  13239.  0                 0            Black
  13240.  1                 3            Brown
  13241.  2                 1            Green
  13242.  3                 2            Red
  13243.  4                 3            Brown
  13244.  5                 1            Green
  13245.  6                 2            Red
  13246.  7                 3            Brown
  13247.  ────────────────────────────────────────────────────────────────────────────
  13248.  
  13249.  
  13250.  Notice that the sequence of available foreground colors repeats from the
  13251.  third element. The first data series in this case would be plotted in brown,
  13252.  the second series in green, the third series in red, the fourth series again
  13253.  in brown, and so forth.
  13254.  
  13255.  Video adapters such as the EGA or the Hercules InColor(tm) Card allow 16
  13256.  on-screen colors. This allows Presentation Graphics to graph more series
  13257.  without duplicating colors.
  13258.  
  13259.  
  13260.  Style Pool
  13261.  
  13262.  Presentation Graphics matches the color pool with a collection of different
  13263.  line styles called the "style pool." Entries in the style pool define the
  13264.  appearance of lines such as axes and grids. Lines can be solid, dotted,
  13265.  dashed, or of some combination.
  13266.  
  13267.  The second member of a palette structure defines a style code as:
  13268.  
  13269.    unsigned short style;
  13270.  
  13271.  Each palette contains a style code that refers to an entry in the style pool
  13272.  in the same way that it contains a color code that refers to an entry in the
  13273.  color pool. The style code value in a palette is applicable only to line
  13274.  graphs and lined scatter diagrams. The style code determines the appearance
  13275.  of the lines drawn between points.
  13276.  
  13277.  The palette's style code adds further variety to the lines of a multiseries
  13278.  graph. It is most useful when the number of lines in a chart exceeds the
  13279.  number of available colors. For example, a graph of nine different data
  13280.  series must repeat colors if only three foreground colors are available for
  13281.  display. However, the style code for each color repetition will be
  13282.  different, ensuring that none of the lines looks the same.
  13283.  
  13284.  
  13285.  Pattern Pool
  13286.  
  13287.  Presentation Graphics also maintains a pool of "fill patterns." Patterns
  13288.  determine the fill design for column, bar, and pie charts. The third member
  13289.  of a palette structure holds the palette's fill pattern. The pattern member
  13290.  is an array:
  13291.  
  13292.    fillmap fill;
  13293.  
  13294.  where  fillmap  is type-defined as:
  13295.  
  13296.    typedef unsigned char fillmap[8];
  13297.  
  13298.  Each fill pattern array holds an 8 x 8 bit map that defines the fill pattern
  13299.  for the data series associated with the palette. Table 14.2 shows how a fill
  13300.  pattern of diagonal stripes is created with the  fill  pattern array.
  13301.  
  13302.  The bit map below corresponds to screen pixels. Each of the 8 layers of the
  13303.  map are binary numbers, where a solid circle signifies 1 and an open circle
  13304.  signifies 0. Thus the first layer of the map─that is, the first
  13305.  byte─represents the binary number 10011001, which is the decimal number 153.
  13306.  
  13307.  
  13308.  Table 14.2  Fill Patterns
  13309.  
  13310. ╓┌──────────────────────────────────┌────────────────────────────────────────╖
  13311.  Bit Map                            Value in fill
  13312.  ────────────────────────────────────────────────────────────────────────────
  13313.    ∙  ∙      ∙  ∙                fill[0] = 153
  13314.      ∙  ∙      ∙  ∙              fill[1] = 204
  13315.  ∙      ∙  ∙      ∙              fill[2] = 102
  13316.  Bit Map                            Value in fill
  13317.  ────────────────────────────────────────────────────────────────────────────
  13318. ∙      ∙  ∙      ∙              fill[2] = 102
  13319.  ∙  ∙      ∙  ∙                  fill[3] =   51
  13320.    ∙  ∙      ∙  ∙                fill[4] = 153
  13321.      ∙  ∙      ∙  ∙              fill[5] = 204
  13322.  ∙      ∙  ∙      ∙              fill[6] = 102
  13323.  ∙  ∙      ∙  ∙                  fill[7] =   51
  13324.  ────────────────────────────────────────────────────────────────────────────
  13325.  
  13326.  
  13327.  If you wish to create the above pattern for your chart's first data series,
  13328.  you must reset the  fill  array for the first palette structure. You can do
  13329.  this in five steps:
  13330.  
  13331.  
  13332.    1.  Declare a structure of type palettetype to hold the palette
  13333.        parameters.
  13334.  
  13335.    2.  Call _pg_initchart to initialize the palettes with default values.
  13336.  
  13337.    3.  Call the Presentation Graphics function _pg_getpalette to retrieve a
  13338.        copy of the current palette data.
  13339.  
  13340.    4.  Assign the values given in Table 14.2 to the array  fill  for the
  13341.        first palette.
  13342.  
  13343.    5.  Call the Presentation Graphics function _pg_setpalette to load the
  13344.        modified palette values.
  13345.  
  13346.  
  13347.  The following lines of code demonstrate these five steps:
  13348.  
  13349.    /* Declare a structure array for palette data. */
  13350.  
  13351.    palettetype palette_struct;
  13352.    .
  13353.    .
  13354.    .
  13355.    /* Initialize chart library */
  13356.  
  13357.    _pg_initchart();
  13358.    .
  13359.    .
  13360.    .
  13361.    /* Copy current palette data into palette_struct */
  13362.  
  13363.    _pg_getpalette( palette_struct );
  13364.  
  13365.    /* Reinitialize fill pattern for first palette using
  13366.       values in Table 14.2 */
  13367.  
  13368.    palette_struct[1].fill[0] = 153;
  13369.    palette_struct[1].fill[1] = 204;
  13370.    palette_struct[1].fill[2] = 102;
  13371.    palette_struct[1].fill[3] =  51;
  13372.    palette_struct[1].fill[4] = 153;
  13373.    palette_struct[1].fill[5] = 204;
  13374.    palette_struct[1].fill[6] = 102;
  13375.    palette_struct[1].fill[7] =  51;
  13376.  
  13377.    /* Load new palette data */
  13378.  
  13379.    _pg_setpalette( palette_struct );
  13380.  
  13381.  Now when you display your bar or column chart the first series appears
  13382.  filled with the striped pattern shown in Table 14.2.
  13383.  
  13384.  Pie charts are a bit different. The idea of multiple series does not really
  13385.  apply to them. Instead, palette structures correspond to individual slices.
  13386.  If the number of slices exceeds the constant _PG_PALETTELEN, palettes are
  13387.  recycled. Thus the first palette dictates not only the appearance of the
  13388.  first slice, but of slice number _PG_PALETTELEN as well. The second palette
  13389.  determines the appearance of both the second slice and of slice number
  13390.  _PG_PALETTELEN + 1, and so forth.
  13391.  
  13392.  
  13393.  Character Pool
  13394.  
  13395.  The last member of a palette structure is an index number in a pool of ASCII
  13396.  characters:
  13397.  
  13398.    char plotchar;
  13399.  
  13400.  The member plotchar  represents plot points on line graphs and scatter
  13401.  diagrams. Each palette uses a different character to distinguish plot points
  13402.  between data series.
  13403.  
  13404.  
  13405.  Customizing Presentation Graphics
  13406.  
  13407.  Presentation Graphics is built for flexibility. You can use its system of
  13408.  default values to produce professional-looking charts with a minimum of
  13409.  programming effort. Or you can fine-tune the appearance of your charts by
  13410.  overriding default values and initializing variables explicitly in your
  13411.  program. The following section shows you how.
  13412.  
  13413.  
  13414.  Chart Environment
  13415.  
  13416.  The header file PGCHART.H defines a structure type chartenv. This structure
  13417.  type organizes the set of variables known as the "chart environment." The
  13418.  chart environment describes everything about a chart except the plots
  13419.  themselves. It's the blank page, in other words, ready for plotting data.
  13420.  The environment determines the appearance of text, axes, grid lines, and
  13421.  legends.
  13422.  
  13423.  Calling the _pg_defaultchart function fills the chart environment with
  13424.  default values. Presentation Graphics allows you to reset any variable in
  13425.  the environment before displaying a chart. Except for adjusting the palette
  13426.  values, all initialization of data is done through a chartenv type
  13427.  structure.
  13428.  
  13429.  The sample chart programs provided earlier illustrate how to adjust
  13430.  variables in the chart environment. These programs create a structure  env
  13431.  of the type chartenv. The structure  env  contains the chart environment
  13432.  variables, initialized by the call to _pg_defaultchart. Environment
  13433.  variables such as the chart title are then given specific values, as in:
  13434.  
  13435.    strcpy( env.maintitle.title, "Good Neighbor Grocery" );
  13436.  
  13437.  Environment variables that determine colors and line styles deserve special
  13438.  mention. The chart environment holds several such variables, which can be
  13439.  recognized by their names. For example, the variable titlecolor specifies
  13440.  the color of title text. Similarly, the variable gridstyle specifies the
  13441.  line style used to draw the chart grid.
  13442.  
  13443.   Colors and line styles in the chart environment are taken from palettes.
  13444.  
  13445.  These variables are index numbers, but do not refer directly to the color
  13446.  pool or line pool. They correspond instead to palette numbers. If you set
  13447.  titlecolor to 2, Presentation Graphics uses the color code in the second
  13448.  palette to determine the title's color. Thus the title in this case would be
  13449.  the same color as the chart's second data series. If you change the color
  13450.  code in the palette, you'll also change the title's color.
  13451.  
  13452.  A structure of type chartenv consists of four secondary structures. The file
  13453.  PGCHART.H type-defines the secondary structures as:
  13454.  
  13455.    titletype
  13456.    axistype
  13457.    windowtype
  13458.    legendtype
  13459.  
  13460.  The remainder of this section describes the chart environment of
  13461.  Presentation Graphics. It first examines structures of the four secondary
  13462.  types that make up the chart environment structure. The section concludes
  13463.  with a description of the chartenv structure type. Each discussion begins
  13464.  with a brief explanation of the structure's purpose, followed by a listing
  13465.  of the structure type definition as it appears in the PGCHART.H file. All
  13466.  symbolic constants are defined in the file PGCHART.H.
  13467.  
  13468.  
  13469.  titletype
  13470.  
  13471.  Structures of type titletype determine text, color, and placement of titles
  13472.  appearing in the graph. The PGCHART.H file defines the structure type as:
  13473.  
  13474.    typedef struct
  13475.    {
  13476.      char     title[_PG_TITLELEN];  /* Title text */
  13477.      short    titlecolor;           /* Palette color
  13478.                                        for title text */
  13479.      short    justify;              /* _PG_LEFT, _PG_CENTER,
  13480.                                        _PG_RIGHT */
  13481.    } titletype;
  13482.  
  13483.  The following list describes titletype members:
  13484.  
  13485.  Member Variable                   Description
  13486.  ────────────────────────────────────────────────────────────────────────────
  13487.  justify                           An integer specifying how the title is
  13488.                                    justified
  13489.                                    within the chart window. The symbolic
  13490.                                    constants
  13491.                                    defined in the PGCHART.H file for this
  13492.                                    variable are _PG_LEFT, _PG_CENTER, and
  13493.                                    _PG_RIGHT.
  13494.  
  13495.  titlecolor                        An integer between 1 and _PG_PALETTELEN
  13496.                                    that specifies a title's color. The
  13497.                                    default value for titlecolor is 1.
  13498.  
  13499.  title[_PG_TITLELEN]               A character array containing title text.
  13500.                                    For example, if  env  is a structure of
  13501.                                    type chartenv, then  env.maintitle.title
  13502.                                    holds the character string used for the
  13503.                                    main title of the chart. Similarly,
  13504.                                    env.xaxis.axistitle.title  contains the
  13505.                                    axis title. The number of characters in
  13506.                                    a title must be one less than
  13507.                                    _PG_TITLELEN to allow room for a null
  13508.                                    terminator.
  13509.  
  13510.  
  13511.  axistype
  13512.  
  13513.  Structures of type axistype contain variables for the axes such as color,
  13514.  scale, grid style, and tick marks. The PGCHART.H file defines the structure
  13515.  type as:
  13516.  
  13517.    typedef struct
  13518.    {
  13519.      short       grid;          /* TRUE=grid lines drawn;
  13520.                                    FALSE=no lines */
  13521.      short       gridstyle;     /* Style bytes for grid */
  13522.      titletype   axistitle;     /* Title definition
  13523.                                    for axis */
  13524.      short       axiscolor;     /* Color for axis */
  13525.      short       labeled;       /* TRUE=ticks marks and titles
  13526.                                    drawn */
  13527.      short       rangetype;     /* _PG_LINEARAXIS,
  13528.                                    _PG_LOGAXIS */
  13529.      float       logbase;       /* Base used if log axis */
  13530.      short       autoscale;     /* TRUE=next 7 values
  13531.                                    calculated by system */
  13532.      float       scalemin;      /* Minimum value of scale */
  13533.      float       scalemax;      /* Maximum value of scale */
  13534.      float       scalefactor;   /* Scale factor for data on
  13535.                                    this axis */
  13536.      titletype   scaletitle;    /* Title definition for
  13537.                                    scaling factor */
  13538.      float       ticinterval;   /* Distance between tick marks
  13539.                                    (world coord.) */
  13540.      short       ticformat;     /* _PG_EXPFORMAT or
  13541.                                    _PG_DECFORMAT */
  13542.      short       ticdecimals;   /* Number of decimals for tick
  13543.                                    labels (max=9) */
  13544.    } axistype;
  13545.  
  13546.  The following list describes axistype member variables:
  13547.  
  13548.  Member Variable                   Description
  13549.  ────────────────────────────────────────────────────────────────────────────
  13550.  autoscale                         A boolean variable. If autoscale is TRUE,
  13551.                                    Presentation Graphics automatically
  13552.                                    determines values
  13553.                                    for  scalefactor, scalemax, scalemin,
  13554.                                    scaletitle, ticdecimals, ticformat, and
  13555.                                    ticinterval (see below).
  13556.                                    If autoscale equals FALSE, these seven
  13557.                                    variables must be specified in your
  13558.                                    program.
  13559.  
  13560.  axiscolor                         An integer between 1 and _PG_PALETTELEN
  13561.                                    that specifies the color used for the
  13562.                                    axis and parallel grid lines. (See
  13563.                                    description for gridstyle above.) Note
  13564.                                    that this member does not determine the
  13565.                                    color of the axis title. That selection
  13566.                                    is made through the structure
  13567.                                    axistitle.
  13568.  
  13569.  axistitle                         A titletype structure that defines the
  13570.                                    title of the associated axis. The title
  13571.                                    of the y axis displays vertically to the
  13572.                                    left of the y axis, and the title of the
  13573.                                    x axis displays horizontally below the x
  13574.                                    axis.
  13575.  
  13576.  grid                              A boolean true/false value that
  13577.                                    determines whether grid lines are drawn
  13578.                                    for the associated axis. Grid lines span
  13579.                                    the data window perpendicular to the
  13580.                                    axis.
  13581.  
  13582.  gridstyle                         An integer between 1 and _PG_PALETTELEN
  13583.                                    that specifies the grid's line style.
  13584.                                    Lines can be solid, dashed, dotted, or
  13585.                                    some combination. The default value for
  13586.                                    gridstyle is 1. Note that the color of
  13587.                                    the parallel axis determines the color
  13588.                                    of the grid lines. Thus the x axis grid
  13589.                                    is the same color as the y axis, and the
  13590.                                    y axis grid is the same color as the x
  13591.                                    axis.
  13592.  
  13593.  labeled                           A boolean value that determines whether
  13594.                                    tick marks and labels are drawn on the
  13595.                                    axis. Axis labels should not be confused
  13596.                                    with axis titles. Axis labels are
  13597.                                    numbers or descriptions such as "23.2"
  13598.                                    or "January" attached to each tick mark.
  13599.  
  13600.  logbase                           If rangetype is logarithmic, the logbase
  13601.                                    variable determines the log base used to
  13602.                                    scale the axis. Default value is 10.
  13603.  
  13604.  rangetype                         An integer that determines whether the
  13605.                                    scale of the axis is linear or
  13606.                                    logarithmic. The rangetype variable
  13607.                                    applies only to value data.
  13608.  
  13609.                                    Specify a linear scale with the
  13610.                                    _PG_LINEARAXIS constant. A linear scale
  13611.                                    is best when the difference between axis
  13612.                                    minimum and maximum is relatively small.
  13613.                                    For example, a linear axis range 0-10
  13614.                                    results in 10 tick marks evenly spaced
  13615.                                    along the axis.
  13616.  
  13617.                                    Use _PG_LOGAXIS to specify a logarithmic
  13618.                                    rangetype. Logarithmic scales are useful
  13619.                                    when the range is very large or when the
  13620.                                    data varies exponentially. Line graphs
  13621.                                    of exponentially varying data can be
  13622.                                    made straight with a logarithmic
  13623.                                    rangetype.
  13624.  
  13625.  scalefactor                       All numeric data are scaled by dividing
  13626.                                    each value by scalefactor. For
  13627.                                    relatively small values, the variable
  13628.                                    scalefactor should be 1, which is the
  13629.                                    default.
  13630.                                    But data with large values should be
  13631.                                    scaled by an
  13632.                                    appropriate factor. For example, data in
  13633.                                    the range
  13634.                                    2 million-20 million should be plotted
  13635.                                    with scale-min set to 2, scalemax set to
  13636.                                    20, and scalefactor set to 1 million.
  13637.  
  13638.                                    If autoscale is set to TRUE,
  13639.                                    Presentation Graphics automatically
  13640.                                    determines a suitable value for
  13641.                                    scalefactor based on the range of data
  13642.                                    to be plotted. Presentation Graphics
  13643.                                    selects only values that are
  13644.                                    a factor of 1 thousand─that is, values
  13645.                                    such as 1
  13646.                                    thousand, 1 million, or 1 billion. It
  13647.                                    then labels the scaletitle appropriately
  13648.                                    (see below). If you desire some other
  13649.                                    value for scaling, you must set
  13650.                                    autoscale to FALSE and set scalefactor
  13651.                                    to the desired scaling value.
  13652.  
  13653.  scalemax                          Highest value represented by the axis.
  13654.  
  13655.  scalemin                          Lowest value represented by the axis.
  13656.  
  13657.  scaletitle                        A titletype structure defining a string
  13658.                                    of text that
  13659.                                    describes the value of scalefactor. If
  13660.                                    autoscale is TRUE, Presentation Graphics
  13661.                                    automatically writes
  13662.                                    a scale description to scaletitle. If
  13663.                                    autoscale equals FALSE and scalefactor
  13664.                                    is 1, scaletitle.title should be blank.
  13665.                                    Otherwise your program should copy an
  13666.                                    appropriate scale description to
  13667.                                    scaletitle.title, such as "( x 1000),"
  13668.                                    "(in millions of units)," "times 10
  13669.                                    thousand dollars," etc.
  13670.  
  13671.                                    For the y axis, the scaletitle text
  13672.                                    displays vertically between the axis
  13673.                                    title and the y axis. For the x axis,
  13674.                                    the scale title appears below the x axis
  13675.                                    title.
  13676.  
  13677.  ticdecimals                       Number of digits to display after the
  13678.                                    decimal point in tick labels. Maximum
  13679.                                    value is 9. Note that this variable
  13680.                                    applies only to axes with value data. It
  13681.                                    is
  13682.                                    ignored for the category axis.
  13683.  
  13684.  ticformat                         An integer that determines the format of
  13685.                                    the labels assigned to each tick mark.
  13686.                                    Set ticformat to _PG_EXPFORMAT for
  13687.                                    exponential format or set it to
  13688.                                    _PG_DECFORMAT for decimal. The default
  13689.                                    is _PG_DECFORMAT. Note that this
  13690.                                    variable applies only to axes with value
  13691.                                    data. It is ignored for the category
  13692.                                    axis.
  13693.  
  13694.  ticinterval                       Sets interval between tick marks on the
  13695.                                    axis. The tick interval is measured in
  13696.                                    the same units as the numeric data
  13697.                                    associated with the axis. For example,
  13698.                                    if 2 sequential tick marks correspond to
  13699.                                    the values 20 and 25, the tick interval
  13700.                                    between them is 5. Note that this
  13701.                                    variable applies only to axes with value
  13702.                                    data. It is ignored for the category
  13703.                                    axis.
  13704.  
  13705.  
  13706.  windowtype
  13707.  
  13708.  Structures of type windowtype contain sizes, locations, and color codes for
  13709.  the three windows produced by Presentation Graphics: the chart window, the
  13710.  data window, and the legend. Refer to the "Terminology" section at the
  13711.  beginning of this chapter for definitions of these terms. Windows are
  13712.  located on the screen relative to the screen's logical origin. By changing
  13713.  the logical origin, you can display charts that are partly or completely off
  13714.  the screen. The PGCHART.H file defines windowtype as:
  13715.  
  13716.    typedef struct
  13717.    {
  13718.      short  x1;            /* Left edge of window in
  13719.                               pixels */
  13720.      short  y1;            /* Top edge of window in
  13721.                               pixels */
  13722.      short  x2;            /* Right edge of window in
  13723.                               pixels */
  13724.      short  y2;            /* Bottom edge of window in
  13725.                               pixels */
  13726.      short  border;        /* TRUE for border, FALSE
  13727.                               otherwise */
  13728.      short  background;    /* Internal palette color for
  13729.                               window background */
  13730.      short  borderstyle;   /* Style bytes for window
  13731.                               border */
  13732.      short  bordercolor;   /* Internal palette color for
  13733.                               window border */
  13734.    } windowtype;
  13735.  
  13736.  The following list describes windowtype member variables:
  13737.  
  13738.  Member Variable                   Description
  13739.  ────────────────────────────────────────────────────────────────────────────
  13740.  x1, y1, x2, y2                    Window coordinates in pixels. The
  13741.                                    ordered pair (x1, y1) specifies the
  13742.                                    coordinate of the upper left corner of
  13743.                                    the window. The ordered pair (x2, y2)
  13744.                                    specifies the coordinate of the lower
  13745.                                    right corner.
  13746.  
  13747.                                    The reference point for the coordinates
  13748.                                    depends on the type of window. The chart
  13749.                                    window is located relative to the
  13750.                                    logical origin, usually the upper left
  13751.                                    corner of the screen. The data and
  13752.                                    legend windows are located relative to
  13753.                                    the upper left corner of the chart
  13754.                                    window. This allows you to change the
  13755.                                    position of the chart window without
  13756.                                    having to redefine coordinates for the
  13757.                                    other two windows.
  13758.  
  13759.  background                        An integer between 1 and _PG_PALETTELEN
  13760.                                    that specifies the window's background
  13761.                                    color. The default value for background
  13762.                                    is 1.
  13763.  
  13764.  border                            A boolean variable that determines
  13765.                                    whether a border frame is drawn around a
  13766.                                    window.
  13767.  
  13768.  bordercolor                       An integer between 1 and _PG_PALETTELEN
  13769.                                    that specifies the color of the window's
  13770.                                    border frame. The default value is 1.
  13771.  
  13772.  borderstyle                       An integer between 1 and _PG_PALETTELEN
  13773.                                    that specifies the line style of the
  13774.                                    window's border frame. The default value
  13775.                                    is 1.
  13776.  
  13777.  
  13778.  legendtype
  13779.  
  13780.  Structures of type legendtype contain size, location, and colors of the
  13781.  chart legend. The PGCHART.H file defines the structure type as:
  13782.  
  13783.    typedef struct
  13784.    {
  13785.      short      legend;        /* TRUE=draw legend;
  13786.                                   FALSE=no legend */
  13787.      short      place;         /* _PG_RIGHT, _PG_BOTTOM,
  13788.                                   _PG_OVERLAY */
  13789.      short      textcolor;     /* Palette color for text*/
  13790.      short      autosize;      /* TRUE=system calculates
  13791.                                   legend size */
  13792.      windowtypelegendwindow;  /* Window definition for
  13793.                                   legend */
  13794.    } legendtype;
  13795.  
  13796.  The following list describes legendtype member variables:
  13797.  
  13798.  Member Variable                   Description
  13799.  ────────────────────────────────────────────────────────────────────────────
  13800.  autosize                          A boolean true/false variable that
  13801.                                    determines whether Presentation Graphics
  13802.                                    is to automatically calculate the size
  13803.                                    of the legend. If autosize equals FALSE,
  13804.                                    the legend window must be specified in
  13805.                                    the legendwindow structure (see below).
  13806.  
  13807.  legend                            A boolean true/false variable that
  13808.                                    determines whether a legend is to appear
  13809.                                    on the chart. The legend variable is
  13810.                                    ignored by functions that graph
  13811.                                    single-series charts.
  13812.  
  13813.  legendwindow                      A windowtype structure that defines
  13814.                                    coordinates, background color, and
  13815.                                    border frame for the legend. Coordinates
  13816.                                    given in legendwindow are ignored if
  13817.                                    autosize is TRUE.
  13818.  
  13819.  place                             An integer that specifies the location
  13820.                                    of the legend relative to the data
  13821.                                    window. Setting the variable place equal
  13822.                                    to the constant _PG_RIGHT positions the
  13823.                                    legend to the right of the data window.
  13824.                                    Setting place to _PG_BOTTOM positions
  13825.                                    the legend below the data window.
  13826.                                    Setting place to _PG_OVERLAY positions
  13827.                                    the legend within the data window.
  13828.  
  13829.                                    These settings influence the size of the
  13830.                                    data
  13831.                                    window. If place is equal to _PG_BOTTOM
  13832.                                    or _PG_RIGHT, Presentation Graphics
  13833.                                    automatically sizes the data window to
  13834.                                    accommodate the legend.
  13835.                                    If place equals _PG_OVERLAY the data
  13836.                                    window is sized without regard to the
  13837.                                    legend.
  13838.  
  13839.  textcolor                         An integer between 1 and _PG_PALETTELEN
  13840.                                    that specifies the color of text within
  13841.                                    the legend window.
  13842.  
  13843.  
  13844.  chartenv
  13845.  
  13846.  A structure of type chartenv defines the chart environment. The following
  13847.  code shows that a chartenv type structure consists almost entirely of
  13848.  structures of the four types discussed above.
  13849.  
  13850.  The PGCHART.H file defines the chartenv structure type as:
  13851.  
  13852.    typedef struct
  13853.    {
  13854.      short       charttype;     /* Chart type */
  13855.      short       chartstyle;    /* Chart style */
  13856.      windowtype  chartwindow;   /* Window definition for
  13857.                                    overall chart */
  13858.      windowtype  datawindow;    /* Window definition for data
  13859.                                    part of chart */
  13860.      titletype   maintitle;     /* Main chart title */
  13861.      titletype   subtitle;      /* Chart subtitle */
  13862.      axistype    xaxis;         /* Definition for x axis */
  13863.      axistype    yaxis;         /* Definition for y axis */
  13864.      legendtype  legend;        /* Definition for legend */
  13865.    } chartenv;
  13866.  
  13867.   Initialize the chart  environment with the _pg_defaultchart function.
  13868.  
  13869.  Note that all the data in a chartenv type structure is initialized by
  13870.  calling the _pg_defaultchart function. If your program does not call
  13871.  _pg_defaultchart, it must explicitly define every variable in the chart
  13872.  environment─a tedious and unnecessary procedure. The recommended method for
  13873.  adjusting the appearance of your chart is to initialize variables for the
  13874.  proper chart type by calling the _pg_defaultchart function, and then
  13875.  reassign selected environment variables such as titles.
  13876.  
  13877.  The following list describes chartenv member variables:
  13878.  
  13879.  Member Variable                   Description
  13880.  ────────────────────────────────────────────────────────────────────────────
  13881.  chartstyle                        An integer that determines the style of
  13882.                                    the chart
  13883.                                    (see Table 14.1). Legal values for
  13884.                                    chartstyle
  13885.                                    are _PG_PERCENT and _PG_NOPERCENT
  13886.                                    for pie charts; _PG_STACKEDBARS and
  13887.                                    _PG_PLAINBARS for bar and column charts;
  13888.                                    and _PG_POINTANDLINE and _PG_POINTONLY
  13889.                                    for line graphs and scatter diagrams.
  13890.                                    This variable corresponds to the third
  13891.                                    argument for the _pg_defaultchart
  13892.                                    function.
  13893.  
  13894.  charttype                         An integer that determines the type of
  13895.                                    chart displayed. The value of the
  13896.                                    variable charttype is  _PG_BARCHART,
  13897.                                    _PG_COLUMNCHART, _PG_LINECHART,
  13898.                                    _PG_SCATTERCHART, or _PG_PIECHART. This
  13899.                                    variable corresponds to the second
  13900.                                    argument for the _pg_defaultchart
  13901.                                    function.
  13902.  
  13903.  chartwindow                       A windowtype structure that defines the
  13904.                                    appearance of the chart window.
  13905.  
  13906.  datawindow                        A windowtype structure that defines the
  13907.                                    appearance of the data window.
  13908.  
  13909.  legend                            A legendtype structure that defines the
  13910.                                    appearance of the legend window.
  13911.  
  13912.  maintitle                         A titletype structure that defines the
  13913.                                    appearance of the main title of the
  13914.                                    chart.
  13915.  
  13916.  subtitle                          A titletype structure that defines the
  13917.                                    appearance of the chart's subtitle.
  13918.  
  13919.  xaxis                             An axistype structure that defines the
  13920.                                    appearance of the x axis. (This variable
  13921.                                    is not applicable for pie charts.)
  13922.  
  13923.  yaxis                             An axistype structure that defines the
  13924.                                    appearance of the y axis. (This variable
  13925.                                    is not applicable for pie charts.)
  13926.  
  13927.  
  13928.  An Overview of the Presentation Graphics Functions
  13929.  
  13930.  The chapter concludes with a few words about the 22 functions that make up
  13931.  the Presentation Graphics library. They are listed in Table 14.3 for
  13932.  convenient reference. Refer to Appendix B, "C Library Guide," or online help
  13933.  for a description of the functions and their arguments.
  13934.  
  13935.  Table 14.3  Presentation Graphics Functions
  13936.  
  13937. ╓┌────────────────────┌─────────────────────┌────────────────────────────────╖
  13938.  Primary Functions    Secondary Functions
  13939.  ────────────────────────────────────────────────────────────────────────────
  13940.  _pg_initchart        _pg_hlabelchart       _pg_setpalette
  13941.  _pg_defaultchart     _pg_vlabelchart       _pg_resetpalette
  13942.  _pg_chart            _pg_analyzechart      _pg_getstyleset
  13943.  _pg_chartms          _pg_analyzechartms    _pg_setstyleset
  13944.  _pg_chartscatter     _pg_analyzescatter    _pg_resetstyleset
  13945.  _pg_chartscatterms   _pg_analyzescatterms  _pg_getchardef
  13946.  Primary Functions    Secondary Functions
  13947.  ────────────────────────────────────────────────────────────────────────────
  13948. _pg_chartscatterms   _pg_analyzescatterms  _pg_getchardef
  13949.  _pg_chartpie         _pg_analyzepie        _pg_setchardef
  13950.                       _pg_getpalette
  13951.  ────────────────────────────────────────────────────────────────────────────
  13952.  
  13953.  
  13954.  In most cases you need only be concerned with seven of the routines, called
  13955.  the "primary functions." These functions initialize variables and display
  13956.  the selected chart types. As demonstrated in example programs earlier in
  13957.  this chapter, you can create very acceptable charts with programs that call
  13958.  only three of the Presentation Graphics primary functions.
  13959.  
  13960.  The 15 secondary functions of Presentation Graphics do not directly display
  13961.  charts. Most of them retrieve or set data in the Presentation Graphics chart
  13962.  environment.
  13963.  
  13964.  Of special interest among the secondary functions are the "analysis
  13965.  functions," identified by the prefix _pg_analyze in their function names.
  13966.  These five functions calculate default values that pertain to a given chart
  13967.  type and data set. Calling an analysis function has the same effect as
  13968.  calling a corresponding primary function, except that the chart is not
  13969.  displayed. This allows you to pass on to the library the burden of
  13970.  calculating values. You can then make modifications  to the resulting values
  13971.  and call a primary routine to display the chart.
  13972.  
  13973.  Use the _pg_hlabelchart and _pg_vlabelchart functions to display text on
  13974.  your chart that is not part of a title or axis label. These functions enable
  13975.  you to attach notes or other messages to your chart. You may also find them
  13976.  useful for labeling separate lines of a multiseries line graph.
  13977.  
  13978.  
  13979.  
  13980.  
  13981.  
  13982.  
  13983.  Chapter 15  Fonts
  13984.  ────────────────────────────────────────────────────────────────────────────
  13985.  
  13986.  Preceding chapters have discussed how to write QuickC programs that generate
  13987.  graphics and display charts. QuickC has yet another capability when it comes
  13988.  to graphics: fonted text. Your programs can display various styles and sizes
  13989.  of text in any graphics image or chart.
  13990.  
  13991.  This chapter tells how. It assumes you have already read Chapter 13,
  13992.  "Graphics." You should understand such terms as "graphics mode" and "text
  13993.  mode," and be familiar with the functions _setvideomode and _moveto. Other
  13994.  than that, there's very little to it. Fonts are simple to learn and even
  13995.  simpler to use, yet they can add to your graphics a final touch of polish.
  13996.  
  13997.  
  13998.  QuickC Fonts
  13999.  
  14000.  A "font" is a collection of stylized text characters. Each font consists of
  14001.  several type sizes and a typeface.
  14002.  
  14003.  "Typeface" is a printer's term that refers to the style of the displayed
  14004.  text─ Courier, for example, or Roman. The list on the following page shows
  14005.  six of the typefaces available with QuickC's font library.
  14006.  
  14007.  "Type size" measures the screen area occupied by individual characters. This
  14008.  term is also borrowed from the printer's lexicon, but for our purposes is
  14009.  specified in units of screen pixels. For example, "Courier 16 x 9" denotes
  14010.  text of Courier typeface, with each character occupying a screen area of 16
  14011.  vertical pixels by 9 horizontal pixels.
  14012.  
  14013.  QuickC's font functions use two methods to create fonts. The first technique
  14014.  generates Courier, Helv, and Tms Rmn fonts through a "bit-mapping" (or
  14015.  "raster-mapping") technique. Bit-mapping defines character images with
  14016.  binary data. Each bit in the map corresponds to a screen pixel. If a bit is
  14017.  1, its associated pixel is set to the current screen color. A bit value of 0
  14018.  clears the pixel. Video adapters use this same technique to display text in
  14019.  graphics mode.
  14020.  
  14021.  The second method creates the remaining three type styles─Modern, Script,
  14022.  and Roman─as "vector-mapped" fonts. Vector-mapping represents each character
  14023.  in terms of lines and arcs. In a literal sense vector-mapped characters are
  14024.  drawn on the screen. You might think of bit-mapped characters as being
  14025.  stenciled.
  14026.  
  14027.  Each method has advantages and disadvantages. Bit-mapped characters are more
  14028.  completely formed since the pixel mapping is predetermined. However, they
  14029.  cannot be scaled. Vector-mapped text can be scaled to any size, but the
  14030.  characters tend to lack the solid appearance of the bit-mapped characters.
  14031.  
  14032.  (This figure may be found in the printed book.)
  14033.  
  14034.  Table 15.1 lists available sizes for each font. Notice that the bit-mapped
  14035.  fonts come in preset sizes as measured in pixels. The exact size of any
  14036.  fonted character depends on screen resolution and display type.
  14037.  
  14038.  Table 15.1  Typefaces and Type Sizes in the QuickC Library
  14039.  
  14040. ╓┌─────────┌────────┌─────────────────────────┌──────────────────────────────╖
  14041.  Typeface  Mapping  Size (in pixels)          Spacing
  14042.  ────────────────────────────────────────────────────────────────────────────
  14043.  Courier   Bit      13 x 8, 16 x 9,           Fixed
  14044.                     20 x 12
  14045.  
  14046.  Helv      Bit      13 x 5, 16 x 7, 20 x 8,   Fixed
  14047.                     13 x 15, 16 x 6, 19 x 8
  14048.  
  14049.  Tms Rmn   Bit      10 x 5, 12 x 6, 15 x 8,   Fixed
  14050.                     16 x 9, 20 x 12, 26 x 16
  14051.  Typeface  Mapping  Size (in pixels)          Spacing
  14052.  ────────────────────────────────────────────────────────────────────────────
  14053.                    16 x 9, 20 x 12, 26 x 16
  14054.  
  14055.  Modern    Vector   Scaled                    Proportional
  14056.  
  14057.  Script    Vector   Scaled                    Proportional
  14058.  
  14059.  Roman     Vector   Scaled                    Proportional
  14060.  
  14061.  ────────────────────────────────────────────────────────────────────────────
  14062.  
  14063.  
  14064.  
  14065.  QuickC's font routines can display characters 32-255, including most
  14066.  extended characters (ASCII 128-255). A few extended characters cannot be
  14067.  displayed; these are represented as either an underscore (_) or period (.)
  14068.  character.
  14069.  
  14070.  
  14071.  Using QuickC's Font Library
  14072.  
  14073.  Data for both bit-mapped and vector-mapped fonts reside in files on disk. A
  14074.  .FON extension identifies the files. The names of the .FON files indicate
  14075.  their content. For example, the files MODERN.FON, ROMAN.FON, and SCRIPT.FON
  14076.  hold data for the three vector-mapped fonts.
  14077.  
  14078.   You can use Microsoft Windows .FON files.
  14079.  
  14080.  QuickC .FON files are identical to the .FON files used in the Microsoft
  14081.  Windows operating environment. If you have access to Windows you can use any
  14082.  of its .FON files with QuickC's font functions. Windows .FON files are also
  14083.  available for purchase separately. In addition, several vendors offer
  14084.  software that can create or modify .FON files, allowing you to design your
  14085.  own fonts.
  14086.  
  14087.  Your programs should follow these three steps to display fonted text:
  14088.  
  14089.  
  14090.    1.  Register fonts
  14091.  
  14092.    2.  Set the current font from the register
  14093.  
  14094.    3.  Display text using the current font
  14095.  
  14096.  
  14097.  The following sections describe each of the three steps in detail. An
  14098.  example program later in the chapter demonstrates the steps.
  14099.  
  14100.  
  14101.  Register Fonts
  14102.  
  14103.  The fonts you plan to use must first be organized into a list in memory, a
  14104.  process called "registering." The register list contains information about
  14105.  the available .FON files. Register fonts by calling the function
  14106.  _registerfonts. This function reads header information from specified .FON
  14107.  files. It builds a list of file information but does not read mapping data
  14108.  from the files.
  14109.  
  14110.  The GRAPH.H file prototypes the _registerfonts function as:
  14111.  
  14112.    short far _registerfonts( unsigned char far * );
  14113.  
  14114.  The argument points to a string containing a file name. The file name is the
  14115.  name of the .FON file for the desired font. The file name can include wild
  14116.  cards, allowing you to register several fonts with one call to
  14117.  _registerfonts.
  14118.  
  14119.  If it successfully reads one or more .FON files, _registerfonts returns the
  14120.  number of fonts registered. If the function fails, it returns a negative
  14121.  error code. Refer to Appendix B, "C Library Guide," or to online help for a
  14122.  description of error codes.
  14123.  
  14124.  
  14125.  Set Current Font
  14126.  
  14127.  Call the function _setfont to select a current font. This function checks to
  14128.  see if the requested font is registered, then reads the mapping data from
  14129.  the appropriate .FON file. A font must be registered and marked current
  14130.  before your program can display text of that font.
  14131.  
  14132.  The GRAPH.H file prototypes _setfonts as
  14133.  
  14134.    short far _setfont( unsigned char far * );
  14135.  
  14136.  The function's argument is a pointer to a character string. The string
  14137.  consists of letter codes that describe the desired font, as outlined below:
  14138.  
  14139.  
  14140.  Option Code                       Meaning
  14141.  ────────────────────────────────────────────────────────────────────────────
  14142.  b                                 Select the best fit from the registered
  14143.                                    fonts. This option instructs _setfont to
  14144.                                    accept the closest-fitting font if a
  14145.                                    font of the specified size is not
  14146.                                    registered.
  14147.  
  14148.                                    If at least one font is registered, the
  14149.                                    b option always sets a current font. If
  14150.                                    you do not specify the b option and an
  14151.                                    exact matching font is not registered,
  14152.                                    _setfont will fail. In this case, any
  14153.                                    existing current font remains current.
  14154.                                    Refer to online help for a description
  14155.                                    of error codes returned by _setfont.
  14156.  
  14157.                                    The _setfont function uses four criteria
  14158.                                    for selecting the best fit. In
  14159.                                    descending order of precedence the four
  14160.                                    criteria are pixel height, typeface,
  14161.                                    pixel width, and spacing (fixed or
  14162.                                    proportional). If you request a
  14163.                                    vector-mapped font,_setfont sizes the
  14164.                                    font to correspond with the specified
  14165.                                    pixel height and width. If you request a
  14166.                                    raster-mapped (bit-mapped) font,
  14167.                                    _setfont chooses the closest available
  14168.                                    size. If the requested type size for a
  14169.                                    raster-mapped font fits exactly between
  14170.                                    two registered fonts, the smaller size
  14171.                                    takes precedence.
  14172.  
  14173.  f                                 Select only a fixed-spaced font.
  14174.  
  14175.  hy                                Character height, where y is the height
  14176.                                    in pixels.
  14177.  
  14178.  nx                                Select font number x, where x is less
  14179.                                    than or equal to the value returned by
  14180.                                    _registerfonts. For example, the option
  14181.                                    n3 makes the third registered font
  14182.                                    current, assuming that three or more
  14183.                                    fonts are registered.
  14184.  
  14185.  p                                 Select only a proportional-spaced font.
  14186.  
  14187.  r                                 Select only a raster-mapped (bit-mapped)
  14188.                                    font.
  14189.  
  14190.  t`fontname'                       Typeface of the font in single quotes.
  14191.                                    The fontname string is one of the
  14192.                                    following:
  14193.  
  14194.                                    courier     modern
  14195.  
  14196.                                    helv        script
  14197.  
  14198.                                    tms rmn     roman
  14199.  
  14200.                                    Notice the space in "tms rmn."
  14201.                                    Additional font files use other names
  14202.                                    for fontname. Refer to the vendor's
  14203.                                    documentation for these names.
  14204.  
  14205.  v                                 Select only a vector-mapped font.
  14206.  
  14207.  wx                                Character width, where x is the width in
  14208.                                    pixels.
  14209.  
  14210.  Option codes are not case-sensitive and can be listed in any order. You can
  14211.  separate codes with spaces or any other character that is not a valid option
  14212.  code. The _setfont function ignores all invalid codes.
  14213.  
  14214.  The _setfont function updates a data area with parameters of the current
  14215.  font. The data area is in the form of a structure, defined in the GRAPH.H
  14216.  file as
  14217.  
  14218.    struct _fontinfo
  14219.    {
  14220.       int     type;          /* set = vector,clear = bit map */
  14221.       int     ascent;        /* pix dist from top to base */
  14222.       int     pixwidth;      /* character width in pixels */
  14223.       int     pixheight;     /* character height in pixels */
  14224.       int     avgwidth;      /* average character width */
  14225.       char    filename[81];  /* file name including path */
  14226.       char    faceName[32];  /* font name */
  14227.    };
  14228.  
  14229.  If you wish to retrieve the parameters of the current font, call the
  14230.  function _getfontinfo. Refer to Appendix B, "C Library Guide," or online
  14231.  help for a description of this function.
  14232.  
  14233.  
  14234.  Display Text
  14235.  
  14236.  The last step consists of two parts. First, select a screen position for the
  14237.  text with the graphics function _moveto. Then display fonted text at that
  14238.  position with the function _outgtext. The _moveto function takes pixel
  14239.  coordinates as arguments. The coordinates locate the top left of the first
  14240.  character in the text string.
  14241.  
  14242.  
  14243.  An Example Program
  14244.  
  14245.  QuickC's font functions shine when used in conjunction with your other
  14246.  graphics functions. They allow you to dress up any image on the screen. Yet
  14247.  they can make a visual impression when used by themselves, as an example
  14248.  will show.
  14249.  
  14250.  The program SAMPLER.C displays sample text in all the available fonts, then
  14251.  exits when a key is pressed. Make sure the .FON files are in the current
  14252.  directory before running the program.
  14253.  
  14254.    /* SAMPLER.C: Display sample text in various fonts. */
  14255.  
  14256.    #include <stdio.h>
  14257.    #include <conio.h>
  14258.    #include <stdlib.h>
  14259.    #include <graph.h>
  14260.    #include <string.h>
  14261.  
  14262.    #define NFONTS 6
  14263.  
  14264.    main()
  14265.  
  14266.    {
  14267.      static unsigned char *text[2*NFONTS] =
  14268.      {
  14269.          "COURIER",        "courier",
  14270.          "HELV",           "helv",
  14271.          "TMS RMN",        "tms rmn",
  14272.          "MODERN",         "modern",
  14273.          "SCRIPT",         "script",
  14274.          "ROMAN",          "roman"
  14275.      };
  14276.      static unsigned char *face[NFONTS] =
  14277.      {
  14278.          "t'courier'",
  14279.          "t'helv'",
  14280.          "t'tms rmn'",
  14281.          "t'modern'",
  14282.          "t'script'",
  14283.          "t'roman'"
  14284.      };
  14285.      static unsigned char list[20];
  14286.      struct videoconfig vc;
  14287.      int mode = _VRES16COLOR;
  14288.      register i;
  14289.  
  14290.      /*  Read header info from all .FON files in
  14291.       *  current directory   */
  14292.  
  14293.      if(_registerfonts( "*.FON" )<0 )
  14294.      {
  14295.         _outtext("Error:  can't register fonts");
  14296.         exit( 0 );
  14297.      }
  14298.  
  14299.      /*   Set highest available video mode */
  14300.  
  14301.      while( !_setvideomode( mode ) )
  14302.         mode--;
  14303.      if( mode == _TEXTMONO )
  14304.         exit ( 0 );
  14305.  
  14306.      /*   Copy video configuration into structure vc */
  14307.  
  14308.      _getvideoconfig( &vc );
  14309.  
  14310.      /*   Display six lines of sample text */
  14311.  
  14312.      for( i = 0; i<NFONTS; i++ )
  14313.      {
  14314.         strcpy( list, face[i] );
  14315.         strcat( list, "h30w24b" );
  14316.  
  14317.         if( !_setfont( list ) )
  14318.         {
  14319.             _setcolor( i + 1 );
  14320.             _moveto( 0, (i * vc.numypixels) / NFONTS );
  14321.             _outgtext( text[i * 2] );
  14322.             _moveto( vc.numxpixels / 2,
  14323.                         (i * vc.numypixels) / NFONTS );
  14324.             _outgtext( text[(i * 2) + 1] );
  14325.         }
  14326.         else
  14327.         {
  14328.             _setvideomode( _DEFAULTMODE );
  14329.             _outtext( "Error:  can't set font" );
  14330.             exit( 0 );
  14331.         }
  14332.      }
  14333.      getch();
  14334.      _setvideomode( _DEFAULTMODE );
  14335.  
  14336.      /* Return memory when finished with fonts */
  14337.  
  14338.      _unregisterfonts();
  14339.      exit ( 0 );
  14340.    }
  14341.  
  14342.  Notice that SAMPLER.C calls the graphics function _moveto to establish the
  14343.  starting position for each text string. Chapter 13, "Graphics," describes
  14344.  the _moveto function in the section "Graphics Coordinates." The function
  14345.  _setfont takes a character string as an argument. The string is a list of
  14346.  options that specifies typeface and the best fit for a character height of
  14347.  30 pixels, and a width of 24 pixels. See Appendix B, "C Library Guide," and
  14348.  online help for complete descriptions of the QuickC font functions.
  14349.  
  14350.  
  14351.  A Few Hints
  14352.  
  14353.  Fonted text is simply another form of graphics, and using fonts effectively
  14354.  requires little programming effort. Still, there are a few things to watch:
  14355.  
  14356.  
  14357.  
  14358.    ■   Remember the video should be set only once to establish a graphics
  14359.        mode. If you generate an image─say, with Presentation Graphics─and
  14360.        wish to incorporate fonted text into it, don't reset the video mode
  14361.        prior to calling the font routines. Doing so will blank the screen,
  14362.        destroying the original image.
  14363.  
  14364.    ■   The _setfont function reads specified .FON files to obtain mapping
  14365.        data for the current font. Each call to _setfont causes a disk access
  14366.        and overwrites the old font data in memory. If you wish to show text
  14367.        of different styles on the same screen, display all text of one font
  14368.        before moving on to the others. By minimizing the number of calls to
  14369.        _setfont you'll save time spent in disk I/O and memory reloads.
  14370.  
  14371.    ■   When your program finishes with the fonts library, you might wish to
  14372.        free the memory occupied by the register list. Call the function
  14373.        _unregisterfonts to do this. As its name implies, this function frees
  14374.        the memory allocated by _registerfonts. The register information for
  14375.        each type size of each font takes up approximately 140 bytes of
  14376.        memory. Thus the amount of memory returned by _unregisterfonts is
  14377.        significant only if you have many fonts registered.
  14378.  
  14379.    ■   As for aesthetics, the same suggestions for the printed page apply to
  14380.        fonted screen text. Typefaces are more effective when they are not
  14381.        competing with each other for attention. Restricting the number of
  14382.        styles per screen to one or two generally results in a more pleasing,
  14383.        less cluttered image.
  14384.  
  14385.  
  14386.  
  14387.  
  14388.  
  14389.  
  14390.  
  14391.  Chapter 16  In-Line Assembly
  14392.  ────────────────────────────────────────────────────────────────────────────
  14393.  
  14394.  QuickC has the ability to handle assembly-language instructions right in
  14395.  your C programs. This powerful feature is called "in-line assembly."
  14396.  
  14397.  Assembly language serves many purposes, such as improving program speed,
  14398.  reducing memory needs, and controlling hardware. The in-line assembler lets
  14399.  you embed assembly-language instructions directly in your C source programs
  14400.  without extra assembly and link steps. And the assembler is built into the
  14401.  compiler─you don't need a separate assembler such as the Microsoft Macro
  14402.  Assembler (MASM).
  14403.  
  14404.  This chapter assumes that you are familiar with assembly-language terms and
  14405.  concepts. If you have never programmed in assembly language, refer to the
  14406.  section "References and Books on Assembly Language," at the end of this
  14407.  chapter.
  14408.  
  14409.  
  14410.  Advantages of In-Line Assembly
  14411.  
  14412.  Because QuickC's in-line assembler doesn't require separate assembly and
  14413.  link steps, it is more convenient than a separate assembler. In-line
  14414.  assembly code can use any C variable or function name that is visible (in
  14415.  scope), so it is easy to integrate it with your program's C code. And
  14416.  because the assembly code can be mixed in-line with C statements, it can do
  14417.  tasks that are cumbersome or impossible in C alone.
  14418.  
  14419.  The uses of in-line assembly include
  14420.  
  14421.  
  14422.    ■   Writing the body of a function in assembly language
  14423.  
  14424.    ■   Spot-optimizing speed-critical sections of code
  14425.  
  14426.    ■   Calling DOS and BIOS routines with the INT instruction
  14427.  
  14428.    ■   Creating TSR (terminate-and-stay-resident) code or handler routines
  14429.        that require knowledge of processor states
  14430.  
  14431.  
  14432.  In-line assembly is a special-purpose tool. If you plan to transport an
  14433.  application, you'll probably want to place machine-specific code in a
  14434.  separate module. And because the in-line assembler doesn't support all MASM
  14435.  directives, you may find it more convenient to use MASM for such modules.
  14436.  
  14437.  
  14438.  The _asm Keyword
  14439.  
  14440.  The _asm keyword invokes the in-line assembler and can appear wherever a C
  14441.  statement is legal. It cannot appear by itself. It must be followed by an
  14442.  assembly instruction, a group of instructions enclosed in braces, or, at the
  14443.  very least, an empty pair of braces. The term "_asm block" here refers to
  14444.  any instruction or group of instructions, whether or not in braces.
  14445.  
  14446.  Below is a simple _asm block enclosed in braces. (The code prints the "beep"
  14447.  character, ASCII 7.)
  14448.  
  14449.    _asm
  14450.    {
  14451.       mov ah, 2
  14452.       mov dl, 7
  14453.       int 21h
  14454.    }
  14455.  
  14456.  Alternatively, you can put _asm in front of each assembly instruction:
  14457.  
  14458.    _asm mov ah, 2
  14459.    _asm mov dl, 7
  14460.    _asm int 21h
  14461.  
  14462.  Since the _asm keyword is a statement separator, you can also put assembly
  14463.  instructions on the same line:
  14464.  
  14465.    _asm mov ah, 2   _asm mov dl, 7   _asm int 21h
  14466.  
  14467.    Braces can prevent ambiguity and needless repetition.
  14468.  
  14469.  All three examples generate the same code, but the first style─enclosing the
  14470.  _asm block in braces─has some advantages. The braces clearly separate
  14471.  assembly code from C code and avoid needless repetition of the _asm keyword.
  14472.  Braces can also prevent ambiguities. If you want to put a C statement on the
  14473.  same line as an _asm block, you must enclose the block in braces. Without
  14474.  the braces, the compiler cannot tell where assembly code stops and C
  14475.  statements begin. Finally, since the text in braces has the same format as
  14476.  ordinary MASM text, you can easily cut and paste text from existing MASM
  14477.  source files.
  14478.  
  14479.  The braces enclosing an _asm block don't affect variable visibility, as do
  14480.  braces in C. You can also nest _asm blocks, but the nesting doesn't affect
  14481.  variable visibility.
  14482.  
  14483.  
  14484.  Using Assembly Language in _asm Blocks
  14485.  
  14486.  The in-line assembler has much in common with other assemblers. For example,
  14487.  it accepts any expression that is legal in MASM, and it supports almost all
  14488.  80286 and 80287 instructions. This section describes the use of
  14489.  assembly-language features in _asm blocks.
  14490.  
  14491.  
  14492.  Instruction Set
  14493.  
  14494.  The in-line assembler supports the full instruction set of the Intel(R)
  14495.  80286 and 80287 processors, except for privileged instructions that control
  14496.  the processor's protected mode (protected mode is available in the OS/2 and
  14497.  XENIX(R) operating systems, but not in DOS). It does not recognize 80386-
  14498.  and 80387-specific instructions. To use assembly instructions specific to
  14499.  the 80286 and 80287 processors, you must compile your QuickC program with
  14500.  the /G2 switch included in the command line. For a description of the
  14501.  compiler /G command-line switch, refer to Chapter 4, "QCL Command
  14502.  Reference," in the Microsoft QuickC Tool Kit.
  14503.  
  14504.  
  14505.  Expressions
  14506.  
  14507.  In-line assembly code can use any MASM expression, that is, any combination
  14508.  of operands and operators that evaluates to a single value or address.
  14509.  
  14510.  
  14511.  Data Directives and Operators
  14512.  
  14513.  Although an _asm block can reference C data types and objects, it cannot
  14514.  define data objects with MASM directives or operators. Specifically, you
  14515.  cannot use the definition directives DB, DW, DD, DQ, DT, and DF, or the
  14516.  operators DUP or THIS. Nor are MASM structures and records available. The
  14517.  in-line assembler doesn't accept the directives STRUC, RECORD, WIDTH, or
  14518.  MASK.
  14519.  
  14520.  
  14521.  EVEN and ALIGN Directives
  14522.  
  14523.  While the in-line assembler doesn't support most MASM directives, it does
  14524.  support EVEN and ALIGN. These directives put NOP (no operation) instructions
  14525.  in the assembly code as needed to align labels to specific boundaries. This
  14526.  makes instruction-fetch operations more efficient for some processors (not
  14527.  including eight-bit processors such as the Intel 8088).
  14528.  
  14529.  
  14530.  Macros
  14531.  
  14532.  The in-line assembler is not a macro assembler. You cannot use MASM macro
  14533.  directives (MACRO, REPT, IRC, IRP, and ENDM) or macro operators ( <>, !, &,
  14534.  %, and .TYPE). An _asm block can use C preprocessor directives, however. See
  14535.  the section "Using C in _asm Blocks" for more information.
  14536.  
  14537.  
  14538.  Segment References
  14539.  
  14540.  You must refer to segments by register rather than by name (the segment name
  14541.  _TEXT is invalid, for instance). Segment overrides must use the register
  14542.  explicitly, as in ES:[BX].
  14543.  
  14544.  
  14545.  Type and Variable Sizes
  14546.  
  14547.  The LENGTH, SIZE, and TYPE operators have a limited meaning in in-line
  14548.  assembly. They cannot be used at all with the DUP operator (because you
  14549.  cannot define data with MASM directives or operators). But you can use them
  14550.  to find the size of C variables or types:
  14551.  
  14552.  
  14553.    ■   The LENGTH operator can return the number of elements in an array. It
  14554.        returns the value 1 for nonarray variables.
  14555.  
  14556.    ■   The SIZE operator can return the size of a C variable. A variable's
  14557.        size is the product of its LENGTH and TYPE.
  14558.  
  14559.    ■   The TYPE operator can return the size of a C type or variable. If the
  14560.        variable is an array, TYPE returns the size of a single element of the
  14561.        array.
  14562.  
  14563.  
  14564.  For instance, if your program has an eight-element int array,
  14565.  
  14566.    int arr[8];
  14567.  
  14568.  the following C and assembly expressions yield the size of  arr  and its
  14569.  elements:
  14570.  
  14571. ╓┌───────────┌───────────────────────────┌───────────────────────────────────╖
  14572.  _asm        C                           Size
  14573.  ────────────────────────────────────────────────────────────────────────────
  14574.  LENGTH arr  sizeof(arr)/sizeof(arr[0])  8
  14575.  SIZE arr    sizeof(arr)                 16
  14576.  _asm        C                           Size
  14577.  ────────────────────────────────────────────────────────────────────────────
  14578. SIZE arr    sizeof(arr)                 16
  14579.  TYPE arr    sizeof(arr[0])              2
  14580.  ────────────────────────────────────────────────────────────────────────────
  14581.  
  14582.  
  14583.  
  14584.  Comments
  14585.  
  14586.  Instructions in an _asm block can use assembly-language comments:
  14587.  
  14588.    _asm mov ax, offset buff ; Load address of buff
  14589.  
  14590.  Because C macros expand into a single logical line, avoid using
  14591.  assemblylanguage comments in macros (see the section "Defining _asm Blocks
  14592.  as C Macros," below). An _asm block can also contain C-style comments, as
  14593.  noted below.
  14594.  
  14595.  
  14596.  Debugging with the CodeView(R) Debugger
  14597.  
  14598.   In-line assembly code can be debugged with CodeView.
  14599.  
  14600.  Programs containing in-line assembly code can be debugged with the CodeView
  14601.  debugger, assuming you compile with the /Zi option.
  14602.  
  14603.  Note that putting multiple assembly instructions or C statements on one line
  14604.  can hamper debugging with CodeView. In source mode, the CodeView debugger
  14605.  lets you set breakpoints on a single line but not on individual statements
  14606.  on the same line. The same principle applies to an _asm block defined as a C
  14607.  macro, which expands to a single logical line.
  14608.  
  14609.  
  14610.  Using C in _asm Blocks
  14611.  
  14612.  Because in-line assembly instructions can be mixed with C statements, they
  14613.  can refer to C variables by name and use many other elements of C. An _asm
  14614.  block can use the following C language elements:
  14615.  
  14616.  
  14617.    ■   Symbols, including labels and variable and function names
  14618.  
  14619.    ■   Constants, including symbolic constants and enum members
  14620.  
  14621.    ■   Macros and preprocessor directives
  14622.  
  14623.    ■   Comments ( /* */ )
  14624.  
  14625.    ■   Type names (wherever a MASM type would be legal)
  14626.  
  14627.    ■   typedef names, generally used with operators such as PTR and TYPE or
  14628.        to specify structure or union members
  14629.  
  14630.  
  14631.  Within an _asm block, you can specify integer constants with either C
  14632.  notation or assembler radix notation (0x100 and 100h are equivalent, for
  14633.  instance). This allows you to define (using #define) a constant in C, and
  14634.  use it in both C and assembly portions of the program. You can also specify
  14635.  constants in octal by preceding them with a 0. For example, 0777 specifies
  14636.  an octal constant.
  14637.  
  14638.  
  14639.  Using Operators
  14640.  
  14641.  An _asm block cannot use C-specific operators, such as the  operator.
  14642.  However, operators shared by QuickC and MASM, such as the * operator, are
  14643.  interpreted as assembly-language operators. For instance, outside an _asm
  14644.  block, square brackets ( [] ) are interpreted as enclosing array subscripts,
  14645.  which C automatically scales to the size of an element in the array. Inside
  14646.  an _asm block, they are seen as the MASM index operator, which yields an
  14647.  unscaled byte offset from any data object or label (not just an array). The
  14648.  following code illustrates the difference:
  14649.  
  14650.    int array[10];
  14651.  
  14652.    _asm mov array[6], bx ;  Store BX at array+6 (not scaled)
  14653.  
  14654.    array[6] = 0;         /* Store 0 at array+12 (scaled) */
  14655.  
  14656.  The first reference to  array  is not scaled, but the second is. Note that
  14657.  you can use the TYPE operator to achieve scaling based on a constant. For
  14658.  instance, the following statements are equivalent:
  14659.  
  14660.    _asm mov array[6 * TYPE int], 0 ; Store 0 at array + 12
  14661.  
  14662.    array[6] = 0;                   /* Store 0 at array + 12 */
  14663.  
  14664.  
  14665.  Using C Symbols
  14666.  
  14667.  An _asm block can refer to any C symbol that is visible (in scope) where the
  14668.  block appears. (C symbols are variable names, function names, and labels─in
  14669.  other words, names that aren't symbolic constants or enum members.)
  14670.  
  14671.  A few restrictions apply to the use of C symbols:
  14672.  
  14673.  
  14674.    ■   Each assembly-language statement can contain only one C symbol.
  14675.        Multiple symbols can appear in the same assembly instruction only with
  14676.        OFFSET, LENGTH, TYPE, and SIZE expressions.
  14677.  
  14678.    ■   Functions referenced in an _asm block must be declared (prototyped)
  14679.        earlier in the program. Otherwise, the compiler cannot distinguish
  14680.        between function names and labels in the _asm block.
  14681.  
  14682.    ■   An _asm block cannot use any C symbols with the same spelling as MASM
  14683.        reserved words (regardless of case). MASM reserved words include
  14684.        instruction names such as PUSH and register names such as SI.
  14685.  
  14686.    ■   Structure and union tags are not recognized in _asm blocks.
  14687.  
  14688.  
  14689.  
  14690.  Accessing C Data
  14691.  
  14692.  A great convenience of in-line assembly is the ability to refer to C
  14693.  variables by name. An _asm block can refer to any symbols─including variable
  14694.  names─that are visible where the block appears. For instance, if the C
  14695.  variable  var  is visible, the instruction
  14696.  
  14697.    _asm mov ax, var
  14698.  
  14699.  stores the value of  var  in AX.
  14700.  
  14701.  If a structure or union member has a unique name, an _asm block can refer to
  14702.  it using only the member name, without specifying the C variable or typedef
  14703.  name before the period (.) operator. If the member name is not unique,
  14704.  however, you must place a variable or typedef name immediately before the
  14705.  period (.) operator. For instance, the following structure types share
  14706.  same_name  as their member name:
  14707.  
  14708.    struct first_type
  14709.    {
  14710.       char *weasel;
  14711.       int same_name;
  14712.    };
  14713.  
  14714.    struct second_type
  14715.    {
  14716.       int wonton;
  14717.       long same_name;
  14718.    };
  14719.  
  14720.  If you declare variables with the types
  14721.  
  14722.    struct first_type hal;
  14723.    struct second_type oat;
  14724.  
  14725.  all references to the member  same_name  must use the variable name, because
  14726.  same_name  is not unique. But the member  weasel  has a unique name, so you
  14727.  can refer to it using only its member name:
  14728.  
  14729.    _asm
  14730.    {
  14731.       mov bx, OFFSET hal
  14732.       mov cx, [bx]hal.same_name ; Must use 'hal'
  14733.       mov si, [bx].weasel       ; Can omit 'hal'
  14734.    }
  14735.  
  14736.  Note that omitting the variable name is merely a coding convenience. The
  14737.  same assembly instructions are generated whether or not it is present.
  14738.  
  14739.  
  14740.  Writing Functions
  14741.  
  14742.  If you write a function with in-line assembly code, it's a simple matter to
  14743.  pass arguments to the function and return a value from it. The following
  14744.  examples compare a function first written for a separate assembler and then
  14745.  rewritten for the in-line assembler. The function, called  power2, receives
  14746.  two parameters, multiplying the first parameter by 2 to the power of the
  14747.  second parameter. Written for a separate assembler, the function might look
  14748.  like this:
  14749.  
  14750.    ; POWER.ASM
  14751.    ; Compute the power of an integer
  14752.    ;
  14753.           PUBLIC _power2
  14754.    _TEXT SEGMENT WORD PUBLIC 'CODE'
  14755.    _power2 PROC
  14756.  
  14757.            push bp         ; Save BP
  14758.            mov bp, sp      ; Move SP into BP so we can refer
  14759.                            ;   to arguments on the stack
  14760.            mov ax, [bp+4]  ; Get first argument
  14761.            mov cx, [bp+6]  ; Get second argument
  14762.            shl ax, cl      ; AX = AX * ( 2 ^ CL )
  14763.            pop bp          ; Restore BP
  14764.            ret             ; Return with sum in AX
  14765.  
  14766.    _power2 ENDP
  14767.    _TEXT   ENDS
  14768.            END
  14769.  
  14770.   Function arguments are usually passed on the stack.
  14771.  
  14772.  Since it's written for a separate assembler, the function requires a
  14773.  separate source file and assembly and link steps. C function arguments
  14774.  usually are passed on the stack, so this version of the  power2  function
  14775.  accesses its arguments by their positions on the stack. (Note that the MODEL
  14776.  directive, available in MASM and some other assemblers, also allows you to
  14777.  access stack arguments and local stack variables by name.)
  14778.  
  14779.  The POWER2.C program below writes the  power2  function with in-line
  14780.  assembly code:
  14781.  
  14782.    /* POWER2.C */
  14783.    #include <stdio.h>
  14784.  
  14785.    int power2( int num, int power );
  14786.  
  14787.    void main( void )
  14788.    {
  14789.       printf( "3 times 2 to the power of 5 is %d\n", \
  14790.               power2( 3, 5) );
  14791.    }
  14792.  
  14793.    int power2( int num, int power )
  14794.    {
  14795.       _asm
  14796.       {
  14797.          mov ax, num    ; Get first argument
  14798.          mov cx, power  ; Get second argument
  14799.          shl ax, cl     ; AX = AX * ( 2 to the power of CL )
  14800.       }
  14801.       /* Return with result in AX */
  14802.    }
  14803.  
  14804.  The in-line version of the  power2  function refers to its arguments by name
  14805.  and appears in the same source file as the rest of the program. This version
  14806.  also requires fewer assembly instructions. Since C automatically preserves
  14807.  BP, the _asm block doesn't need to do so. It can also dispense with the RET
  14808.  instruction, since the C part of the function performs the return.
  14809.  
  14810.  Because the in-line version of  power2  doesn't execute a C return
  14811.  statement, it causes a harmless warning if you compile at warning levels 2
  14812.  or higher:
  14813.  
  14814.    warning C4035: 'power2' : no return value
  14815.  
  14816.  The function does return a value, but QuickC cannot tell that in the absence
  14817.  of a return statement. Simply ignore the warning in this context.
  14818.  
  14819.  
  14820.  Using and Preserving Registers
  14821.  
  14822.  In general, you should not assume that a register will have a given value
  14823.  when an _asm block begins. An _asm block inherits whatever register values
  14824.  happen to result from the normal flow of control.
  14825.  
  14826.  As you may have noticed in the POWER2.C example in the previous section, the
  14827.  power2  function doesn't preserve the value in the AX register. When you
  14828.  write a function in assembly language, you don't need to preserve the AX,
  14829.  BX, CX, DX, ES, and flags registers. However, you should preserve any other
  14830.  registers you use (DI, SI, DS, SS, SP, and BP).
  14831.  
  14832.  ────────────────────────────────────────────────────────────────────────────
  14833.  WARNING
  14834.  
  14835.  If your in-line assembly code changes the direction flag using the STD or
  14836.  CLD instructions, you must restore the flag to its original value.
  14837.  ────────────────────────────────────────────────────────────────────────────
  14838.  
  14839.  The POWER2.C example in the previous section also shows that functions
  14840.  return values in registers. This is true whether the function is written in
  14841.  assembly language or in C.
  14842.  
  14843.   Functions return values in the AX and DX registers.
  14844.  
  14845.  If the return value is short (a char, int, or near pointer), it is stored in
  14846.  AX. The POWER2.C example returned a value by terminating with the desired
  14847.  value in AX.
  14848.  
  14849.  If the return value is long, store the high word in DX and the low word in
  14850.  AX. To return a longer value (such as a floating-point value), store the
  14851.  value in memory and return a pointer to the value (in AX if near or in DX:AX
  14852.  if far).
  14853.  
  14854.  Assembly instructions that appear in-line with C statements are free to
  14855.  alter the AX, BX, CX, and DX registers. C doesn't expect these registers to
  14856.  be maintained between statements, so you don't need to preserve them. The
  14857.  same is true of the SI and DI registers, with some exceptions (see the
  14858.  section "Optimizing," below). You should preserve the SP and BP registers
  14859.  unless you have some reason to change them─to switch stacks, for instance.
  14860.  
  14861.  
  14862.  Jumping to Labels
  14863.  
  14864.  Like an ordinary C label, a label in an _asm block is visible (has scope)
  14865.  throughout the function in which it is defined (not only in the block). Both
  14866.  assembly instructions and C goto statements can jump to labels inside or
  14867.  outside the _asm block.
  14868.  
  14869.   Labels in _asm blocks have function scope and are not case sensitive.
  14870.  
  14871.  Unlike C labels, labels defined in _asm blocks are not case sensitive, even
  14872.  when used in C statements. C labels are not case sensitive in an _asm block,
  14873.  either. (Outside an _asm block, a C label is case sensitive as usual.) The
  14874.  following do-nothing code shows all the permutations.
  14875.  
  14876.    void func( void )
  14877.    {
  14878.       goto C_Dest;  /* legal */
  14879.       goto c_dest;  /* error */
  14880.  
  14881.       goto A_Dest;  /* legal */
  14882.       goto a_dest;  /* legal */
  14883.  
  14884.       _asm
  14885.       {
  14886.          jmp C_Dest ; legal
  14887.          jmp c_dest ; legal
  14888.  
  14889.          jmp A_Dest ; legal
  14890.          jmp a_dest ; legal
  14891.  
  14892.          a_dest:    ; _asm label
  14893.       }
  14894.  
  14895.       C_Dest:       /* C label */
  14896.       return;
  14897.    }
  14898.  
  14899.  Don't use C library function names as labels in _asm blocks. For instance,
  14900.  you might be tempted to use  exit  as a label,
  14901.  
  14902.    jne exit
  14903.       .
  14904.       .
  14905.       .
  14906.    exit:
  14907.       ; More _asm code follows
  14908.  
  14909.  forgetting that exit is the name of a C library function. The code doesn't
  14910.  cause a compiler error, but it might cause a jump to the exit function
  14911.  instead of the desired location.
  14912.  
  14913.  As in MASM programs, the dollar symbol ($) serves as the current location
  14914.  counter─a label for the instruction currently being assembled. In _asm
  14915.  blocks, its main use is to make long conditional jumps:
  14916.  
  14917.    jne $+5 ; next instruction is 5 bytes long
  14918.    jmp farlabel
  14919.    ; $+5
  14920.       .
  14921.       .
  14922.       .
  14923.    farlabel:
  14924.  
  14925.  
  14926.  Calling C Functions
  14927.  
  14928.  An _asm block can call C functions, including C library routines. The
  14929.  following example calls the printf library routine:
  14930.  
  14931.    #include <stdio.h>
  14932.  
  14933.    char format[] = "%s %s\n";
  14934.    char hello[] = "Hello";
  14935.    char world[] = "world";
  14936.  
  14937.    void main( void )
  14938.    {
  14939.       _asm
  14940.       {
  14941.          mov  ax, offset world
  14942.          push ax
  14943.          mov  ax, offset hello
  14944.          push ax
  14945.          mov  ax, offset format
  14946.          push ax
  14947.          call printf
  14948.         add sp, 6
  14949.       }
  14950.    }
  14951.  
  14952.  Since function arguments are passed on the stack, you simply push the needed
  14953.  arguments─string pointers, in the example above─before calling the function.
  14954.  The arguments are pushed in reverse order, so they come off the stack in the
  14955.  desired order. To emulate the C statement
  14956.  
  14957.    printf( format, hello, world );
  14958.  
  14959.  the example pushes pointers to  world,  hello, and  format, in that order,
  14960.  then calls printf. The last instruction in the _asm block adjusts the stack
  14961.  to account for the arguments previously pushed onto it.
  14962.  
  14963.  
  14964.  Defining _asm Blocks as C Macros
  14965.  
  14966.  C macros offer a convenient way to insert assembly code into C code, but
  14967.  they demand extra care because a macro expands into a single logical line.
  14968.  To create trouble-free macros, follow these rules:
  14969.  
  14970.  
  14971.    ■   Enclose the _asm block in braces
  14972.  
  14973.    ■   Put the _asm keyword in front of each assembly instruction
  14974.  
  14975.    ■   Use old-style C comments ( /* comment */ ) instead of assembly-style
  14976.        comments ( ; comment )
  14977.  
  14978.  
  14979.  To illustrate, the following example defines a simple macro:
  14980.  
  14981.    #define BEEP _asm \
  14982.    /* Beep sound */       \
  14983.    {                       \
  14984.       _asm mov ah, 2       \
  14985.       _asm mov dl, 7       \
  14986.       _asm int 21h         \
  14987.    }
  14988.  
  14989.  At first glance, the last three _asm keywords seem superfluous. They are
  14990.  needed, however, because the macro expands into a single line:
  14991.  
  14992.    _asm /* Beep sound */ { _asm mov ah, 2  _asm mov dl, 7 _asm int 21h }
  14993.  
  14994.  The third and fourth _asm keywords are needed as statement separators. The
  14995.  only statement separators recognized in _asm blocks are the newline
  14996.  character and _asm keyword. And since a block defined as a macro is one
  14997.  logical line, you must separate each instruction with _asm.
  14998.  
  14999.  The braces are essential as well. If you omit them, the compiler can be
  15000.  confused by C statements on the same line to the right of the macro
  15001.  invocation. Without the closing brace, QuickC cannot tell where assembly
  15002.  code stops, and it sees C statements after the _asm block as assembly
  15003.  instructions.
  15004.  
  15005.    Use C comments in _asm blocks written as macros.
  15006.  
  15007.  Assembly-style comments that start with a semicolon (;) continue to the end
  15008.  of the line. This causes problems in macros because QuickC ignores
  15009.  everything after the comment, all the way to the end of the logical line. To
  15010.  prevent errors, use C comments ( /* comment */ ) in _asm blocks defined as
  15011.  macros.
  15012.  
  15013.  An _asm block written as a C macro can take arguments. Unlike an ordinary C
  15014.  macro, however, an _asm macro cannot return a value. So you cannot use such
  15015.  macros in C expressions.
  15016.  
  15017.   You can convert MASM macros to C macros.
  15018.  
  15019.  Note that some MASM-style macros can be written as C macros. Below is a MASM
  15020.  macro that sets the video page to the value specified in the  page
  15021.  argument:
  15022.  
  15023.    setpage   MACRO page
  15024.              mov ah, 5
  15025.              mov al, page
  15026.              int 10h
  15027.              ENDM
  15028.  
  15029.  The following code defines  setpage  as a C macro:
  15030.  
  15031.    #define setpage( page ) _asm  \
  15032.       {                                \
  15033.          _asm mov ah, 5                \
  15034.          _asm mov al, page             \
  15035.          _asm int 10h                  \
  15036.    }
  15037.  
  15038.  Both macros do the same job.
  15039.  
  15040.  
  15041.  Optimizing
  15042.  
  15043.  The presence of an _asm block in a function affects optimization in a few
  15044.  different ways. First, as you might expect, QuickC doesn't try to optimize
  15045.  the _asm block itself. What you write in assembly language is exactly what
  15046.  you get.
  15047.  
  15048.  Second, the presence of an _asm block affects register variable storage.
  15049.  (See the section "Register Variables" in Chapter 5, "Advanced Data Types,"
  15050.  for a discussion of register variables.) Under normal circumstances, QuickC
  15051.  automatically stores variables in registers. This is not done, however, in
  15052.  any function that contains an _asm block. To get register variable storage
  15053.  in such a function, you must request it with the register keyword.
  15054.  
  15055.  Since the compiler stores register variables in the SI and DI registers,
  15056.  these registers represent variables in functions that request register
  15057.  storage. The first eligible variable is stored in SI and the second in DI.
  15058.  Preserve SI and DI in such functions unless you want to change the register
  15059.  variables.
  15060.  
  15061.  Keep in mind that the name of a variable declared with register translates
  15062.  directly into a register reference (assuming a register is available for
  15063.  such use). For instance, if you declare
  15064.  
  15065.    register int sample;
  15066.  
  15067.  and the variable  sample  happens to be stored in SI, then the _asm
  15068.  instruction
  15069.  
  15070.    _asm mov ax, sample
  15071.  
  15072.  is equivalent to
  15073.  
  15074.    _asm mov ax, si
  15075.  
  15076.  If you declare a variable with register and the compiler cannot store the
  15077.  variable in a register, QuickC issues a compiler error if you reference the
  15078.  variable in an _asm block. The solution is to remove the register
  15079.  declaration from that variable.
  15080.  
  15081.  Register variables form a slight exception to the general rule that an
  15082.  assembly-language statement can contain no more than one C symbol. If one of
  15083.  the symbols is a register variable, for example,
  15084.  
  15085.    register int v1;
  15086.    int v2;
  15087.  
  15088.  then an instruction can use two C symbols, as in
  15089.  
  15090.    mov v1, v2
  15091.  
  15092.  Finally, the presence of in-line assembly code inhibits loop optimization
  15093.  for the entire function in which the code appears. (Loop optimization can be
  15094.  selected with the /Ol command-line switch; see Chapter 4, "QCL Command
  15095.  Reference," in Microsoft QuickC Tool Kit.) This optimization is suppressed
  15096.  no matter which compiler options you use.
  15097.  
  15098.  
  15099.  References and Books on Assembly Language
  15100.  
  15101.  Assembly language varies widely for different computer processors. In
  15102.  selecting a reference on assembly language, make sure it describes assembly
  15103.  for the Intel 8086 family of processors or compatibles. These are the
  15104.  microprocessors used in the IBM and IBM-compatible computers able to run
  15105.  QuickC.
  15106.  
  15107.  The following books and articles may be useful in learning to program in
  15108.  assembly language:
  15109.  
  15110.  Chesley, Harry R. and Mitchell Waite. Supercharging C with Assembly
  15111.  Language.
  15112.      Reading, Massachusetts: Addison-Wesley Publishing Company,  Inc., 1987.
  15113.  
  15114.  Duncan, Ray. Advanced MS-DOS Programming, 2nd ed. Redmond,  Washington:
  15115.  Microsoft Press, 1988.
  15116.  
  15117.  Lafore, Robert. Assembly Language Primer for the IBM PC & XT.
  15118.      New York, New York: Plume/Waite, 1984.
  15119.  
  15120.  Metcalf, Christopher D. and Marc B. Sugiyama. COMPUTE!'s Beginner's Guide to
  15121.  Machine Language on the IBM PC & PCjr.
  15122.      Greensboro, North Carolina: COMPUTE! Publications, Inc., 1985.
  15123.  
  15124.  Microsoft. Microsoft Macro Assembler 5.1 Programmer's Guide.
  15125.      Redmond, Washington, 1987. (Included with Microsoft Macro Assembler.)
  15126.  
  15127.  Microsoft. Microsoft Macro Assembler 5.1 Reference.
  15128.      Redmond, Washington, 1987. (Included with Microsoft Macro Assembler.)
  15129.  
  15130.  Sargent, Murray and Richard L. Shoemaker. The IBM Personal Computer from the
  15131.  Inside Out.
  15132.      Reading, Massachusetts: Addison-Wesley Publishing Company, Inc., 1986.
  15133.  
  15134.  The above references are listed for your convenience only. With the
  15135.  exception of those published by Microsoft, Microsoft Corporation does not
  15136.  endorse these books or recommend them over others on the same subject.
  15137.  
  15138.  
  15139.  
  15140.  
  15141.  
  15142.  
  15143.  Appendix A  C Language Guide
  15144.  ────────────────────────────────────────────────────────────────────────────
  15145.  
  15146.  This appendix provides a quick summary of C language fundamentals. It does
  15147.  not attempt to teach you the C language (Part 1 of this book does that) or
  15148.  document all the details of C. Use it as a refresher or ready reference
  15149.  after you have read all the material in Chapters 1 through 10.
  15150.  
  15151.  To simplify reference, this appendix has the same general organization as
  15152.  the chapters in Part 1. Each major section lists the chapter(s) where you
  15153.  may find more detailed information on a given topic.
  15154.  
  15155.  You can also use QuickC's online help to get instant information on any
  15156.  topic. The online help index and table of contents provide alternate ways to
  15157.  access information.
  15158.  
  15159.  
  15160.  General Syntax
  15161.  
  15162.  Basic C-language syntax is explained in Chapter 1, "Anatomy of a C Program."
  15163.  
  15164.  
  15165.  A C statement consists of keywords, expressions, and function calls. A
  15166.  statement always ends with a semicolon. A statement block is a collection of
  15167.  statements enclosed by braces ({ }). A statement block can appear anywhere a
  15168.  simple C statement appears. No semicolon occurs after the closing brace.
  15169.  
  15170.  C is a free-format programming language. You can insert "whitespace"
  15171.  characters (spaces, tabs, carriage returns, and form feeds) almost anywhere,
  15172.  to indent statement blocks and otherwise make your code more readable.
  15173.  
  15174.  Comments begin with the slash-asterisk sequence (/*) and end with the
  15175.  asterisk-slash sequence (*/). Comments are legal anywhere a space is legal,
  15176.  but they cannot be nested.
  15177.  
  15178.  
  15179.  User-Defined Names
  15180.  
  15181.  The rules governing user-defined names are explained in Chapter 1, "Anatomy
  15182.  of a C Program," and Chapter 4, "Basic Data Types."
  15183.  
  15184.  You can define your own names ("identifiers") for variables, functions, and
  15185.  user-defined types. Identifiers are case sensitive. For instance, the
  15186.  identifier myVariable  is not the same as the identifier  Myvariable. You
  15187.  cannot use a C keyword (see the list below) as an identifier.
  15188.  
  15189.  An identifier can contain only the following characters:
  15190.  
  15191.  
  15192.    ■   abcdefghijklmnopqrstuvwxyz
  15193.  
  15194.    ■   ABCDEFGHIJKLMNOPQRSTUVWXYZ
  15195.  
  15196.    ■   0123456789
  15197.  
  15198.    ■   _ (underscore)
  15199.  
  15200.  
  15201.  The first character of an identifier must be a letter or the underscore
  15202.  character. The first 31 characters of local identifiers are significant. The
  15203.  name can contain more than 31 characters, but QuickC ignores everything
  15204.  beyond the thirty-first character. Global identifiers are normally
  15205.  significant to 30 characters.
  15206.  
  15207.  
  15208.  Keywords
  15209.  
  15210.  A keyword has a special meaning in the C language. You must spell keywords
  15211.  as shown in the following list, and you cannot use them as user-defined
  15212.  names (see above).
  15213.  
  15214.  _asm            _emit           _interrupt       signed
  15215.   auto            enum           _loadds          sizeof
  15216.  _based          _export          long            static
  15217.    break          extern         _near            struct
  15218.   case           _far            _pascal          switch
  15219.  _cdecl          _fastcall        register        typedef
  15220.   char            float           return          union
  15221.   const           for            _saveregs        unsigned
  15222.   continue       _fortran        _segname         void
  15223.   default         goto           _segment         volatile
  15224.   do             _huge           _self            while
  15225.   double          if              short
  15226.   else            int
  15227.  
  15228.  A few other words, such as main, have a special meaning but are not keywords
  15229.  in the strict sense. Use online help to get details on all such words.
  15230.  
  15231.  
  15232.  Functions
  15233.  
  15234.  The rules governing C functions are explained in Chapter 2, "Functions."
  15235.  
  15236.  Every C program must have at least one function, named main, which marks the
  15237.  beginning and end of the program's execution. Every executable statement in
  15238.  a C program must occur within a function.
  15239.  
  15240.  Variables can be declared inside or outside functions. Variables declared
  15241.  inside a function are "local" and can only be accessed in that function.
  15242.  Variables declared outside all functions are "global" and can be accessed
  15243.  from any function in your program.
  15244.  
  15245.  You call a C function by stating its name. If the function requires
  15246.  "arguments" (data), you list the arguments in the parentheses that follow
  15247.  the function name. Arguments that you pass to a function become local
  15248.  variables in the function.
  15249.  
  15250.  A function can return a value (using the return keyword) or return nothing.
  15251.  If the function contains no return statement, it ends automatically when
  15252.  execution reaches the closing brace of the function definition.
  15253.  
  15254.  A function "prototype" (declaration) tells QuickC the function's name, the
  15255.  type of value it returns, and the number and type of arguments it requires.
  15256.  Function prototypes normally appear near the beginning of the program. They
  15257.  allow QuickC to check the accuracy of every reference to the function.
  15258.  
  15259.  
  15260.  Flow Control
  15261.  
  15262.  Flow-control statements are explained in Chapter 3, "Flow Control."
  15263.  
  15264.  The C language provides several kinds of flow-control statements. The for,
  15265.  while, and do statements create loops. The if and switch statements perform
  15266.  a branch. The break, continue, return, and goto statements perform an
  15267.  unconditional "jump" to another location in your program.
  15268.  
  15269.  The following sections describe the C flow-control statements in
  15270.  alphabetical order.
  15271.  
  15272.  
  15273.  The break Statement
  15274.  
  15275.  The break statement terminates the smallest enclosing do, for, switch, or
  15276.  while statement in which it appears. It passes control to the statement
  15277.  following the terminated statement.
  15278.  
  15279.  This statement is often used to exit from a loop or switch statement (see
  15280.  below). The following example illustrates break:
  15281.  
  15282.    while( c != 'Q' )
  15283.    {
  15284.      /* Some C statements here */
  15285.      if( number_of_characters > 80 )
  15286.          break;  /* Break out of while loop */
  15287.      /* More C statements here */
  15288.    }
  15289.    /* Execution continues here after break statement */
  15290.  
  15291.  
  15292.  The continue Statement
  15293.  
  15294.  The continue statement is the opposite of the break statement. It passes
  15295.  control to the next iteration of the smallest enclosing do, for, or while
  15296.  statement in which it appears.
  15297.  
  15298.  This statement is often used to return to the start of a loop from within a
  15299.  deeply nested loop.
  15300.  
  15301.  The following example illustrates continue:
  15302.  
  15303.    while( c != 'Q' )
  15304.    {
  15305.      /* Some C statements here*/
  15306.      if( c == 0x20 )
  15307.         continue;    /* Skip rest of loop */
  15308.      /* More C statements here */
  15309.    }
  15310.  
  15311.  In the example, the continue statement skips to the next iteration of the
  15312.  loop whenever  c  equals 0x20, the ASCII value for a space character.
  15313.  
  15314.  
  15315.  The do Statement
  15316.  
  15317.  The do statement repeats a statement until a specified expression becomes
  15318.  false. The test expression in the loop is evaluated after the body of the
  15319.  loop executes. Thus, the body of a do loop always executes at least once.
  15320.  
  15321.  Use a break, goto, or return statement when you need to exit a do loop
  15322.  early. Use the continue statement to terminate an iteration without exiting
  15323.  the loop. The continue statement passes control to the next iteration of the
  15324.  loop.
  15325.  
  15326.  The following example illustrates do:
  15327.  
  15328.    sample = 1;
  15329.    do
  15330.      printf( "%d\t%d\n", sample, sample * sample );
  15331.    while( ++x <= 7 );
  15332.  
  15333.  The printf statement in the example always executes at least once, no matter
  15334.  what value  x  has when the loop begins.
  15335.  
  15336.  
  15337.  The for Statement
  15338.  
  15339.  The for statement lets you repeat a statement a specified number of times.
  15340.  It consists of three expressions:
  15341.  
  15342.  
  15343.    ■   An initializing expression, which is evaluated when the loop begins
  15344.  
  15345.    ■   A test expression, which is evaluated before each iteration of the
  15346.        loop
  15347.  
  15348.    ■   A modifying expression, which is evaluated at the end of each
  15349.        iteration of the loop
  15350.  
  15351.  
  15352.  These expressions are enclosed in parentheses and followed by the loop
  15353.  body─the statement the loop is to execute. Each expression in the
  15354.  parentheses can be any legal C statement.
  15355.  
  15356.  The for statement works as follows:
  15357.  
  15358.  
  15359.    1.  The initializing expression is evaluated.
  15360.  
  15361.    2.  As long as the test expression evaluates to a nonzero value, the loop
  15362.        body is executed. When the test expression becomes 0, control passes
  15363.        to the statement following the loop body.
  15364.  
  15365.    3.  At the end of each iteration of the loop, the modifying expression is
  15366.        evaluated.
  15367.  
  15368.  
  15369.  You can use a break, goto, or return statement to exit a for loop early. Use
  15370.  the continue statement to terminate an iteration without exiting the for
  15371.  loop. The continue statement passes control to the next iteration of the
  15372.  loop.
  15373.  
  15374.  The following example illustrates for:
  15375.  
  15376.    for( counter = 0; counter < 100; counter++ )
  15377.    {
  15378.      x[counter] = 0; /* Set every array element to zero */
  15379.    }
  15380.  
  15381.  
  15382.  The goto Statement
  15383.  
  15384.  The goto statement performs a jump to the statement following the specified
  15385.  label. A goto statement can jump anywhere within the current function.
  15386.  
  15387.  A common use of goto is to exit immediately from a deeply nested loop. For
  15388.  instance:
  15389.  
  15390.    for( ... )
  15391.    {
  15392.       for( ... )
  15393.       {
  15394.          /* Do something here */
  15395.          if(c == CTRL_C)
  15396.             goto myplace;
  15397.       }
  15398.       /* Do something else here */
  15399.    }
  15400.  
  15401.    /* The goto label is named myplace */
  15402.    myplace:
  15403.    /* The goto statement transfers control here */
  15404.  
  15405.  
  15406.  The if Statement
  15407.  
  15408.  The if statement performs a branch based on the outcome of a conditional
  15409.  test. If the test expression is true, the body of the if statement executes.
  15410.  If it is false, the statement body is skipped.
  15411.  
  15412.  The else keyword is used with if to form an either-or construct that
  15413.  executes one statement when the test expression is true and another when
  15414.  it's false. C does not offer an "else-if" keyword. You can combine if and
  15415.  else statements to achieve the same effect. C pairs each else with the most
  15416.  recent if that lacks an else.
  15417.  
  15418.  Below is a simple if statement:
  15419.  
  15420.    if( score < 70 )
  15421.      grade = 'F';
  15422.    else
  15423.      grade = 'P';
  15424.  
  15425.  If the value of the variable  score  is less than 70, the variable  grade
  15426.  is set to the constant  F. Otherwise,  score  is set to  P.
  15427.  
  15428.  
  15429.  The return Statement
  15430.  
  15431.  The return statement ends the execution of the function in which it appears.
  15432.  It can also return a value to the calling function. For example:
  15433.  
  15434.    return;      /* End function and return no value */
  15435.  
  15436.    return myvariable; /* End function and return value of myvariable */
  15437.  
  15438.  
  15439.  The switch Statement
  15440.  
  15441.  The switch statement allows you to branch to various sections of code based
  15442.  on the value of a single variable. This variable must evaluate to a char,
  15443.  int, or long constant.
  15444.  
  15445.  Each section of code in the switch statement is marked with a case label─the
  15446.  keyword case followed by a constant or constant expression. The value of the
  15447.  switch test expression is compared to the constant in each case label. If a
  15448.  match is found, control transfers to the statement after the matching label
  15449.  and continues until you reach a break statement or the end of the switch
  15450.  statement.
  15451.  
  15452.  For example:
  15453.  
  15454.    switch( answer )
  15455.    {
  15456.      case 'y': /* First case */
  15457.         printf( "lowercase y\n" );
  15458.         break;
  15459.  
  15460.      case 'n': /* Another case */
  15461.         printf( "lowercase n\n" );
  15462.         break;
  15463.  
  15464.      default:  /* Default case */
  15465.         printf( "not a lowercase y or n\n" );
  15466.         break;
  15467.    }
  15468.  
  15469.  The example tests the value of the variable  answer. If  answer  evaluates
  15470.  to the constant  'y', control transfers to the first case in the switch
  15471.  statement. If it equals  'n', control transfers to the second case.
  15472.  
  15473.  A case labelled with the default keyword executes when none of the other
  15474.  case constants matches the value of the switch test expression. In the
  15475.  example, the default case executes when  answer  equals any value other than
  15476.   'y'  or  'n'.
  15477.  
  15478.  If you omit the break statement at the end of a case, execution falls
  15479.  through to the next case.
  15480.  
  15481.  If you omit the default case and no matching case is found, nothing in the
  15482.  switch statement executes.
  15483.  
  15484.  No two case constants in the same switch statement can have the same value.
  15485.  
  15486.  
  15487.  
  15488.  The while Statement
  15489.  
  15490.  The while statement repeats a statement until its test expression becomes
  15491.  false. A while loop evaluates its test expression before executing its loop
  15492.  body. If the test expression is false when the loop begins, the loop body
  15493.  never executes. (Contrast this behavior with the do loop, which always
  15494.  executes its loop body at least once.)
  15495.  
  15496.  For example:
  15497.  
  15498.    while( !sample )  /* Repeat until sample equals 1 */
  15499.    {
  15500.      printf( "%d\t%d\n", x, x*x );
  15501.      x += 6;
  15502.      if( x > 20 )
  15503.         sample = 1;
  15504.    }
  15505.  
  15506.  You can exit a while loop early with a break or goto statement. The continue
  15507.  statement skips to the next iteration of the loop.
  15508.  
  15509.  
  15510.  Data Types
  15511.  
  15512.  Data types are explained in Chapter 4, "Data Types," and Chapter 5,
  15513.  "Advanced Data Types." A brief description is given here.
  15514.  
  15515.  
  15516.  Basic Data Types
  15517.  
  15518.  The basic data types in C are character (char), integer (int), and floating
  15519.  point (float and double). All other data types are derived from these basic
  15520.  types. For example, a string is an array of char values.
  15521.  
  15522.  Table A.1 lists the range of values for each data type.
  15523.  
  15524.  Table A.1  Basic Data Types
  15525.  
  15526. ╓┌────────────────┌────────────────────────────┌─────────────────────────────╖
  15527.  Type Name        Other Names                  Range of Values
  15528.  ────────────────────────────────────────────────────────────────────────────
  15529.  char             signed char                  -128 to 127
  15530.  
  15531.  unsigned char    none                         0 to 255
  15532.  
  15533.  int              signed, signed int           -32,768 to 32,767
  15534.  
  15535.  unsigned         unsigned int                 0 to 65,535
  15536.  
  15537.  unsigned short   unsigned short int           0 to 65,535
  15538.  
  15539.  short            short int, signed short      -32,768 to
  15540.  
  15541.                   signed short int             32,767
  15542.  Type Name        Other Names                  Range of Values
  15543.  ────────────────────────────────────────────────────────────────────────────
  15544.                  signed short int             32,767
  15545.  
  15546.  long             long int, signed long        -2,147,483,647 to
  15547.  
  15548.                   signed long int              2,147,483,648
  15549.  
  15550.  unsigned long    unsigned long int            0 to 4,294,967,295
  15551.  
  15552.  _segment         none                         0 to 65,535
  15553.  
  15554.  enum             none                         -32,768 to 32,767
  15555.  
  15556.  float            none                         Approximately 1.2E-38 to
  15557.                                                3.4E+38 (7-digit precision)
  15558.  
  15559.  double           none                         Approximately 2.2E-308 to
  15560.                                                1.8E+308 (15-digit precision)
  15561.  
  15562.  long double      none                         Approximately 3.4E-4932 to
  15563.  Type Name        Other Names                  Range of Values
  15564.  ────────────────────────────────────────────────────────────────────────────
  15565. long double      none                         Approximately 3.4E-4932 to
  15566.                                                1.2E+4932 (19-digit
  15567.                                                precision)
  15568.  
  15569.  ────────────────────────────────────────────────────────────────────────────
  15570.  
  15571.  
  15572.  
  15573.  
  15574.  Character Type
  15575.  
  15576.  The character type (char) occupies one byte of storage and can express a
  15577.  whole number in the range of -128 to 127. Unsigned characters have a range
  15578.  of 0 to 255. You can represent any ASCII character as an unsigned char
  15579.  value.
  15580.  
  15581.  Typical declarations of character types are shown below:
  15582.  
  15583.    char answer; /* Declare a character variable answer */
  15584.  
  15585.    char alpha = 'a'; /* Declare character variable alpha
  15586.                         and initialize it */
  15587.  
  15588.  A character constant represents a single ASCII character. Typical character
  15589.  constants are shown below:
  15590.  
  15591.    char alpha = 'a'; /* Declare and initialize */
  15592.  
  15593.    char c2 = 0x61; /* Declare and initialize with
  15594.                       hexadecimal value for 'a' */
  15595.  
  15596.  Escape Sequences - Escape sequences represent special characters, such as
  15597.  the carriage return. An escape sequence consists of a backslash character
  15598.  plus a letter or punctuation mark. Table A.2 lists the C escape sequences;
  15599.  they are also listed in online help.
  15600.  
  15601.  Table A.2  C Escape Sequences
  15602.  
  15603. ╓┌──────────┌─────────────────────┌──────────────────────────────────────────╖
  15604.  Character  Meaning               Hexadecimal Value
  15605.  Character  Meaning               Hexadecimal Value
  15606.  ────────────────────────────────────────────────────────────────────────────
  15607.  \a         Alert (bell)          0x07
  15608.  \n         New line (linefeed)   0x0A
  15609.  \b         Backspace             0x08
  15610.  \r         Carriage return       0x0D
  15611.  \f         Formfeed              0x0C
  15612.  \t         Tab                   0x09
  15613.  \v         Vertical tab          0x0B
  15614.  \\         Backslash             0x5C
  15615.  \'         Single quote          0x27
  15616.  \"         Double quote          0x22
  15617.  \0         Null                  0x00
  15618.  ────────────────────────────────────────────────────────────────────────────
  15619.  
  15620.  
  15621.  
  15622.  Integer Type
  15623.  
  15624.  The integer (int) type occupies two bytes of storage and can express a whole
  15625.  number in the range -32,768 to 32,767. Unsigned integers (unsigned or
  15626.  unsigned int) have a range of 0 to 65,535.
  15627.  
  15628.  In QuickC, short integers (short or short int) are the same as integers
  15629.  (int). Note that the short and int types are not the same in some operating
  15630.  systems other than DOS.
  15631.  
  15632.  Signed long integers (long) occupy four bytes and have a range of
  15633.  -2,147,483,648 to 2,147,483,647. Unsigned long integers have a range of 0 to
  15634.  4,294,967,295.
  15635.  
  15636.  Integer variables are declared with the keywords int, short, unsigned, or
  15637.  long. Typical declarations of integer types are shown below:
  15638.  
  15639.    int z; /* Declare an int variable z */
  15640.  
  15641.    int ten = 10; /* Declare int variable and
  15642.                     assign it the value 10 */
  15643.  
  15644.    unsigned int a; /* Declare unsigned int variable */
  15645.  
  15646.    unsigned long BigInt = 2000000001UL; /* Declare and
  15647.                                            initialize */
  15648.  
  15649.  Integer constants are used to represent decimal, octal, and hexadecimal
  15650.  numbers. There are three types of integer constants:
  15651.  
  15652.  
  15653.    1.  Decimal constants can only contain the digits 0-9. The first digit
  15654.        must not be 0.
  15655.  
  15656.    2.  Octal constants can only contain the digits 0-7. The first digit must
  15657.        be 0.
  15658.  
  15659.    3.  Hexadecimal constants can only contain the digits 0-9, plus the
  15660.        letters a-f or A-F. The constant must begin with either 0x or 0X.
  15661.  
  15662.  
  15663.  You can specify that an integer constant is long by adding the suffix l or
  15664.  L. The suffix can be used with decimal, hexadecimal, or octal notation.
  15665.  
  15666.  To specify that an integer constant is short, add the suffix u or U. This
  15667.  suffix can also be used with decimal, hexadecimal, or octal notation.
  15668.  
  15669.  Typical integer constants are shown below:
  15670.  
  15671.    42    /* Decimal constant */
  15672.  
  15673.    0x34  /* Hexadecimal constant */
  15674.  
  15675.    0x3cL /* Long hexadecimal constant */
  15676.  
  15677.    052   /* Octal constant */
  15678.  
  15679.  
  15680.  Floating-Point Types
  15681.  
  15682.  You can declare floating-point variables using the keywords float or double.
  15683.  The float type occupies four bytes of storage and can express a
  15684.  floating-point value in the range 1.2E-38 to 3.4E+38. This type has
  15685.  seven-digit precision.
  15686.  
  15687.  The double type occupies eight bytes of storage and can express a
  15688.  floating-point value in the range 2.2E-308 to 1.8E+308. This type has
  15689.  fifteen-digit precision.
  15690.  
  15691.  The long double type occupies ten bytes of storage and can express a
  15692.  floating-point value in the range 3.4E-4932 to 1.2E+4932. This type has
  15693.  nineteen-digit precision.
  15694.  
  15695.  Typical declarations of floating-point types are shown below:
  15696.  
  15697.    float SmallPi = 3.14;  /* Declare floating-point variable */
  15698.  
  15699.    double AccuratePi = 3.141592653596  /* Declare
  15700.                                          double-precision */
  15701.  
  15702.  Floating-point constants can represent decimal numbers in either single or
  15703.  double precision. A floating-point constant must either contain a decimal
  15704.  point or end with the suffix e or E. Typical floating-point constants are
  15705.  shown below:
  15706.  
  15707.    2.78   /* Floating-point constant */
  15708.  
  15709.    3E     /* Floating-point constant */
  15710.  
  15711.  
  15712.  Aggregate Data Types
  15713.  
  15714.  Aggregate data types are built from one or more of the basic data types.
  15715.  These include the following:
  15716.  
  15717.  
  15718.    ■   Arrays (including strings)
  15719.  
  15720.    ■   Structures
  15721.  
  15722.    ■   Unions
  15723.  
  15724.  
  15725.  
  15726.  Arrays and Strings
  15727.  
  15728.  An "array" is a collection of data elements of a single type. An array can
  15729.  contain any data type. You can access an element of an array by using the
  15730.  array name and a numeric subscript.
  15731.  
  15732.  A "string" is an array of characters that terminates with the null character
  15733.  (\0). Arrays that contain strings must allow space for the final null
  15734.  character.
  15735.  
  15736.  Typical arrays and strings are shown below:
  15737.  
  15738.    int id_number[10]; /* One-dimensional;
  15739.                          10 elements; integer */
  15740.  
  15741.    char name[30]; /* String */
  15742.  
  15743.    float matrix[5][3]; /* Two-dimensional array,
  15744.                           5 rows, 3 columns */
  15745.  
  15746.    char baby[30] = "Peter Roddy"; /* String initialization */
  15747.  
  15748.  
  15749.  Structures
  15750.  
  15751.  A "structure" is a collection of data items of different types. Once you
  15752.  have defined a structure type, you can declare a structure variable using
  15753.  that type.
  15754.  
  15755.  The following example illustrates a simple structure:
  15756.  
  15757.    struct date
  15758.    {
  15759.      int month;
  15760.      int day;
  15761.      int year;
  15762.    }
  15763.  
  15764.    struct date today;
  15765.  
  15766.  The example defines a structure type named  date  and declares a structure
  15767.  variable  today  to be of type  date.
  15768.  
  15769.  Use the structure-member operator ( . ) to access the "elements" (members)
  15770.  of a structure. The name
  15771.  
  15772.    today.month
  15773.  
  15774.  refers to the  month  member of the  today  structure in the example.
  15775.  
  15776.  
  15777.  Unions
  15778.  
  15779.  A "union" is a set of data items of different types sharing the same storage
  15780.  space in memory. One use of unions is accessing the computer's DOS
  15781.  registers. For instance, QuickC defines the union REGS as the following:
  15782.  
  15783.    union REGS
  15784.    {
  15785.      struct WORDREGS x;
  15786.      struct BYTEREGS h;
  15787.    };
  15788.  
  15789.  
  15790.  Advanced Data Types
  15791.  
  15792.  Advanced data topics are explained in Chapter 5, "Advanced Data Types." A
  15793.  brief description of each topic is given here.
  15794.  
  15795.  
  15796.  Visibility
  15797.  
  15798.  Variables declared outside all functions are global and can be accessed
  15799.  anywhere in the current source file. Variables declared inside a function
  15800.  are local and can be accessed only in that function. Use the extern keyword
  15801.  to make a variable declared in another source file visible in the current
  15802.  source file.
  15803.  
  15804.  
  15805.  Lifetime
  15806.  
  15807.  Global variables, and local variables declared with the static keyword,
  15808.  exist for the lifetime of the program. Other local variables are
  15809.  "automatic;" they come into being when the function starts and evaporate
  15810.  when it ends.
  15811.  
  15812.  
  15813.  Type Conversions
  15814.  
  15815.  A type conversion occurs automatically when an expression mixes two
  15816.  different data types. QuickC converts the lower-ranking type to the
  15817.  higher-ranking type before it performs the specified operation.
  15818.  
  15819.  You can also "cast" (manually convert) a value to any type by placing the
  15820.  desired type name in parentheses in front of the value. The example below
  15821.  casts the value of  sample  to type float and assigns the value to  x:
  15822.  
  15823.    int sample;
  15824.    float x;
  15825.    x = (float)sample;
  15826.  
  15827.  
  15828.  User-Defined Types
  15829.  
  15830.  The typedef keyword allows you to create user-defined types, which are
  15831.  synonyms for existing data types. User-defined types can make your program
  15832.  more readable. For example, a type called  string  may be easier to
  15833.  understand than a type called char *.
  15834.  
  15835.  A simple typedef declaration is shown below. The name of an existing type
  15836.  (long int) is followed by the synonym  income.
  15837.  
  15838.    typedef long int income;
  15839.  
  15840.  Once you have created a new type name, you can use it wherever the original
  15841.  type name could be used:
  15842.  
  15843.    income net_income, gross_income;
  15844.  
  15845.  In the example above, the variables  net_income  and  gross_income  are of
  15846.  type  income, which is the same as long int.
  15847.  
  15848.  
  15849.  Enumerated Types
  15850.  
  15851.  An enumerated type (declared with enum) has values limited to a specified
  15852.  set. If the enum declaration does not specify any values, QuickC assigns
  15853.  sequential integers to the enumeration identifiers beginning at zero.
  15854.  
  15855.  The example below assigns the values of 0, 1, and 2 to the enumeration
  15856.  identifiers  zero,  one, and  two, respectively. It also creates an
  15857.  enumerated type  small_numbers  that can be used to declare other variables.
  15858.  
  15859.  
  15860.    /* Enumerated data type */
  15861.    enum small_numbers {zero, one, two};
  15862.  
  15863.    /* Variable my_numbers is of type small_numbers */
  15864.    enum small_numbers  my_numbers;
  15865.  
  15866.  The following example explicitly assigns values to the enumeration
  15867.  identifiers:
  15868.  
  15869.    /* Enumerated data type */
  15870.    enum even_numbers { two = 2, four = 4, six = 6 };
  15871.  
  15872.  
  15873.  Operators
  15874.  
  15875.  C-language operators are explained in Chapter 6, "Operators."
  15876.  
  15877.  An "operand" is a constant or variable manipulated by an operator in an
  15878.  expression. An "operator" specifies how the operands in an expression are to
  15879.  be evaluated. Operators also produce a result that can be nested within a
  15880.  larger expression.
  15881.  
  15882.  C provides a rich set of operators covering everything from basic arithmetic
  15883.  operations to logical and bitwise operations. You can also combine the
  15884.  assignment operator (=) with any arithmetic or bitwise operator to form a
  15885.  combined assignment operator.
  15886.  
  15887.  C operators have two properties, precedence and associativity. You can
  15888.  change the normal order of evaluation by enclosing expressions in
  15889.  parentheses.
  15890.  
  15891.  Table A.3 lists the C operators and their precedence and associativity
  15892.  values. The lines in the table separate precedence levels. The highest
  15893.  precedence level is at the top of the table.
  15894.  
  15895.  Table A.3  C Operators
  15896.  
  15897. ╓┌───────────────────────┌────────────────────────────────────┌──────────────╖
  15898.  Symbol                  Name or Meaning                      Associativity
  15899.  Symbol                  Name or Meaning                      Associativity
  15900.  ────────────────────────────────────────────────────────────────────────────
  15901.  ( )                     Function call                        Left to right
  15902.  
  15903.  [ ]                     Array element
  15904.  
  15905.  .                       Structure or union
  15906.                          member
  15907.  
  15908.  ->                      Pointer to structure
  15909.                          member
  15910.  
  15911.  ────────────────────────────────────────────────────────────────────────────
  15912.  
  15913.  - -                     Decrement                            Right to left
  15914.  
  15915.  ++                      Increment
  15916.  
  15917.  ────────────────────────────────────────────────────────────────────────────
  15918.  
  15919.  :>                      Base operator                        Left to right
  15920.  Symbol                  Name or Meaning                      Associativity
  15921.  ────────────────────────────────────────────────────────────────────────────
  15922. :>                      Base operator                        Left to right
  15923.  
  15924.  ────────────────────────────────────────────────────────────────────────────
  15925.  
  15926.  !                       Logical NOT                          Right to left
  15927.  
  15928.  ~                       One's complement
  15929.  
  15930.  -                       Unary minus
  15931.  
  15932.  +                       Unary plus
  15933.  
  15934.  &                       Address
  15935.  
  15936.  *                       Indirection
  15937.  
  15938.  sizeof                  Size in bytes
  15939.  
  15940.  (type)                  Type cast [for example, (float) i]
  15941.  Symbol                  Name or Meaning                      Associativity
  15942.  ────────────────────────────────────────────────────────────────────────────
  15943. (type)                  Type cast [for example, (float) i]
  15944.  
  15945.  ────────────────────────────────────────────────────────────────────────────
  15946.  
  15947.  *                       Multiply                             Left to right
  15948.  
  15949.  /                       Divide
  15950.  
  15951.  %                       Modulus (remainder)
  15952.  
  15953.  ────────────────────────────────────────────────────────────────────────────
  15954.  
  15955.  +                       Add                                  Left to right
  15956.  
  15957.  -                       Subtract
  15958.  
  15959.  ────────────────────────────────────────────────────────────────────────────
  15960.  
  15961.  <<                      Left shift                           Left to right
  15962.  Symbol                  Name or Meaning                      Associativity
  15963.  ────────────────────────────────────────────────────────────────────────────
  15964. <<                      Left shift                           Left to right
  15965.  
  15966.  >>                      Right shift
  15967.  
  15968.  ────────────────────────────────────────────────────────────────────────────
  15969.  
  15970.  <                       Less than                            Left to right
  15971.  
  15972.  <=                      Less than or equal to
  15973.  
  15974.  >                       Greater than
  15975.  
  15976.  >=                      Greater than or equal to
  15977.  
  15978.  ────────────────────────────────────────────────────────────────────────────
  15979.  
  15980.  ==                      Equal                                Left to right
  15981.  
  15982.  !=                      Not equal
  15983.  Symbol                  Name or Meaning                      Associativity
  15984.  ────────────────────────────────────────────────────────────────────────────
  15985. !=                      Not equal
  15986.  
  15987.  ────────────────────────────────────────────────────────────────────────────
  15988.  
  15989.  &                       Bitwise AND                          Left to right
  15990.  
  15991.  ────────────────────────────────────────────────────────────────────────────
  15992.  
  15993.  ^                       Bitwise exclusive OR                 Left to right
  15994.  
  15995.  ────────────────────────────────────────────────────────────────────────────
  15996.  
  15997.  |                       Bitwise OR                           Left to right
  15998.  
  15999.  ────────────────────────────────────────────────────────────────────────────
  16000.  
  16001.  &&                      Logical AND                          Left to right
  16002.  
  16003.  ────────────────────────────────────────────────────────────────────────────
  16004.  Symbol                  Name or Meaning                      Associativity
  16005.  ────────────────────────────────────────────────────────────────────────────
  16006. ────────────────────────────────────────────────────────────────────────────
  16007.  
  16008.  ||                      Logical OR                           Left to right
  16009.  
  16010.  ────────────────────────────────────────────────────────────────────────────
  16011.  
  16012.  ? :                     Conditional                          Right to left
  16013.  
  16014.  ────────────────────────────────────────────────────────────────────────────
  16015.  
  16016.  =                       Assignment                           Right to left
  16017.  
  16018.  *=, /=, %=, +=, -=      Compound assignment
  16019.  
  16020.  <<=, >>=,  &=, ^=, |=
  16021.  
  16022.  ────────────────────────────────────────────────────────────────────────────
  16023.  
  16024.  ,                       Comma                                Left to right
  16025.  Symbol                  Name or Meaning                      Associativity
  16026.  ────────────────────────────────────────────────────────────────────────────
  16027. ,                       Comma                                Left to right
  16028.  
  16029.  ────────────────────────────────────────────────────────────────────────────
  16030.  
  16031.  
  16032.  
  16033.  
  16034.  Preprocessor Directives
  16035.  
  16036.  Preprocessor directives are explained in Chapter 7, "Preprocessor
  16037.  Directives."
  16038.  
  16039.  A "preprocessor directive" is a command to the QuickC compiler, which
  16040.  processes all such commands before it compiles your source program. A
  16041.  preprocessor directive begins with the # symbol, followed by the directive
  16042.  and any arguments the directive needs. Since a preprocessor directive is not
  16043.  a C language statement, it doesn't end in a semicolon.
  16044.  
  16045.  The two most commonly used directives are #define and #include. Use the
  16046.  #define directive to give a meaningful name to some constant in your
  16047.  program. The following directive tells QuickC to replace  PI  with  3.14159
  16048.  everywhere in the source program:
  16049.  
  16050.    #define PI  3.14159
  16051.  
  16052.  The #include directive below tells QuickC to insert the contents of a
  16053.  specified file at the current location in your source program.
  16054.  
  16055.    #include <stdio.h> /* Standard header file */
  16056.  
  16057.  Such files are called "include files" or "header files." Standard header
  16058.  files, such as STDIO.H, end with the .H extension and contain function
  16059.  prototypes and other definitions needed for QuickC library routines.
  16060.  
  16061.  Table A.4 lists and describes the QuickC standard header files. Consult
  16062.  online help for information on the header files needed by individual library
  16063.  functions.
  16064.  
  16065.  Table A.4  QuickC Header Files
  16066.  
  16067. ╓┌─────────────────────────────────┌─────────────────────────────────────────╖
  16068.  File Name                         Major Contents
  16069.  ────────────────────────────────────────────────────────────────────────────
  16070.  ASSERT.H                          assert debugging macro
  16071.  
  16072.  BIOS.H                            BIOS service functions
  16073.  
  16074.  CONIO.H                           Console and port I/O routines
  16075.  
  16076.  CTYPE.H                           Character classification
  16077.  
  16078.  DIRECT.H                          Directory control
  16079.  
  16080.  DOS.H                             MS-DOS interface functions
  16081.  
  16082.  ERRNO.H                           System-wide error numbers
  16083.  
  16084.  FCNTL.H                           Flags used in open and sopen functions
  16085.  
  16086.  FLOAT.H                           Constants needed by math functions
  16087.  
  16088.  File Name                         Major Contents
  16089.  ────────────────────────────────────────────────────────────────────────────
  16090. 
  16091.  GRAPH.H                           Low-level graphics and font routines
  16092.  
  16093.  IO.H                              File-handling and low-level I/O
  16094.  
  16095.  LIMITS.H                          Ranges of integers and character types
  16096.  
  16097.  LOCALE.H                          Internationalization functions
  16098.  
  16099.  MALLOC.H                          Memory-allocation functions
  16100.  
  16101.  MATH.H                            Floating-point math routines
  16102.  
  16103.  MEMORY.H                          Buffer-manipulation routines
  16104.  
  16105.  PGCHART.H                         Presentation graphics
  16106.  
  16107.  PROCESS.H                         Process-control routines
  16108.  
  16109.  File Name                         Major Contents
  16110.  ────────────────────────────────────────────────────────────────────────────
  16111. 
  16112.  SEARCH.H                          Searching and sorting functions
  16113.  
  16114.  SETJMP.H                          setjmp and longjmp functions
  16115.  
  16116.  SHARE.H                           Flags used in sopen
  16117.  
  16118.  SIGNAL.H                          Constants used by signal function
  16119.  
  16120.  STDARG.H                          Macros used to access variable-length
  16121.                                    argument-list functions
  16122.  
  16123.  STDDEF.H                          Commonly used data types and values
  16124.  
  16125.  STDIO.H                           Standard I/O header file
  16126.  
  16127.  STDLIB.H                          Commonly used library functions
  16128.  
  16129.  STRING.H                          String-manipulation functions
  16130.  File Name                         Major Contents
  16131.  ────────────────────────────────────────────────────────────────────────────
  16132. STRING.H                          String-manipulation functions
  16133.  
  16134.  TIME.H                            General time functions
  16135.  
  16136.  VARARGS.H                         Variable-length argument-list functions
  16137.  
  16138.  SYS\LOCKING.H                     Flags used by locking function
  16139.  
  16140.  SYS\STAT.H                        File-status structures and functions
  16141.  
  16142.  SYS\TIMEB.H                       time function
  16143.  
  16144.  SYS\TYPES.H                       File-status and time types
  16145.  
  16146.  SYS\UTIME.H                       utime function
  16147.  
  16148.  ────────────────────────────────────────────────────────────────────────────
  16149.  
  16150.  
  16151.  
  16152.  
  16153.  Pointers
  16154.  
  16155.  Pointers are described in Chapter 8, "Pointers," and Chapter 9, "Advanced
  16156.  Pointers."
  16157.  
  16158.  A "pointer" is a variable that contains the memory address of an item rather
  16159.  than its value. A pointer can point to any type of data item or to a
  16160.  function. The following code illustrates pointer declarations:
  16161.  
  16162.    int *intptr; /* Pointer to an integer */
  16163.    char *name; /* Pointer to char */
  16164.  
  16165.  The following operators are used with pointers:
  16166.  
  16167.  
  16168.    ■   The indirection operator (*) has two uses. In a declaration, it means
  16169.        that the declared item is a pointer. In an expression, it denotes the
  16170.        data being pointed to.
  16171.  
  16172.    ■   The address-of operator (&) yields the memory address at which an item
  16173.        is stored.
  16174.  
  16175.  
  16176.  You can perform four arithmetic operations on pointers:
  16177.  
  16178.  
  16179.    1.  Adding a pointer and an integer
  16180.  
  16181.    2.  Subtracting an integer from a pointer
  16182.  
  16183.    3.  Subtracting two pointers
  16184.  
  16185.    4.  Comparing two pointers
  16186.  
  16187.  
  16188.  Pointer arithmetic operations are automatically scaled by the size of the
  16189.  object pointed to. For instance, adding 1 to a pointer to a float item
  16190.  causes the address stored in the pointer to be incremented four bytes, the
  16191.  size of one float item.
  16192.  
  16193.  QuickC 2.5 also supports based pointers, a highly advanced feature, that are
  16194.  compatible with Microsoft C version 6.0. Please refer to your C 6.0
  16195.  documentation for more information about based pointers and objects.
  16196.  
  16197.  
  16198.  
  16199.  
  16200.  
  16201.  
  16202.  Appendix B  C Library Guide
  16203.  ────────────────────────────────────────────────────────────────────────────
  16204.  
  16205.  This appendix outlines the features of the C run-time library provided with
  16206.  QuickC. It does not intend to be a complete presentation of the complete C
  16207.  run-time library. Instead, this appendix presents the most fundamental
  16208.  routines, grouped by category so you can begin experimenting with C and with
  16209.  QuickC.
  16210.  
  16211.  Remember, use online help to get instant help on any topic of interest. The
  16212.  online help system provided with QuickC provides complete reference
  16213.  information for all C library functions, keywords, and preprocessor
  16214.  directives.
  16215.  
  16216.  
  16217.  Overview of the C Run-Time Library
  16218.  
  16219.  At last count, the C run-time library contained over 400 functions to use in
  16220.  C programs. This appendix describes the major categories of functions
  16221.  included in the library and, within those categories, the fundamental
  16222.  routines every C programmer should know.
  16223.  
  16224.  The discussions of these categories give only a brief overview of the
  16225.  capabilities of the run-time library. You can find a complete description of
  16226.  the syntax and use of each routine in online help.
  16227.  
  16228.  The routines in the C run-time library are divided into the following
  16229.  categories:
  16230.  
  16231.  Table B.1  C Run-Time Library Routines
  16232.  
  16233. ╓┌───────────────────────────────┌──────────────────────────────────┌────────╖
  16234.  Category                        Function Routines                  Page
  16235.  Category                        Function Routines                  Page
  16236.  ────────────────────────────────────────────────────────────────────────────
  16237.  Buffer Manipulation             memchr, memcmp, memcpy, memmove,   345
  16238.                                  memset
  16239.  
  16240.  ────────────────────────────────────────────────────────────────────────────
  16241.  
  16242.  Character Classification        isalnum, isalpha, isascii,         346
  16243.  and Conversion                  iscntrl, isdigit, isgraph,
  16244.                                  islower, isprint, ispunct,
  16245.                                  isspace, isupper, isxdigit,
  16246.                                  tolower, toupper
  16247.  
  16248.  ────────────────────────────────────────────────────────────────────────────
  16249.  
  16250.  Data Conversion                 atof, atoi, atol, itoa, ltoa,      348
  16251.                                  ultoa, strtod, strtol, strtoul
  16252.  
  16253.  ────────────────────────────────────────────────────────────────────────────
  16254.  
  16255.  Error Message                   assert, perror, strerror,          349
  16256.  Category                        Function Routines                  Page
  16257.  ────────────────────────────────────────────────────────────────────────────
  16258. Error Message                   assert, perror, strerror,          349
  16259.                                  _strerror
  16260.  
  16261.  ────────────────────────────────────────────────────────────────────────────
  16262.  
  16263.  Graphics 1: Low-Level                                              350
  16264.                       Graphics
  16265.  
  16266.  Configure Mode and              _displaycursor, _getvideoconfig,   351
  16267.     Environment                  _setvideomode
  16268.  
  16269.  Set Coordinates                 _getcurrentposition,               352
  16270.                                  _getphyscoord,_getviewcoord,
  16271.                                  _getwindowcoord,
  16272.                                  _setcliprgn,_setvieworg,
  16273.                                  _setviewport, _setwindow
  16274.  
  16275.  Set Palette                     _remapallpalette, remappallette,   354
  16276.                                  _selectpalette
  16277.  Category                        Function Routines                  Page
  16278.  ────────────────────────────────────────────────────────────────────────────
  16279.                                 _selectpalette
  16280.  
  16281.  Set Attributes                  _getbkcolor, _getcolor,            355
  16282.                                  _setbkcolor, _setcolor
  16283.  
  16284.  Output Images                   _arc, _clearscreen, _ellipse,      356
  16285.                                  _floodfill, _getpixel,
  16286.                                  _lineto, _moveto, _pie,
  16287.                                  _rectangle, _setpixel
  16288.  
  16289.  Output Text                     _displaycursor, _gettextcolor,     359
  16290.                                  _gettextcursor,
  16291.                                  _gettextposition, _outtext,
  16292.                                  _settextposition,
  16293.                                  _settextcolor, _settextwindow
  16294.  
  16295.  Transfer Images                 _getimage, _imagesize, _putimage   361
  16296.  
  16297.  ────────────────────────────────────────────────────────────────────────────
  16298.  Category                        Function Routines                  Page
  16299.  ────────────────────────────────────────────────────────────────────────────
  16300. ────────────────────────────────────────────────────────────────────────────
  16301.  
  16302.  Graphics 2: Presentation        _pg_chart, _pg_chartms,            362
  16303.                       Graphics   _pg_chartpie, _pg_chartscatter,
  16304.                                  _pg_chartscatterms,
  16305.                                  _pg_defaultchart, _pg_initchart
  16306.  
  16307.  ────────────────────────────────────────────────────────────────────────────
  16308.  
  16309.  Graphics 3: Font Display        _getfontinfo, _getgtextextent,     365
  16310.                                  _outgtext, _registerfonts,
  16311.                                  _setfont, _unregisterfonts
  16312.  
  16313.  ────────────────────────────────────────────────────────────────────────────
  16314.  
  16315.  Input and Output                                                   367
  16316.  
  16317.  Stream Routines                 clearerr, fclose, feof, ferror,    367
  16318.                                  fflush, fgetc, fgetpos, fgets,
  16319.  Category                        Function Routines                  Page
  16320.  ────────────────────────────────────────────────────────────────────────────
  16321.                                 fflush, fgetc, fgetpos, fgets,
  16322.                                  fopen, fprintf, fputc, fputs,
  16323.                                  fread, freopen, fscanf, fseek,
  16324.                                  fsetpos, ftell, fwrite, getc,
  16325.                                  getchar, gets, printf, putc,
  16326.                                  putchar, puts, rewind, scanf,
  16327.                                  sprintf, sscanf, tmpfile, tmpnam,
  16328.                                  ungetc
  16329.  
  16330.  Low-Level Routines              close, creat, eof, lseek, open,    373
  16331.                                  read, tell, write
  16332.  
  16333.  Console and Port                cgets, cprintf, cputs, cscanf,     375
  16334.     I/O Routines                 getch, getche, kbhit,
  16335.                                  putch, ungetch
  16336.  
  16337.  ────────────────────────────────────────────────────────────────────────────
  16338.  
  16339.  Math                            abs, fabs, labs, acos, asin, atan,  377
  16340.  Category                        Function Routines                  Page
  16341.  ────────────────────────────────────────────────────────────────────────────
  16342. Math                            abs, fabs, labs, acos, asin, atan,  377
  16343.                                  atan2, ceil, cos, cosh,
  16344.                                  exp, floor, fmod, frexp, ldexp,
  16345.                                  log, log10, modf, pow, rand,
  16346.                                  srand, sin, sinh, sqrt, tan, tanh
  16347.  
  16348.  ────────────────────────────────────────────────────────────────────────────
  16349.  
  16350.  Memory Allocation               calloc, free, _ffree, hfree,       381
  16351.                                  _nfree, malloc, _fmalloc,
  16352.                                  _nmalloc, realloc
  16353.  
  16354.  ────────────────────────────────────────────────────────────────────────────
  16355.  
  16356.  Process Control                 abort, atexit, exit, _exit,        383
  16357.                                  system
  16358.  
  16359.  ────────────────────────────────────────────────────────────────────────────
  16360.  
  16361.  Category                        Function Routines                  Page
  16362.  ────────────────────────────────────────────────────────────────────────────
  16363. 
  16364.  Searching and Sorting           bsearch, lfind, lsearch, qsort     384
  16365.  
  16366.  ────────────────────────────────────────────────────────────────────────────
  16367.  
  16368.  String Manipulation             strcat, strcpy, strdup, strncat,   385
  16369.                                  strncpy, strchr,
  16370.                                  strcspn, strpbrk, strrchr, strspn,
  16371.                                  strstr, strcmp,
  16372.                                  strcmpi, stricmp, strncmp,
  16373.                                  strnicmp, strlen, strlwr,
  16374.                                  strupr, strnset, strset, strtok
  16375.  
  16376.  ────────────────────────────────────────────────────────────────────────────
  16377.  
  16378.  Time                            asctime, clock, ctime, difftime,   389
  16379.                                  ftime, gmtime,
  16380.                                  mktime, time
  16381.  
  16382.  Category                        Function Routines                  Page
  16383.  ────────────────────────────────────────────────────────────────────────────
  16384. 
  16385.  ────────────────────────────────────────────────────────────────────────────
  16386.  
  16387.  
  16388.  
  16389.  
  16390.  Buffer-Manipulation Routines
  16391.  
  16392.  Buffer manipulation routines are used with areas of memory on a
  16393.  character-by-character basis. Buffers are arrays of characters (bytes).
  16394.  Unlike strings, however, they are not usually terminated with a null
  16395.  character (\0).
  16396.  
  16397.  memchr - Returns a pointer to the first occurrence, within a specified
  16398.  number of characters, of a given character in the buffer.
  16399.  
  16400.  Include                           STRING.H
  16401.  
  16402.  Prototype                         void *memchr( const void *buf,  int c,
  16403.                                    size_t count );
  16404.  
  16405.  Arguments                         buf         Pointer to buffer
  16406.  
  16407.                                    c           Character to copy
  16408.  
  16409.                                    count       Number of characters
  16410.  
  16411.  Returns                           A pointer to the location of c in buf
  16412.                                    if successful;
  16413.  
  16414.                                    NULL if c is not within first count
  16415.                                    bytes  of buf
  16416.  
  16417.  ────────────────────────────────────────────────────────────────────────────
  16418.  memcmp - Compares a specified number of characters from two buffers.
  16419.  
  16420.  Include                           STRING.H
  16421.  
  16422.  Prototype                         int memcmp( const void *buf1,  const
  16423.                                    void *buf2, size_t count );
  16424.  
  16425.  Arguments                         buf1        First buffer
  16426.  
  16427.                                    buf2        Second buffer
  16428.  
  16429.                                    count       Number of characters
  16430.  
  16431.  Returns                           A negative value if buf1 < buf2,  0 if
  16432.                                    buf1 = buf2,
  16433.  
  16434.                                    a positive value if buf1 > buf2
  16435.  
  16436.  ────────────────────────────────────────────────────────────────────────────
  16437.  memcpy - Copies a specified number of characters from one buffer to another.
  16438.  
  16439.  Include                           STRING.H
  16440.  
  16441.  Prototype                         void *memcpy( void *dest,  const void *
  16442.                                    src, size_t count );
  16443.  
  16444.  Arguments                         dest        New buffer
  16445.  
  16446.                                    src         Buffer to copy from
  16447.  
  16448.                                    count       Number of characters to copy
  16449.  
  16450.  Returns                           A pointer to dest
  16451.  
  16452.  ────────────────────────────────────────────────────────────────────────────
  16453.  memmove - Copies a specified number of characters from one buffer to
  16454.  another. When the source and target areas overlap, the memmove function is
  16455.  guaranteed to properly copy the full source.
  16456.  
  16457.  Include                           STRING.H
  16458.  
  16459.  Prototype                         void *memmove( void *dest,  const void *
  16460.                                    src, size_t count );
  16461.  
  16462.  Arguments                         dest        Target object
  16463.  
  16464.                                    src         Source object
  16465.  
  16466.                                    count       Number of characters to copy
  16467.  
  16468.  Returns                           The value of dest
  16469.  
  16470.  ────────────────────────────────────────────────────────────────────────────
  16471.  memset - Uses a given character to initialize a specified number of bytes in
  16472.  the buffer.
  16473.  
  16474.  Include                           STRING.H
  16475.  
  16476.  Prototype                         void *memset( void *dest,  int c, size_t
  16477.                                    count );
  16478.  
  16479.  Arguments                         dest        Pointer to destination
  16480.  
  16481.                                    c           Character to set
  16482.  
  16483.                                    count       Number of characters
  16484.  
  16485.  Returns                           A pointer to dest
  16486.  
  16487.  
  16488.  Character Classification and Conversion Routines
  16489.  
  16490.  The classification routines (is...) test a character and return a one (1) if
  16491.  the character is in the set that the routine is testing for. The conversion
  16492.  routines (to...) convert characters between uppercase and lowercase. These
  16493.  routines are generally faster than writing a test expression such as the
  16494.  following:
  16495.  
  16496.    if ((c >= 0) || c <= 0x7f))
  16497.  
  16498.  ────────────────────────────────────────────────────────────────────────────
  16499.  isalnum, isalpha, isascii, iscntrl, isdigit, isgraph, islower, isprint,
  16500.  ispunct, isspace, isupper, isxdigit These routines test a character for a
  16501.  specified condition and return a nonzero value if the condition is true. -
  16502.  
  16503.  Include                           CTYPE.H
  16504.  
  16505.  Prototypes                        int isalnum( int c );  (alphanumeric
  16506.                                    character: A-Z, a-z, 0-9)
  16507.  
  16508.  
  16509.  
  16510.                                    int isalpha( int c );   (alphabetic
  16511.                                    character: A-Z,  a-z)
  16512.  
  16513.  
  16514.  
  16515.                                    int isascii( int c );     (ASCII
  16516.                                    character: 0x00-0x7F)
  16517.  
  16518.  
  16519.  
  16520.                                    int iscntrl( int c );    (control
  16521.                                    character: 0x00-0x1F,  0x7F)
  16522.  
  16523.  
  16524.  
  16525.                                    int isdigit( int c );     (decimal
  16526.                                    digit: 0-9)
  16527.  
  16528.  
  16529.  
  16530.                                    int isgraph( int c );   (printable
  16531.                                    character, not space:  0x21-0x7E)
  16532.  
  16533.  
  16534.  
  16535.                                    int islower( int c );   (lowercase
  16536.                                    letter: a-z)
  16537.  
  16538.  
  16539.  
  16540.                                    int isprint( int c );    (printable
  16541.                                    character: 0x20-0x7E)
  16542.  
  16543.  
  16544.  
  16545.                                    int ispunct( int c );   (punctuation
  16546.                                    character)
  16547.  
  16548.  
  16549.  
  16550.                                    int isspace( int c );    (white-space
  16551.                                    character:  0x09-0x0D, 0x20)
  16552.  
  16553.  
  16554.  
  16555.                                    int isupper( int c );   (uppercase
  16556.                                    letter: A-Z)
  16557.  
  16558.  
  16559.  
  16560.                                    int isxdigit( int c );   (hexadecimal
  16561.                                    digit: A-F,  a-f, 0-9)
  16562.  
  16563.  Argument                          c           Character to be tested
  16564.  
  16565.  Returns                           A nonzero value if the condition is true
  16566.  
  16567.  ────────────────────────────────────────────────────────────────────────────
  16568.  tolower, toupper - These routines accept a character argument and return a
  16569.  converted character. The tolower and toupper routines are also implemented
  16570.  as functions. To use the function versions, you must do the following:
  16571.  
  16572.  
  16573.    ■   Include CTYPE.H if necessary for other macro definitions
  16574.  
  16575.    ■   If CTYPE.H is included, give #undef directives for tolower and toupper
  16576.  
  16577.    ■   Include STDLIB.H (which contains the function prototypes)
  16578.  
  16579.  
  16580.  Include                           CTYPE.H
  16581.  
  16582.  Prototypes                        int tolower( int c );
  16583.  
  16584.  
  16585.  
  16586.                                    int toupper( int c );
  16587.  
  16588.  Argument                          c           Character to be converted
  16589.  
  16590.  Returns                           tolower: the lowercase equivalent of c
  16591.                                    only if c is an uppercase letter
  16592.  
  16593.                                    toupper: the uppercase equivalent of c
  16594.                                    only if c  is a lowercase letter
  16595.  
  16596.  
  16597.  Data Conversion Routines
  16598.  
  16599.  The data conversion routines convert numbers to strings of ASCII characters
  16600.  and vice versa.
  16601.  
  16602.  ────────────────────────────────────────────────────────────────────────────
  16603.  atof, atoi, atol - These ASCII-to-number routines convert an ASCII string to
  16604.  a float, an integer, and a long, respectively.
  16605.  
  16606.  Include                           STDLIB.H or MATH.H (atof)
  16607.  
  16608.                                    STDLIB.H (atoi, atol)
  16609.  
  16610.  Prototypes                        double atof( const char *string  );
  16611.  
  16612.  
  16613.  
  16614.                                    int atoi( const char *string );
  16615.  
  16616.  
  16617.  
  16618.                                    long atol( const char *string );
  16619.  
  16620.  Argument                          string      String to be converted
  16621.  
  16622.  Returns                           The converted string, or 0 if string
  16623.                                    cannot  be converted
  16624.  
  16625.  ────────────────────────────────────────────────────────────────────────────
  16626.  itoa, ltoa, ultoa - These number-to-ASCII routines convert an integer, a
  16627.  long value, or an unsigned long value to an ASCII string.
  16628.  
  16629.  Include                           STDLIB.H
  16630.  
  16631.  Prototypes                        char * itoa( int value, char  *string,
  16632.                                    int radix );
  16633.  
  16634.  
  16635.  
  16636.                                    char * ltoa( long value, char *string,
  16637.                                    int radix );
  16638.  
  16639.  
  16640.  
  16641.                                    char * ultoa( unsigned long value, char
  16642.                                    *string,  int radix );
  16643.  
  16644.  Arguments                         value       Number to be converted
  16645.  
  16646.                                    string      String result
  16647.  
  16648.                                    radix       Number base of value
  16649.  
  16650.  Returns                           A pointer to string; there is no error
  16651.                                    return
  16652.  
  16653.  ────────────────────────────────────────────────────────────────────────────
  16654.  strtod, strtol, strtoul - These routines convert a string to a double, a
  16655.  long, and an unsigned long, respectively.
  16656.  
  16657.  Include                           STDLIB.H
  16658.  
  16659.  Prototypes                        double strtod( const char *nptr,  char
  16660.                                    **endptr );
  16661.  
  16662.  
  16663.  
  16664.                                    long strtol( const char *nptr, char **
  16665.                                    endptr,  int base );
  16666.  
  16667.  
  16668.  
  16669.                                    unsigned long strtoul( const char *nptr,
  16670.                                    char **endptr,  int base );
  16671.  
  16672.  Arguments                         nptr        String to convert
  16673.  
  16674.                                    endptr      End of scan
  16675.  
  16676.                                    base        Number base to use
  16677.  
  16678.  Returns                           strtod: the converted value; overflow
  16679.                                    returns  HUGE_VAL,
  16680.  
  16681.                                    underflow returns 0
  16682.  
  16683.                                    strtol: the converted value; overflow
  16684.                                    returns LONG_MAX
  16685.  
  16686.                                    or LONG_MIN, depending on sign of
  16687.                                    converted  value
  16688.  
  16689.                                    strtoul: the converted value if
  16690.                                    successful, 0 if not, and
  16691.  
  16692.                                    ULONG_MAX on overflow
  16693.  
  16694.  
  16695.  Error Message Routines
  16696.  
  16697.  The routines in this category handle the display of error messages.
  16698.  
  16699.  The assert macro is typically used to test for program logic errors; it
  16700.  prints a message when a given "assertion" fails to hold true. Defining the
  16701.  identifier NDEBUG to any value causes occurrences of assert to be disabled
  16702.  in the source file, thus allowing you to turn off assertion checking without
  16703.  modifying the source file.
  16704.  
  16705.  The perror routine prints the system-error message, along with a
  16706.  user-supplied message, for the last system-level call that produced an
  16707.  error. The perror routine is declared in the include files STDLIB.H and
  16708.  STDIO.H. The error number is obtained from the errno variable. The system
  16709.  message is taken from the sys_errlist array.
  16710.  
  16711.  The strerror and _strerror routines store error messages in a string.
  16712.  
  16713.  ────────────────────────────────────────────────────────────────────────────
  16714.  assert - Tests for logic error.
  16715.  
  16716.  Include                           ASSERT.H, STDIO.H
  16717.  
  16718.  Prototype                         void assert( expression );
  16719.  
  16720.  Argument                          expression  Expression to test
  16721.  
  16722.  Returns                           Void
  16723.  
  16724.  ────────────────────────────────────────────────────────────────────────────
  16725.  perror - Prints error message.
  16726.  
  16727.  Include                           STDIO.H
  16728.  
  16729.  Prototypes                        void perror( const char *string  );
  16730.  
  16731.                                    int errno;
  16732.  
  16733.                                    int sys_nerr;
  16734.  
  16735.                                    char *sys_errlist [sys_nerr];
  16736.  
  16737.  Arguments                         string      User-supplied message
  16738.  
  16739.                                    errno       Error number
  16740.  
  16741.                                    sys_nerr    Number of system-error
  16742.                                                messages
  16743.  
  16744.                                    sys_errlis  Array of error messages
  16745.                                    t
  16746.  
  16747.  Returns                           Void
  16748.  
  16749.  ────────────────────────────────────────────────────────────────────────────
  16750.  strerror, _strerror  - Saves system-error message and optional user-error
  16751.  message in string. The routine strerror is the ANSI-compatible version.
  16752.  
  16753.  Include                           STRING.H
  16754.  
  16755.  Prototypes                        char *strerror( int errnum  );
  16756.  
  16757.                                    char *_strerror( char *string );
  16758.  
  16759.                                    int errno;
  16760.  
  16761.                                    int sys_nerr;
  16762.  
  16763.                                    char *sys_errlist [sys_nerr];
  16764.  
  16765.  Arguments                         errnum      Error number
  16766.  
  16767.                                    string      User-supplied message
  16768.  
  16769.                                    errno       Error number
  16770.  
  16771.                                    sys_nerr    Number of system-error
  16772.                                                messages
  16773.  
  16774.                                    sys_errlis  Array of error messages
  16775.                                    t
  16776.  
  16777.  Returns                           A pointer to the error-message string
  16778.  
  16779.  
  16780.  Graphics 1: Low-Level Graphics Routines
  16781.  
  16782.  The low-level graphics routines provide line, figure, and pixel manipulation
  16783.  capabilities. The routines for presentation graphics are described in the
  16784.  next section. The routines for displaying fonts follow the presentation
  16785.  graphics section.
  16786.  
  16787.  The graphics package supports the IBM(R) (and compatible) Enhanced Graphics
  16788.  Adapter (EGA), Color Graphics Adapter (CGA), certain operating modes of the
  16789.  Video Graphics Array (VGA) hardware configurations, and the MCGA (Multicolor
  16790.  Graphics Array). The graphics package also supports the Hercules Graphics
  16791.  Card, Graphics Card Plus, InColor Card, and 100 percent compatible cards, as
  16792.  well as the special Olivetti(R) modes available on AT&T(R) computers.
  16793.  
  16794.  The low-level graphics routines can be divided into the seven categories
  16795.  listed below, corresponding to the different tasks involved with creating
  16796.  and manipulating graphic objects:
  16797.  
  16798.  Category                          Task
  16799.  ────────────────────────────────────────────────────────────────────────────
  16800.  Configure mode and environment    Selects the proper display mode for the
  16801.                                    hardware and establishes memory areas
  16802.                                    for writing and displaying images
  16803.  
  16804.  Set coordinates                   Specifies the logical origin and the
  16805.                                    active display area within the screen
  16806.  
  16807.  Set palette                       Specifies a palette mapping
  16808.  
  16809.  Set attributes                    Specifies background and foreground
  16810.                                    colors and mask and line styles
  16811.  
  16812.  Output images                     Draws and fills figures on the screen
  16813.  
  16814.  Output text                       Writes text to the screen
  16815.  
  16816.  Transfer images                   Stores images in memory and retrieves
  16817.                                    them
  16818.  
  16819.  
  16820.  Configure Mode and Environment
  16821.  
  16822.  The configure category of functions sets the status of the cursor, sets
  16823.  active and visual pages, and determines and sets video display modes.
  16824.  
  16825.  The _setvideomode and _getvideoconfig functions are generally used at the
  16826.  very beginning of a graphics program.
  16827.  
  16828.  ────────────────────────────────────────────────────────────────────────────
  16829.  _displaycursor - Determines whether the cursor will be left on or turned off
  16830.  on exit from graphics routines.
  16831.  
  16832.  Include                           GRAPH.H
  16833.  
  16834.  Prototype                         short _far _displaycursor( short toggle
  16835.                                    );
  16836.  
  16837.  Argument                          toggle      Cursor state (_GCURSORON,
  16838.                                                _GCURSOROFF  )
  16839.  
  16840.  Returns                           The previous value of toggle
  16841.  
  16842.  ────────────────────────────────────────────────────────────────────────────
  16843.  _getvideoconfig - Obtains status of current graphics environment.
  16844.  
  16845.  Include                           GRAPH.H
  16846.  
  16847.  Prototype                         struct videoconfig _far * _far
  16848.                                    _getvideoconfig
  16849.  
  16850.                                    ( struct videoconfig _far *config );
  16851.  
  16852.  Argument                          config      Configuration information
  16853.  
  16854.  Returns                           The configuration information as a
  16855.                                    videoconfig  structure
  16856.  
  16857.  ────────────────────────────────────────────────────────────────────────────
  16858.  _setvideomode - Selects screen display mode.
  16859.  
  16860.  Include                           GRAPH.H
  16861.  
  16862.  Prototype                         short _far _setvideomode( short mode );
  16863.  
  16864.  Argument                          mode        Desired mode (_DEFAULTMODE,
  16865.                                                _TEXTBW40,
  16866.  
  16867.                                    _TEXTC40, _TEXTBW80, _TEXTC80,
  16868.                                    _MRES4COLOR,
  16869.  
  16870.                                    _MRESNOCOLOR, _HRESBW, _TEXTMONO,
  16871.  
  16872.                                    _HERCMONO, _MRES16COLOR, _HRES16COLOR,
  16873.  
  16874.                                    _ERESNOCOLOR, _ERESCOLOR, _VRES2COLOR,
  16875.  
  16876.                                    _VRES16COLOR, _MRES256COLOR, _ORESCOLOR,
  16877.  
  16878.                                    _MAXRESMODE, _MAXCOLORMODE)
  16879.  
  16880.  Returns                           A nonzero value if successful, 0 if not
  16881.  
  16882.  
  16883.  Set Coordinates
  16884.  
  16885.  The Microsoft C graphics routines recognize three sets of coordinates:
  16886.  
  16887.  
  16888.    1.  Window coordinates defined with real-number values that are mapped to
  16889.        a specified viewport
  16890.  
  16891.    2.  Viewport coordinates defined by the application (viewport coordinates)
  16892.  
  16893.    3.  Fixed physical coordinates determined by the hardware and display
  16894.        configuration of the user's environment (physical coordinates)
  16895.  
  16896.  
  16897.  The functions in this category alter the coordinate systems and provide a
  16898.  means to translate coordinates between the various systems.
  16899.  
  16900.  Most of these routines have two or three forms. The functions are listed by
  16901.  the "base" name, without a suffix. Note, though, that function names that
  16902.  end with a _w, such as _getcurrentposition_w, use the window-coordinate
  16903.  system. Those that end with a _wxy, such as _getviewcoord_wxy, use the
  16904.  window-coordinate system and a _wxycoord structure to define the
  16905.  coordinates.
  16906.  
  16907.  The default viewport-coordinate system is identical to the physical one. The
  16908.  physical origin (0, 0) is always in the upper left corner of the display.
  16909.  The x axis extends in the positive direction left to right, and the y axis
  16910.  extends in the positive direction top to bottom.
  16911.  
  16912.  The dimensions of the x and y axes depend upon the hardware display
  16913.  configuration and the selected mode. These values are accessible at run time
  16914.  by examining the numxpixels and numypixels fields of the videoconfig
  16915.  structure returned by _getvideoconfig.
  16916.  
  16917.  ────────────────────────────────────────────────────────────────────────────
  16918.  _getcurrentposition - Obtains the coordinates of the current graphic-output
  16919.  position. The _getcurrentposition function returns the position as an
  16920.  xycoord structure and the _getcurrentposition_w function returns the
  16921.  position as a  _wxycoord structure.
  16922.  
  16923.  Include                           GRAPH.H
  16924.  
  16925.  Prototypes                        struct xycoord _far _getcurrentposition(
  16926.                                    void );
  16927.  
  16928.  
  16929.  
  16930.                                    struct _wxycoord _far
  16931.                                    _getcurrentposition_w( void );
  16932.  
  16933.  Arguments                         None
  16934.  
  16935.  Returns                           _getcurrentposition: the coordinates of
  16936.                                    the current position as
  16937.  
  16938.                                    an xycoord structure
  16939.  
  16940.                                    _getcurrentposition_w: the coordinates
  16941.                                    of the current position
  16942.  
  16943.                                    as a _wxycoord structure
  16944.  
  16945.  ────────────────────────────────────────────────────────────────────────────
  16946.  _getphyscoord - Converts viewport coordinates to physical coordinates.
  16947.  
  16948.  Include                           GRAPH.H
  16949.  
  16950.  Prototype                         struct xycoord _far _getphyscoord( short
  16951.                                    x, short y );
  16952.  
  16953.  Argument                          x, y        View point to translate
  16954.  
  16955.  Returns                           A pair of physical coordinates as an
  16956.                                    xycoord  structure
  16957.  
  16958.  ────────────────────────────────────────────────────────────────────────────
  16959.  _getviewcoord  - Converts specified coordinates to viewport coordinates.
  16960.  
  16961.  Include                           GRAPH.H
  16962.  
  16963.  Prototypes                        struct xycoord _far _getviewcoord( short
  16964.                                    x, short  );
  16965.  
  16966.  
  16967.  
  16968.                                    struct xycoord _far _getviewcoord_w(
  16969.                                    double wx, double wy  );
  16970.  
  16971.  
  16972.  
  16973.                                    struct xycoord _far _getviewcoord_wxy(
  16974.                                    struct _wxycoord _far
  16975.  
  16976.                                    *pwxy1 );
  16977.  
  16978.  Arguments                         x, y        Physical point to translate
  16979.  
  16980.                                    wx, wy      Window-coordinate point to
  16981.                                                translate
  16982.  
  16983.                                    pwxy1       Window-coordinate point to
  16984.                                                translate
  16985.  
  16986.  Returns                           A pair of logical coordinates as an
  16987.                                    xycoord  structure
  16988.  
  16989.  ────────────────────────────────────────────────────────────────────────────
  16990.  _getwindowcoord - Converts physical coordinates to window coordinates.
  16991.  
  16992.  Include                           GRAPH.H
  16993.  
  16994.  Prototype                         struct _wxycoord _far _getwindowcoord(
  16995.                                    short  x, short y );
  16996.  
  16997.  Argument                          x, y        Physical point to translate
  16998.  
  16999.  Returns                           A pair of window coordinates as a
  17000.                                    _wxycoord  structure
  17001.  
  17002.  ────────────────────────────────────────────────────────────────────────────
  17003.  _setcliprgn - Limits graphic output to part of the screen.
  17004.  
  17005.  Include                           GRAPH.H
  17006.  
  17007.  Prototype                         void _far _setcliprgn( short x1, short
  17008.                                    y1, short x2, short y2 );
  17009.  
  17010.  Arguments                         x1, y1      Upper left corner of clip
  17011.                                                region
  17012.  
  17013.                                    x2, y2      Lower right corner of clip
  17014.                                                region
  17015.  
  17016.  Returns                           Void
  17017.  
  17018.  ────────────────────────────────────────────────────────────────────────────
  17019.  _setvieworg - Positions the logical origin.
  17020.  
  17021.  Include                           GRAPH.H
  17022.  
  17023.  Prototype                         struct xycoord _far _setvieworg( short x
  17024.                                    ,  short y );
  17025.  
  17026.  Argument                          x, y        New origin point
  17027.  
  17028.  Returns                           The physical coordinates of the previous
  17029.                                    viewport  origin in an
  17030.  
  17031.                                    xycoord structure
  17032.  
  17033.  ────────────────────────────────────────────────────────────────────────────
  17034.  _setviewport - Limits graphic output and positions the logical origin within
  17035.  a limited area.
  17036.  
  17037.  Include                           GRAPH.H
  17038.  
  17039.  Prototype                         void _far _setviewport( short x1,  short
  17040.                                    y1, short x2, short y2 );
  17041.  
  17042.  Arguments                         x1, y1      Upper left corner of window
  17043.  
  17044.                                    x2, y2      Lower right corner of window
  17045.  
  17046.  Returns                           Void
  17047.  
  17048.  ────────────────────────────────────────────────────────────────────────────
  17049.  _setwindow - Defines a window-coordinate system.
  17050.  
  17051.  Include                           GRAPH.H
  17052.  
  17053.  Prototype                         void _far _setwindow( short finvert,
  17054.                                    double wx1, double wy1,
  17055.  
  17056.                                    double wx2, double wy2 );
  17057.  
  17058.  Arguments                         wx1, wy1    Upper left corner of  window
  17059.  
  17060.                                    wx2, wy2    Lower right corner of window
  17061.  
  17062.                                    finvert     Invert flag  (TRUE, FALSE)
  17063.  
  17064.  Returns                           Void
  17065.  
  17066.  
  17067.  Set Palette
  17068.  
  17069.  A screen pixel can be represented as a one-, two-, or four-bit value,
  17070.  depending on the particular mode. The byte representation is called the
  17071.  "color value."
  17072.  
  17073.  Each color that can be displayed is represented by a unique ordinal value
  17074.  called a "color index." A palette is simply a mapping of the actual display
  17075.  colors to the legal values.
  17076.  
  17077.  ────────────────────────────────────────────────────────────────────────────
  17078.  _remapallpalette, _remappalette - The _remapallpalette routine assigns
  17079.  colors to all color values. The _remappalette routine assigns color indexes
  17080.  to selected color values.
  17081.  
  17082.  Include                           GRAPH.H
  17083.  
  17084.  Prototypes                        short _far _remapallpalette( long _far *
  17085.                                    colors  );
  17086.  
  17087.  
  17088.  
  17089.                                    long _far _remappalette( short index,
  17090.                                    long color );
  17091.  
  17092.  
  17093.  
  17094.  Arguments                         colors      Color value array: (_BLACK,
  17095.                                                _BLUE, _GREEN,
  17096.  
  17097.                                    _CYAN, _RED, _MAGENTA, _BROWN,  _WHITE,
  17098.  
  17099.                                    _GRAY, _LIGHTBLUE, ,_LIGHTGREEN,
  17100.  
  17101.                                    _LIGHTCYAN, _LIGHTRED, _LIGHTMAGENTA,
  17102.  
  17103.                                    _LIGHTYELL  _BRIGHTWHITE)
  17104.                                    OW,
  17105.  
  17106.                                    index       Color index to reassign
  17107.  
  17108.                                    color       Color value to assign color
  17109.                                                index
  17110.  
  17111.  Returns                           _remapallpalette:  0 if successful, -1
  17112.                                    if not
  17113.  
  17114.                                    _remappalette:  the previous color value
  17115.                                    of the index argument
  17116.  
  17117.                                    if successful, -1 if not
  17118.  
  17119.  ────────────────────────────────────────────────────────────────────────────
  17120.  _selectpalette - Selects a predefined palette.
  17121.  
  17122.  Include                           GRAPH.H
  17123.  
  17124.  Prototype                         short _far _selectpalette( short number
  17125.                                    );
  17126.  
  17127.  Argument                          number      Palette number
  17128.  
  17129.  Returns                           The value of the previous palette
  17130.  
  17131.  
  17132.  Set Attributes
  17133.  
  17134.  Attributes are characteristics (color, fill pattern, or line style) that can
  17135.  be specified for low-level graphics routines.
  17136.  
  17137.  A fill mask is an 8-by-8-bit template array, with each bit representing a
  17138.  pixel. If a bit is 0, the pixel in memory is left untouched: the mask is
  17139.  transparent to that pixel. If a bit is 1, the pixel is assigned the current
  17140.  color value. The template is repeated over the entire fill area.
  17141.  
  17142.  A line style is a 16-bit template buffer, with each bit corresponding to a
  17143.  pixel. If a bit is 0, the pixel is set to the current background color. If a
  17144.  bit is 1, the pixel is set to the current color. The template is repeated
  17145.  for the length of the line.
  17146.  
  17147.  ────────────────────────────────────────────────────────────────────────────
  17148.  _getbkcolor - Reports the current background color.
  17149.  
  17150.  Include                           GRAPH.H
  17151.  
  17152.  Prototype                         long _far _getbkcolor( void );
  17153.  
  17154.  Arguments                         None
  17155.  
  17156.  Returns                           The current background color
  17157.  
  17158.  ────────────────────────────────────────────────────────────────────────────
  17159.  _getcolor - Obtains the current color.
  17160.  
  17161.  Include                           GRAPH.H
  17162.  
  17163.  Prototype                         short _far _getcolor( void );
  17164.  
  17165.  Arguments                         None
  17166.  
  17167.  Returns                           The current color
  17168.  
  17169.  ────────────────────────────────────────────────────────────────────────────
  17170.  _setbkcolor - Sets the current background color.
  17171.  
  17172.  Include                           GRAPH.H
  17173.  
  17174.  Prototype                         long _far _setbkcolor( long color );
  17175.  
  17176.  Argument                          color       Desired color value
  17177.  
  17178.  Returns                           The color value of the previous
  17179.                                    background color
  17180.  
  17181.  ────────────────────────────────────────────────────────────────────────────
  17182.  _setcolor - Sets the current color.
  17183.  
  17184.  Include                           GRAPH.H
  17185.  
  17186.  Prototype                         short _far _setcolor( short color );
  17187.  
  17188.  Argument                          color       Desired color index
  17189.  
  17190.  Returns                           The previous color
  17191.  
  17192.  
  17193.  Output Images
  17194.  
  17195.  These routines display graphic elements (arcs, lines, pixels, etc.) on the
  17196.  screen.
  17197.  
  17198.  Circular figures such as arcs and ellipses are centered within a "bounding
  17199.  rectangle," specified by two points that define the diagonally opposed
  17200.  corners of the rectangle. The center of the rectangle becomes the center of
  17201.  the figure, and the rectangle's borders determine the size of the figure.
  17202.  
  17203.  Most of these routines have two or three forms. The functions are listed by
  17204.  the "base" name, without a suffix. Note, though, that function names that
  17205.  end with a _w, such as _arc_w, use the window coordinate system. Those that
  17206.  end with a _wxy, such as _ellipse_wxy, use the window coordinate system and
  17207.  a  _wxycoord structure to define the coordinates.
  17208.  
  17209.  ────────────────────────────────────────────────────────────────────────────
  17210.  _arc  - Draws an arc.
  17211.  
  17212.  Include                           GRAPH.H
  17213.  
  17214.  Prototypes                        short _far _arc( short x1, short  y1,
  17215.                                    short x2, short y2,
  17216.  
  17217.                                    short x3, short y3, short x4, short y4
  17218.                                    );
  17219.  
  17220.  
  17221.  
  17222.                                    short _far _arc_wxy( struct _wxycoord
  17223.                                    pwxy1,
  17224.  
  17225.                                    struct _wxycoord*pwxy2, struct
  17226.                                    _wxycoord*pwxy3,
  17227.  
  17228.                                    struct _wxycoord*pwxy4 );
  17229.  
  17230.  Arguments                         x1, y1      Upper left corner of
  17231.                                                bounding  rectangle
  17232.  
  17233.                                    x2, y2      Lower right corner of
  17234.                                                bounding rectangle
  17235.  
  17236.                                    x3, y3      Start vector
  17237.  
  17238.                                    x4, y4      End vector
  17239.  
  17240.                                    pwxy1       Upper left corner of
  17241.                                                bounding rectangle
  17242.  
  17243.                                    pwxy2       Lower right corner of
  17244.                                                bounding rectangle
  17245.  
  17246.                                    pwxy3       Start vector
  17247.  
  17248.                                    pwxy4       End vector
  17249.  
  17250.  Returns                           A nonzero value if the arc is drawn
  17251.                                    successfully,  0 if not
  17252.  
  17253.  ────────────────────────────────────────────────────────────────────────────
  17254.  _clearscreen - Erases the screen and fills it with the current background
  17255.  color.
  17256.  
  17257.  Include                           GRAPH.H
  17258.  
  17259.  Prototype                         void _far _clearscreen( short area );
  17260.  
  17261.  Argument                          area        Target area (_GCLEARSCREEN,
  17262.                                                _GVIEWPORT,
  17263.  
  17264.                                     _GWINDOW)
  17265.  
  17266.  Returns                           Void
  17267.  
  17268.  ────────────────────────────────────────────────────────────────────────────
  17269.  _ellipse  - Draws an ellipse.
  17270.  
  17271.  Include                           GRAPH.H
  17272.  
  17273.  Prototypes                        short _far _ellipse( short control,
  17274.                                    short x1, short y1,
  17275.  
  17276.                                    short x2, short y2 );
  17277.  
  17278.  
  17279.  
  17280.                                    short _far _ellipse_w( short control,
  17281.                                    double wx1,  double wy1,
  17282.  
  17283.                                    double wx2, double wy2 );
  17284.  
  17285.  
  17286.  
  17287.                                    short _far _ellipse_wxy( short control,
  17288.                                    struct _wxycoord*  pwxy1,
  17289.  
  17290.                                    struct _wxycoord*pwxy2 );
  17291.  
  17292.  Arguments                         control     Fill flag ( _GFILLINTERIOR,
  17293.                                                 _GBORDER)
  17294.  
  17295.                                    x1, y1      Upper left corner of
  17296.                                                bounding rectangle (view
  17297.  
  17298.                                    coordinates)
  17299.  
  17300.                                    x2, y2      Lower right corner of
  17301.                                                bounding rectangle (view
  17302.  
  17303.                                    coordinates)
  17304.  
  17305.                                    wx1, wy1    Upper left corner of
  17306.                                                bounding rectangle (window
  17307.  
  17308.                                    coordinates)
  17309.  
  17310.                                    wx2, wy2    Lower right corner of
  17311.                                                bounding rectangle  (window
  17312.  
  17313.                                    coordinates)
  17314.  
  17315.                                    pwxy1       Upper left corner of
  17316.                                                bounding rectangle (window
  17317.  
  17318.                                    coordinates)
  17319.  
  17320.                                    pwxy2       Lower right corner of
  17321.                                                bounding rectangle (window
  17322.  
  17323.                                    coordinates)
  17324.  
  17325.  Returns                           A nonzero value if the ellipse is drawn
  17326.                                    successfully,  0 if not
  17327.  
  17328.  ────────────────────────────────────────────────────────────────────────────
  17329.  _floodfill  - Fills an area of the screen with the current color.
  17330.  
  17331.  Include                           GRAPH.H
  17332.  
  17333.  Prototypes                        short _far _floodfill( short x, short  y
  17334.                                    , short boundary );
  17335.  
  17336.  
  17337.  
  17338.                                    short _far _floodfill_w( double wx,
  17339.                                    double wy, short  boundary );
  17340.  
  17341.  Arguments                         x, y        Start point (view
  17342.                                                coordinates)
  17343.  
  17344.                                    wx, wy      Start point (window
  17345.                                                coordinates)
  17346.  
  17347.                                    boundary    Boundary color
  17348.  
  17349.  Returns                           A nonzero value if successful, 0 if not
  17350.  
  17351.  ────────────────────────────────────────────────────────────────────────────
  17352.  _getpixel  - Obtains a pixel's color index. The coordinates can be specified
  17353.  in either view coordinates (_getpixel) or in window coordinates
  17354.  (_getpixel_w).
  17355.  
  17356.  Include                           GRAPH.H
  17357.  
  17358.  Prototypes                        short _far _getpixel( short x, short  y
  17359.                                    );
  17360.  
  17361.  
  17362.  
  17363.                                    short _far _getpixel_w( double wx,
  17364.                                    double wy );
  17365.  
  17366.  Arguments                         x, y        Pixel position (view
  17367.                                                coordinates)
  17368.  
  17369.                                    wx, wy      Pixel position (window
  17370.                                                coordinates)
  17371.  
  17372.  Returns                           The color index if successful, -1 if not
  17373.  
  17374.  ────────────────────────────────────────────────────────────────────────────
  17375.  _lineto  - Draws a line from the current graphic output position to a
  17376.  specified point. The coordinate of the end point can be specified in either
  17377.  view coordinates (_lineto) or in window coordinates (_lineto_w).
  17378.  
  17379.  Include                           GRAPH.H
  17380.  
  17381.  Prototypes                        short _far _lineto( short x, short  y );
  17382.  
  17383.  
  17384.  
  17385.                                    short _far _lineto_w( double wx, double
  17386.                                    wy );
  17387.  
  17388.  Arguments                         x, y        End point (view coordinates)
  17389.  
  17390.                                    wx, wy      End point (window
  17391.                                                coordinates)
  17392.  
  17393.  Returns                           A nonzero value if the line is drawn
  17394.                                    successfully,  0 if not
  17395.  
  17396.  ────────────────────────────────────────────────────────────────────────────
  17397.  _moveto  - Moves the current graphic-output position to a specified point.
  17398.  The coordinates can be specified in either view coordinates (_moveto) or in
  17399.  window coordinates (_moveto_w).
  17400.  
  17401.  Include                           GRAPH.H
  17402.  
  17403.  Prototypes                        struct xycoord _far _moveto( short x,
  17404.                                    short );
  17405.  
  17406.  
  17407.  
  17408.                                    struct _wxycoord _far _moveto_w( double
  17409.                                    wx, double wy  );
  17410.  
  17411.  Arguments                         x, y        Target position (view
  17412.                                                coordinates)
  17413.  
  17414.                                    wx, wy      Target position (window
  17415.                                                coordinates)
  17416.  
  17417.  Returns                           The logical coordinates of the previous
  17418.                                    position  as an xycoord
  17419.  
  17420.                                    structure (_moveto) or as a _wxycoord
  17421.                                    structure (_moveto_w)
  17422.  
  17423.  ────────────────────────────────────────────────────────────────────────────
  17424.  _pie  - Draws a figure shaped like a pie wedge.
  17425.  
  17426.  Include                           GRAPH.H
  17427.  
  17428.  Prototypes                        short _far _pie( short control, short
  17429.                                    x1, short y1,
  17430.  
  17431.                                    short x2, short y2, short x3, short y3,
  17432.                                    short x4, short y4 );
  17433.  
  17434.  
  17435.  
  17436.                                    short _far _pie_wxy( short control,
  17437.                                    struct _wxycoord*  pwxy1,
  17438.  
  17439.                                    struct _wxycoord*pwxy2, struct
  17440.                                    _wxycoord* pwxy3,
  17441.  
  17442.                                    struct _wxycoord*pwxy4 );
  17443.  
  17444.  Arguments                         control     Fill flag (_GFILLINTERIOR,
  17445.                                                _GBORDER)
  17446.  
  17447.                                    x1, y1      Upper left corner of
  17448.                                                bounding rectangle (view
  17449.                                                coordinates)
  17450.  
  17451.                                    x2, y2      Lower right corner of
  17452.                                                bounding rectangle (view
  17453.                                                coordinates)
  17454.  
  17455.                                    x3, y3      Start vector(view
  17456.                                                coordinates)
  17457.  
  17458.                                    x4, y4      End vector (view coordinates)
  17459.  
  17460.                                    pwxy1       Upper left corner of
  17461.                                                bounding rectangle (window
  17462.                                                coordinates)
  17463.  
  17464.                                    pwxy2       Lower right corner of
  17465.                                                bounding rectangle (window
  17466.                                                coordinates)
  17467.  
  17468.                                    pwxy3       Start vector (window
  17469.                                                coordinates)
  17470.  
  17471.                                    pwxy4       End vector (window
  17472.                                                coordinates)
  17473.  
  17474.  Returns                           A nonzero value if the pie is drawn
  17475.                                    successfully,  0 if not
  17476.  
  17477.  
  17478.  
  17479.  ────────────────────────────────────────────────────────────────────────────
  17480.  _rectangle  - Draws a rectangle.
  17481.  
  17482.  Include                           GRAPH.H
  17483.  
  17484.  Prototypes                        short _far _rectangle( short control,
  17485.                                    short x1, short y1,
  17486.  
  17487.                                    short x2, short y2 );
  17488.  
  17489.  
  17490.  
  17491.                                    short _far _rectangle_w( short control,
  17492.                                    double wx1,  double wy1,
  17493.  
  17494.                                    double wx2, double wy2 );
  17495.  
  17496.  
  17497.  
  17498.                                    short _far _rectangle_wxy( short control
  17499.                                    , struct _wxycoord*pwxy1,
  17500.  
  17501.                                    struct _wxycoord*pwxy2 );
  17502.  
  17503.  Arguments                         control     Fill flag (_GFILLINTERIOR,
  17504.                                                _GBORDER)
  17505.  
  17506.                                    x1, y1      Upper left corner (view
  17507.                                                coordinates)
  17508.  
  17509.                                    x2, y2      Lower right corner (view
  17510.                                                coordinates)
  17511.  
  17512.                                    wx1, wy1    Upper left corner (window
  17513.                                                coordinates)
  17514.  
  17515.                                    wx2, wy2    Lower right corner (window
  17516.                                                coordinates)
  17517.  
  17518.                                    pwxy1       Upper left corner (window
  17519.                                                coordinates)
  17520.  
  17521.                                    pwxy2       Lower right corner (window
  17522.                                                coordinates)
  17523.  
  17524.  Returns                           A nonzero value if the rectangle is
  17525.                                    drawn successfully,  0 if not
  17526.  
  17527.  ────────────────────────────────────────────────────────────────────────────
  17528.  _setpixel  - Sets a pixel's color index.
  17529.  
  17530.  Include                           GRAPH.H
  17531.  
  17532.  Prototypes                        short _far _setpixel( short x, short  y
  17533.                                    );
  17534.  
  17535.  
  17536.  
  17537.                                    short _far _setpixel_w( double wx,
  17538.                                    double wy );
  17539.  
  17540.  Arguments                         x, y        Target pixel (view
  17541.                                                coordinates)
  17542.  
  17543.                                    wx, wy      Target pixel (window
  17544.                                                coordinates)
  17545.  
  17546.  Returns                           The pixel's previous value if successful,
  17547.                                    -1  if not
  17548.  
  17549.  
  17550.  Output Text
  17551.  
  17552.  These routines provide text output in both graphics and text modes.
  17553.  
  17554.  These functions recognize text window boundaries and should be used in
  17555.  applications using text windows.
  17556.  
  17557.  No formatting capability is provided. If you want to output integer or
  17558.  floating-point values, you must convert the values into a string variable
  17559.  before calling these routines. All screen positions are specified as
  17560.  character-row and character-column coordinates.
  17561.  
  17562.  ────────────────────────────────────────────────────────────────────────────
  17563.  _displaycursor - Sets the cursor "on" or "off" on exit from a graphics
  17564.  routine.
  17565.  
  17566.  Include                           GRAPH.H
  17567.  
  17568.  Prototype                         short _far _displaycursor( short toggle
  17569.                                    );
  17570.  
  17571.  Argument                          toggle      Cursor state (_GCURSORON,
  17572.                                                _GCURSOROFF)
  17573.  
  17574.  Returns                           The previous value of toggle
  17575.  
  17576.  ────────────────────────────────────────────────────────────────────────────
  17577.  _gettextcolor - Obtains the current text color.
  17578.  
  17579.  Include                           GRAPH.H
  17580.  
  17581.  Prototype                         short _far _gettextcolor( void );
  17582.  
  17583.  Arguments                         None
  17584.  
  17585.  Returns                           The color index of the current text
  17586.                                    color
  17587.  
  17588.  ────────────────────────────────────────────────────────────────────────────
  17589.  _gettextcursor - Obtains the current cursor attribute.
  17590.  
  17591.  Include                           GRAPH.H
  17592.  
  17593.  Prototype                         short _far _gettextcursor( void );
  17594.  
  17595.  Arguments                         None
  17596.  
  17597.  Returns                           The current cursor attribute
  17598.  
  17599.  ────────────────────────────────────────────────────────────────────────────
  17600.  _gettextposition - Obtains the current text-output position.
  17601.  
  17602.  Include                           GRAPH.H
  17603.  
  17604.  Prototype                         struct rccoord _far _gettextposition(
  17605.                                    void  );
  17606.  
  17607.  Arguments                         None
  17608.  
  17609.  Returns                           The current text position as an rccoord
  17610.                                    structure
  17611.  
  17612.  ────────────────────────────────────────────────────────────────────────────
  17613.  _outtext - Outputs text to the screen at the current position.
  17614.  
  17615.  Include                           GRAPH.H
  17616.  
  17617.  Prototype                         void _far _outtext( unsigned char _far *
  17618.                                    text  );
  17619.  
  17620.  Argument                          text        Text to be output
  17621.  
  17622.  Returns                           Void
  17623.  
  17624.  ────────────────────────────────────────────────────────────────────────────
  17625.  _settextposition - Relocates the current text position.
  17626.  
  17627.  Include                           GRAPH.H
  17628.  
  17629.  Prototype                         struct rccoord _far _settextposition(
  17630.                                    short  row, short col );
  17631.  
  17632.  Arguments                         row         Row coordinate of new output
  17633.                                                position
  17634.  
  17635.                                    col         Column coordinate of new
  17636.                                                output position
  17637.  
  17638.  Returns                           The previous text position in an rccoord
  17639.                                    structure
  17640.  
  17641.  ────────────────────────────────────────────────────────────────────────────
  17642.  _settextcolor - Sets the current text color.
  17643.  
  17644.  Include                           GRAPH.H
  17645.  
  17646.  Prototype                         short _far _settextcolor( short index
  17647.                                    );
  17648.  
  17649.  Argument                          index       Desired color index
  17650.  
  17651.  Returns                           The value of the previous color
  17652.  
  17653.  ────────────────────────────────────────────────────────────────────────────
  17654.  _settextwindow - Sets the current text-display window.
  17655.  
  17656.  Include                           GRAPH.H
  17657.  
  17658.  Prototype                         void _far _settextwindow( short r1,
  17659.                                    short c1, short r2, short c2 );
  17660.  
  17661.  Arguments                         r1, c1      Upper left corner of window
  17662.  
  17663.                                    r2, c2      Lower right corner of window
  17664.  
  17665.  Returns                           Void
  17666.  
  17667.  
  17668.  Transfer Images
  17669.  
  17670.  These functions transfer screen images between memory and the display, using
  17671.  a buffer allocated by the application. You can use these functions to
  17672.  animate graphics elements on the screen.
  17673.  
  17674.  Most of these routines have two or three forms. The functions are listed by
  17675.  the "base" name, without a suffix. Note, though, that function names that
  17676.  end in a _w, such as _getimage_w, use the window-coordinate system. Those
  17677.  that end with a _wxy, such as _imagesize_wxy, use the window-coordinate
  17678.  system and a _wxycoord structure to define the coordinates.
  17679.  
  17680.  The _imagesize function is used to find the size in bytes of the buffer
  17681.  needed to store a given image.
  17682.  
  17683.  ────────────────────────────────────────────────────────────────────────────
  17684.  _getimage - Stores a screen image in memory.
  17685.  
  17686.  Include                           GRAPH.H
  17687.  
  17688.  Prototypes                        void _far _getimage( short x1, short  y1
  17689.                                    ,
  17690.  
  17691.                                    short x2, short y2, char _huge *image
  17692.                                    );
  17693.  
  17694.  
  17695.  
  17696.                                    void _far _getimage_w( double wx1,
  17697.                                    double wy1,
  17698.  
  17699.                                    double wx2, double wy2, char _huge *
  17700.                                    image  );
  17701.  
  17702.  
  17703.  
  17704.                                    void _far _getimage_wxy( struct
  17705.                                    _wxycoord*pwxy1,
  17706.  
  17707.                                    struct _wxycoord*pwxy2, char _huge *
  17708.                                    image  );
  17709.  
  17710.  Arguments                         x1, y1      Upper left corner of
  17711.                                                bounding  rectangle (view
  17712.                                                coordinates)
  17713.  
  17714.                                    x2, y2      Lower right corner of
  17715.                                                bounding rectangle (view
  17716.                                                coordinates)
  17717.  
  17718.                                    wx1, wy1    Upper left corner of
  17719.                                                bounding rectangle (window
  17720.                                                coordinates)
  17721.  
  17722.                                    wx2, wy2    Lower right corner of
  17723.                                                bounding rectangle  (window
  17724.                                                coordinates)
  17725.  
  17726.                                    pwxy1       Upper left corner of
  17727.                                                bounding rectangle (window
  17728.                                                coordinates)
  17729.  
  17730.                                    pwxy2       Lower right corner of
  17731.                                                bounding rectangle (window
  17732.                                                coordinates)
  17733.  
  17734.                                    image       Storage buffer for screen
  17735.                                                image
  17736.  
  17737.  Returns                           Void
  17738.  
  17739.  ────────────────────────────────────────────────────────────────────────────
  17740.  _imagesize - Returns image size in bytes.
  17741.  
  17742.  Include                           GRAPH.H
  17743.  
  17744.  Prototypes                        long _far _imagesize( short x1, short
  17745.                                    y1, short x2, short y2 );
  17746.  
  17747.  
  17748.  
  17749.                                    long _far _imagesize_w( double wx1,
  17750.                                    double wy1, double  wx2,
  17751.  
  17752.                                    double wy2 );
  17753.  
  17754.  
  17755.  
  17756.                                    long _far _imagesize_wxy( struct
  17757.                                    _wxycoord* pwxy1,
  17758.  
  17759.                                    struct _wxycoord* pwxy2 );
  17760.  
  17761.  Arguments                         x1, y1      Upper left corner of
  17762.                                                bounding  rectangle (view
  17763.                                                coordinates)
  17764.  
  17765.                                    x2, y2      Lower right corner of
  17766.                                                bounding rectangle (view
  17767.                                                coordinates)
  17768.  
  17769.                                    wx1, wy1    Upper left corner of
  17770.                                                bounding rectangle (window
  17771.                                                coordinates)
  17772.  
  17773.                                    wx2, wy2    Lower right corner of
  17774.                                                bounding rectangle  (window
  17775.                                                coordinates)
  17776.  
  17777.                                    pwxy1       Upper left corner of
  17778.                                                bounding rectangle (window
  17779.                                                coordinates)
  17780.  
  17781.                                    pwxy2       Lower right corner of
  17782.                                                bounding rectangle (window
  17783.                                                coordinates)
  17784.  
  17785.  Returns                           The storage size of the image in bytes
  17786.  
  17787.  ────────────────────────────────────────────────────────────────────────────
  17788.  _putimage - Retrieves an image from memory and displays it.
  17789.  
  17790.  Include                           GRAPH.H
  17791.  
  17792.  Prototypes                        void _far _putimage( short x, short  y,
  17793.  
  17794.                                    char _huge *image, short action );
  17795.  
  17796.  
  17797.  
  17798.                                    void _far _putimage_w( double wx, double
  17799.                                    wy,
  17800.  
  17801.                                    char _huge *image, short action );
  17802.  
  17803.  Arguments                         x, y        Position of upper left
  17804.                                                corner of  image (view
  17805.                                                coordinates)
  17806.  
  17807.                                    wx, wy      Position of upper left
  17808.                                                corner of image (window
  17809.                                                coordinates)
  17810.  
  17811.                                    image       Stored image buffer
  17812.  
  17813.                                    action      Interaction with existing
  17814.                                                screen image (_GAND,   _GOR,
  17815.  
  17816.                                    _GXOR, _GPSET, _GPRESET)
  17817.  
  17818.  Returns                           Void
  17819.  
  17820.  
  17821.  Graphics 2: Presentation Graphics Routines
  17822.  
  17823.  The presentation graphics routines provide complete charting capabilities
  17824.  for line, bar, column, scatter, and pie charts.
  17825.  
  17826.  Some charts plot both "categories," or non-numeric data such as time
  17827.  periods, and "values," or specific numeric data, such as sales. Presentation
  17828.  graphics routines support the following kinds of charts:
  17829.  
  17830.  Chart Name                        Description
  17831.  ────────────────────────────────────────────────────────────────────────────
  17832.  Line                              Category/value chart, with styles for
  17833.                                    lines between points and for no lines
  17834.  
  17835.  Bar                               Category/value chart, horizontal bars,
  17836.                                    styles for stacked and unstacked
  17837.                                    multiple series charts
  17838.  
  17839.  Column                            Category/value chart, vertical bars,
  17840.                                    with styles for stacked and unstacked
  17841.                                    multiple series charts
  17842.  
  17843.  Scatter                           Value/value chart, with styles for lines
  17844.                                    connecting points or for no lines
  17845.  
  17846.  Pie                               Pie chart, with optional percentages and
  17847.                                    exploded sections
  17848.  
  17849.  The graphics package supports the IBM (and compatible) Enhanced Graphics
  17850.  Adapter (EGA), Color Graphics Adapter (CGA), certain operating modes of the
  17851.  Video Graphics Array (VGA) hardware configurations, and the Multicolor
  17852.  Graphics Array (MCGA). The graphics package also supports the Hercules
  17853.  Graphics Card, Graphics Card Plus, InColor Card, and 100-percent compatible
  17854.  cards, as well as the special Olivetti modes available on AT&T computers.
  17855.  
  17856.  The _pg_initchart and _pg_defaultchart functions are generally used at the
  17857.  very beginning of a presentation graphics program.
  17858.  
  17859.  The _pg_chart functions produce column charts, line charts, and bar charts.
  17860.  The _pg_chartscatter functions produce a scatter plot of data. The
  17861.  _pg_chartpie function generates a pie chart.
  17862.  
  17863.  ────────────────────────────────────────────────────────────────────────────
  17864.  _pg_chart - Generates a chart of the type specified in the env environment
  17865.  variable. It produces a column, bar, or line chart for a single series of
  17866.  data.
  17867.  
  17868.  Include                           PGCHART.H
  17869.  
  17870.  Prototype                         short _far _pg_chart( chartenv _far*env,
  17871.  
  17872.  
  17873.                                    char _far*_far *categories, float _far*
  17874.                                    values,  short n );
  17875.  
  17876.  Arguments                         env         Chart environment variable
  17877.  
  17878.                                    categories  Array of category variables
  17879.  
  17880.                                    values      Array of data values
  17881.  
  17882.                                    n           Number of data values to
  17883.                                                chart
  17884.  
  17885.  Returns                           0 if successful, nonzero if not
  17886.  
  17887.  ────────────────────────────────────────────────────────────────────────────
  17888.  _pg_chartms - Generates a multiple series of charts of the type specified in
  17889.  the env environment variable. It produces a column, bar, or line chart for a
  17890.  multiple series of data. All series must be the same length.
  17891.  
  17892.  Include                           PGCHART.H
  17893.  
  17894.  Prototype                         short _far _pg_chartms( chartenv _far *
  17895.                                    env,
  17896.  
  17897.                                    char _far * _far*categories, float _far*
  17898.                                    values,  short n, short nseries,
  17899.  
  17900.                                    short arraydim, char _far* _far*
  17901.                                    serieslabels  );
  17902.  
  17903.  Arguments                         env         Chart environment variable
  17904.  
  17905.                                    categories  Array of category variables
  17906.  
  17907.                                    values      Two-dimensional array of
  17908.                                                data values (series, data)
  17909.  
  17910.                                    n           Number of data values to
  17911.                                                chart in a series
  17912.  
  17913.                                    nseries     Number of series to chart
  17914.  
  17915.                                    arraydim    Second (row) dimension of
  17916.                                                data array
  17917.  
  17918.                                    serieslabe  Array of labels for series
  17919.                                    ls
  17920.  
  17921.  Returns                           0 if successful, nonzero if not
  17922.  
  17923.  ────────────────────────────────────────────────────────────────────────────
  17924.  _pg_chartpie - Generates a pie chart for a single series of data.
  17925.  
  17926.  Include                           PGCHART.H
  17927.  
  17928.  Prototype                         short _far _pg_chartpie( chartenv _far*
  17929.                                    env,
  17930.  
  17931.                                    char _far* _far*categories, float _far*
  17932.                                    values,
  17933.  
  17934.                                    short _far*explode, short n );
  17935.  
  17936.  Arguments                         env         Chart environment variable
  17937.  
  17938.                                    categories  Array of category names
  17939.  
  17940.                                    values      Array of data values
  17941.  
  17942.                                    explode     Array of explode flags;
  17943.                                                1=explode, 0=do not explode
  17944.  
  17945.                                    n           Number of data values to
  17946.                                                chart
  17947.  
  17948.  Returns                           0 if successful, nonzero if not
  17949.  
  17950.  ────────────────────────────────────────────────────────────────────────────
  17951.  _pg_chartscatter - Generates a scatter chart for a single series of data.
  17952.  
  17953.  Include                           PGCHART.H
  17954.  
  17955.  Prototype                         short _far _pg_chartscatter( chartenv
  17956.                                    _far  *env, float _far *xvalues,
  17957.  
  17958.                                    float _far *yvalues, short n );
  17959.  
  17960.  Arguments                         env         Chart environment variable
  17961.  
  17962.                                    xvalues     Array of x-axis data values
  17963.  
  17964.                                    yvalues     Array of y-axis data values
  17965.  
  17966.                                    n           Number of data values to
  17967.                                                chart
  17968.  
  17969.  Returns                           0 if successful, nonzero if not
  17970.  
  17971.  ────────────────────────────────────────────────────────────────────────────
  17972.  _pg_chartscatterms - Generates a scatter chart for a multiple series of
  17973.  data.
  17974.  
  17975.  Include                           PGCHART.H
  17976.  
  17977.  Prototype                         short _far _pg_chartscatterms( chartenv
  17978.                                    _far  *env,
  17979.  
  17980.                                    float _far*xvalues, float _far*yvalues,
  17981.                                    short nseries, short n,
  17982.  
  17983.                                    short rowdim, char _far* _far *
  17984.                                    serieslabels  );
  17985.  
  17986.  Arguments                         env         Chart environment variable
  17987.  
  17988.                                    xvalues     Two-dimensional array of x
  17989.                                                -axis values
  17990.  
  17991.                                    yvalues     Two-dimensional array of y
  17992.                                                -axis values
  17993.  
  17994.                                    n           Number of data values to
  17995.                                                chart in a series
  17996.  
  17997.                                    nseries     Number of series to chart
  17998.  
  17999.                                    rowdim      Second (row) dimension of
  18000.                                                data array
  18001.  
  18002.                                    serieslabe  Array of labels for series
  18003.                                    ls
  18004.  
  18005.  Returns                           0 if successful, nonzero if not
  18006.  
  18007.  ────────────────────────────────────────────────────────────────────────────
  18008.  _pg_defaultchart - Initializes all necessary variables in the chart
  18009.  environment for the specified default chart and chart style.
  18010.  
  18011.  Include                           PGCHART.H
  18012.  
  18013.  Prototype                         short _far _pg_defaultchart( chartenv
  18014.                                    _far  *env, short charttype,
  18015.  
  18016.                                    short chartstyle );
  18017.  
  18018.  Arguments                         env         Chart environment variable
  18019.  
  18020.                                    charttype   Chart type (_PG_BARCHART,
  18021.  
  18022.                                    _PG_COLUMNCHART, _PG_LINECHART,
  18023.  
  18024.                                    _PG_SCATTERCHART, _PG_PIECHART)
  18025.  
  18026.                                    chartstyle  Chart style
  18027.  
  18028.  Returns                           0 if successful, nonzero if not
  18029.  
  18030.  ────────────────────────────────────────────────────────────────────────────
  18031.  _pg_initchart - Initializes chart line-style set, default palettes, screen
  18032.  modes, and character fonts. You must call this routine before any other
  18033.  charting routine.
  18034.  
  18035.  Include                           PGCHART.H
  18036.  
  18037.  Prototype                         short _far _pg_initchart( void );
  18038.  
  18039.  Arguments                         None
  18040.  
  18041.  Returns                           0 if successful, nonzero if not
  18042.  
  18043.  
  18044.  Graphics 3: Font Display Routines
  18045.  
  18046.  The font graphics routines display font-based characters on the screen.
  18047.  
  18048.  The _registerfonts function initializes the fonts package with a set of
  18049.  disk-based type fonts. This must be done at the very beginning of any fonts
  18050.  program. The _unregisterfonts function frees fonts from memory when they are
  18051.  no longer needed.
  18052.  
  18053.  The _setfont function makes a specified font the current active font for
  18054.  output. The _outgtext function displays text on the screen using the current
  18055.  font.
  18056.  
  18057.  ────────────────────────────────────────────────────────────────────────────
  18058.  _getfontinfo - Obtains the current font characteristics.
  18059.  
  18060.  Include                           GRAPH.H
  18061.  
  18062.  Prototype                         short _far _getfontinfo( struct
  18063.                                    _fontinfo  _far *fontbuffer );
  18064.  
  18065.  Argument                          fontbuffer  Font information
  18066.  
  18067.  Returns                           Font information as a _fontinfo
  18068.                                    structure
  18069.  
  18070.  ────────────────────────────────────────────────────────────────────────────
  18071.  _getgtextextent - Determines the width of the specified text in the current
  18072.  font.
  18073.  
  18074.  Include                           GRAPH.H
  18075.  
  18076.  Prototype                         short _far _getgtextextent( unsigned
  18077.                                    char  _far * text );
  18078.  
  18079.  Argument                          text        Text to be analyzed
  18080.  
  18081.  Returns                           The width of the text in pixels
  18082.  
  18083.  ────────────────────────────────────────────────────────────────────────────
  18084.  _outgtext - Outputs text in the current font to the screen at the current
  18085.  position.
  18086.  
  18087.  Include                           GRAPH.H
  18088.  
  18089.  Prototype                         void _far _outgtext( unsigned char _far
  18090.                                    *text  );
  18091.  
  18092.  Argument                          text        Text to be output
  18093.  
  18094.  Returns                           Void
  18095.  
  18096.  ────────────────────────────────────────────────────────────────────────────
  18097.  _registerfonts - Initializes the font library.
  18098.  
  18099.  Include                           GRAPH.H
  18100.  
  18101.  Prototype                         short _far _registerfonts( unsigned char
  18102.                                    _far *filename );
  18103.  
  18104.  Argument                          file name   File name of .FON files to
  18105.                                                register
  18106.  
  18107.  Returns                           Void
  18108.  
  18109.  ────────────────────────────────────────────────────────────────────────────
  18110.  _setfont - Finds a single font that matches a specified set of
  18111.  characteristics and makes this font the current font.
  18112.  
  18113.  Include                           GRAPH.H
  18114.  
  18115.  Prototype                         short _far _setfont( unsigned char _far
  18116.                                    *options  );
  18117.  
  18118.  Argument                          options     Font options string
  18119.  
  18120.  Returns                           Void
  18121.  
  18122.  ────────────────────────────────────────────────────────────────────────────
  18123.  _unregisterfonts - Frees memory associated with fonts.
  18124.  
  18125.  Include                           GRAPH.H
  18126.  
  18127.  Prototype                         void _far _unregisterfonts( void );
  18128.  
  18129.  Arguments                         None
  18130.  
  18131.  Returns                           Void
  18132.  
  18133.  
  18134.  Input and Output Routines
  18135.  
  18136.  The input and output (I/O) routines of the standard C library allow you to
  18137.  read and write data to and from files and devices. In C, there are no
  18138.  predefined file structures; all data is treated as sequences of bytes.
  18139.  
  18140.  Three types of I/O functions are available:
  18141.  
  18142.  
  18143.    ■   Stream I/O,  in which the data file is a stream of individual
  18144.        characters
  18145.  
  18146.    ■   Low-level I/O, which uses the system's I/O capabilities directly
  18147.  
  18148.    ■   Console and port I/O, which are stream routines for console or port
  18149.  
  18150.  
  18151.  Stream I/O uses the FILE structure. The stream routines provide for
  18152.  buffered, formatted, or unformatted input and output.
  18153.  
  18154.  Low-level I/O uses a file "handle" to access files. This handle is an
  18155.  integer value that is used to refer to the file in subsequent operations.
  18156.  
  18157.  Do not mix stream and low-level routines on the same file or device.
  18158.  
  18159.  
  18160.  Stream Routines
  18161.  
  18162.  In the stream routines listed below, the following manifest constants are
  18163.  used:
  18164.  
  18165.  
  18166.    ■   EOF is defined to be the value returned at end-of-file
  18167.  
  18168.    ■   NULL is the null pointer
  18169.  
  18170.    ■   FILE is the structure that maintains information about a stream
  18171.  
  18172.    ■   BUFSIZ defines the default size of stream buffers, in bytes
  18173.  
  18174.  
  18175.  ────────────────────────────────────────────────────────────────────────────
  18176.  clearerr - Clears the error indicator for a stream.
  18177.  
  18178.  Include                           STDIO.H
  18179.  
  18180.  Prototype                         void clearerr( FILE *stream  );
  18181.  
  18182.  Argument                          stream      Pointer to FILE structure
  18183.  
  18184.  Returns                           Void
  18185.  
  18186.  ────────────────────────────────────────────────────────────────────────────
  18187.  fclose - Closes a stream.
  18188.  
  18189.  Include                           STDIO.H
  18190.  
  18191.  Prototype                         int fclose( FILE *stream  );
  18192.  
  18193.  Argument                          stream      Target FILE structure
  18194.  
  18195.  Returns                           0 if successful, EOF if not
  18196.  
  18197.  ────────────────────────────────────────────────────────────────────────────
  18198.  feof - Tests for end-of-file on a stream.
  18199.  
  18200.  Include                           STDIO.H
  18201.  
  18202.  Prototype                         int feof( FILE *stream  );
  18203.  
  18204.  Argument                          stream      Pointer to FILE structure
  18205.  
  18206.  Returns                           A nonzero value when the current
  18207.                                    position is  the end-of-file,
  18208.  
  18209.                                    0 if not
  18210.  
  18211.  ────────────────────────────────────────────────────────────────────────────
  18212.  ferror - Tests for error on a stream.
  18213.  
  18214.  Include                           STDIO.H
  18215.  
  18216.  Prototype                         int ferror( FILE *stream  );
  18217.  
  18218.  Argument                          stream      Pointer to FILE structure
  18219.  
  18220.  Returns                           A nonzero value to indicate an error in
  18221.                                    stream,  0 to indicate
  18222.  
  18223.                                    no error
  18224.  
  18225.  ────────────────────────────────────────────────────────────────────────────
  18226.  fflush - Flushes a stream.
  18227.  
  18228.  Include                           STDIO.H
  18229.  
  18230.  Prototype                         int fflush( FILE *stream  );
  18231.  
  18232.  Argument                          stream      Pointer to FILE structure
  18233.  
  18234.  Returns                           0 if successful, if stream has no buffer,
  18235.                                    or  if stream is open
  18236.  
  18237.                                    only for reading; returns EOF otherwise
  18238.  
  18239.  ────────────────────────────────────────────────────────────────────────────
  18240.  fgetc - Reads a character from a stream (function version).
  18241.  
  18242.  Include                           STDIO.H
  18243.  
  18244.  Prototype                         int fgetc( FILE *stream  );
  18245.  
  18246.  Argument                          stream      Pointer to FILE structure
  18247.  
  18248.  Returns                           The character read; EOF may indicate
  18249.                                    error
  18250.  
  18251.  ────────────────────────────────────────────────────────────────────────────
  18252.  fgetpos - Gets the position indicator of a stream.
  18253.  
  18254.  Include                           STDIO.H
  18255.  
  18256.  Prototype                         int fgetpos( FILE *stream,  fpos_t *pos
  18257.                                    );
  18258.  
  18259.  Arguments                         stream      Target stream
  18260.  
  18261.                                    pos         Position indicator storage
  18262.  
  18263.  Returns                           0 if successful, a nonzero value if not
  18264.  
  18265.                                    errno:  EINVAL, EBADF
  18266.  
  18267.  ────────────────────────────────────────────────────────────────────────────
  18268.  fgets - Reads a string from a stream.
  18269.  
  18270.  Include                           STDIO.H
  18271.  
  18272.  Prototype                         char *fgets( char *string,  int n, FILE
  18273.                                    *stream );
  18274.  
  18275.  Arguments                         string      Storage location for data
  18276.  
  18277.                                    n           Number of characters stored
  18278.  
  18279.                                    stream      Pointer to FILE structure
  18280.  
  18281.  Returns                           A pointer to string if successful, NULL
  18282.                                    if unsuccessful or at
  18283.  
  18284.                                    end-of-file
  18285.  
  18286.  ────────────────────────────────────────────────────────────────────────────
  18287.  fopen - Opens a stream.
  18288.  
  18289.  Include                           STDIO.H
  18290.  
  18291.  Prototype                         FILE *fopen( const char *filename,
  18292.                                    const char *mode );
  18293.  
  18294.  Arguments                         filename    Path name of file
  18295.  
  18296.                                    mode        Type of access permitted
  18297.                                                such as r, w,  a, r+, w+, a+
  18298.                                                , t, b
  18299.  
  18300.                                    (appended to type to indicate mode)
  18301.  
  18302.  Returns                           A pointer to the open file if successful,
  18303.                                    NULL  if not
  18304.  
  18305.  ────────────────────────────────────────────────────────────────────────────
  18306.  fprintf - Writes formatted data to a stream.
  18307.  
  18308.  Include                           STDIO.H
  18309.  
  18310.  Prototype                         int fprintf( FILE *stream,  const char *
  18311.                                    format [[, argument]]...  );
  18312.  
  18313.  Arguments                         stream      Pointer to FILE structure
  18314.  
  18315.                                    format      Format-control string
  18316.  
  18317.  Returns                           The number of characters printed
  18318.  
  18319.  ────────────────────────────────────────────────────────────────────────────
  18320.  fputc - Writes a character to a stream (function version).
  18321.  
  18322.  Include                           STDIO.H
  18323.  
  18324.  Prototype                         int fputc( int c, FILE *stream  );
  18325.  
  18326.  Arguments                         c           Character to be written
  18327.  
  18328.                                    stream      Pointer to FILE structure
  18329.  
  18330.  Returns                           The character written; EOF may indicate
  18331.                                    error
  18332.  
  18333.  ────────────────────────────────────────────────────────────────────────────
  18334.  fputs - Writes a string to a stream.
  18335.  
  18336.  Include                           STDIO.H
  18337.  
  18338.  Prototype                         int fputs( const char *string,  FILE *
  18339.                                    stream );
  18340.  
  18341.  Arguments                         string      String to be output
  18342.  
  18343.                                    stream      Pointer to FILE structure
  18344.  
  18345.  Returns                           0 if successful, nonzero if not
  18346.  
  18347.  ────────────────────────────────────────────────────────────────────────────
  18348.  fread - Reads unformatted data from a stream.
  18349.  
  18350.  Include                           STDIO.H
  18351.  
  18352.  Prototype                         size_t fread( void *buffer,  size_t size
  18353.                                    , size_t count, FILE *stream  );
  18354.  
  18355.  Arguments                         buffer      Storage location for data
  18356.  
  18357.                                    size        Item size in bytes
  18358.  
  18359.                                    count       Maximum number of items to
  18360.                                                be read
  18361.  
  18362.                                    stream      Pointer to FILE structure
  18363.  
  18364.  Returns                           The number of items actually read
  18365.  
  18366.  ────────────────────────────────────────────────────────────────────────────
  18367.  freopen - Reassigns a FILE pointer.
  18368.  
  18369.  Include                           STDIO.H
  18370.  
  18371.  Prototype                         FILE *freopen( const char  *filename,
  18372.                                    const char *mode,
  18373.  
  18374.                                    FILE *stream );
  18375.  
  18376.  Arguments                         filename    Path name of new file
  18377.  
  18378.                                    mode        Type of access permitted
  18379.                                                such as r,  w,  a,  r+,  w+,
  18380.  
  18381.                                    a+,  t,  b (appended to type to indicate
  18382.                                    mode)
  18383.  
  18384.                                    stream      Pointer to FILE structure
  18385.  
  18386.  Returns                           A pointer to the newly opened file if
  18387.                                    successful,  a NULL
  18388.  
  18389.                                    pointer if not
  18390.  
  18391.  ────────────────────────────────────────────────────────────────────────────
  18392.  fscanf - Reads formatted data from a stream.
  18393.  
  18394.  Include                           STDIO.H
  18395.  
  18396.  Prototype                         int fscanf( FILE *stream,  const char*
  18397.                                    format  [[, argument]]  ... );
  18398.  
  18399.  Arguments                         stream      Pointer to FILE structure
  18400.  
  18401.                                    format      Format-control string
  18402.  
  18403.  Returns                           The number of fields successfully
  18404.                                    converted and  assigned;
  18405.  
  18406.                                    EOF indicates an attempt to read the
  18407.                                    end-of-file
  18408.  
  18409.  ────────────────────────────────────────────────────────────────────────────
  18410.  fseek - Repositions FILE pointer to given location.
  18411.  
  18412.  Include                           STDIO.H
  18413.  
  18414.  Prototype                         int fseek( FILE *stream,  long offset,
  18415.                                    int origin );
  18416.  
  18417.  Arguments                         stream      Pointer to FILE structure
  18418.  
  18419.                                    offset      Number of bytes from origin
  18420.  
  18421.                                    origin      Initial position (SEEK_SET,
  18422.                                                SEEK_CUR,  SEEK_END)
  18423.  
  18424.  Returns                           0 if successful, a nonzero value if not
  18425.  
  18426.  ────────────────────────────────────────────────────────────────────────────
  18427.  fsetpos - Sets the position indicator of a stream.
  18428.  
  18429.  Include                           STDIO.H
  18430.  
  18431.  Prototype                         int fsetpos( FILE *stream,  const fpos_t
  18432.                                    *pos );
  18433.  
  18434.  Arguments                         stream      Target stream
  18435.  
  18436.                                    pos         Position-indicator storage
  18437.  
  18438.  Returns                           0 if successful, a nonzero value if not
  18439.  
  18440.                                    errno:  EINVAL, EBADF
  18441.  
  18442.  ────────────────────────────────────────────────────────────────────────────
  18443.  ftell - Gets current FILE pointer position.
  18444.  
  18445.  Include                           STDIO.H
  18446.  
  18447.  Prototype                         long ftell( FILE *stream  );
  18448.  
  18449.  Argument                          stream      Target FILE structure
  18450.  
  18451.  Returns                           The current position if successful, -1L
  18452.                                    if  not
  18453.  
  18454.                                    errno:  EINVAL, EBADF
  18455.  
  18456.  ────────────────────────────────────────────────────────────────────────────
  18457.  fwrite - Writes unformatted data items to a stream.
  18458.  
  18459.  Include                           STDIO.H
  18460.  
  18461.  Prototype                         size_t fwrite( const void *buffer,
  18462.                                    size_t size, size_t count,
  18463.  
  18464.                                    FILE *stream );
  18465.  
  18466.  Arguments                         buffer      Pointer to data to be
  18467.                                                written
  18468.  
  18469.                                    size        Item size in bytes
  18470.  
  18471.                                    count       Maximum number of items to
  18472.                                                be written
  18473.  
  18474.                                    stream      Pointer to FILE structure
  18475.  
  18476.  Returns                           The number of full items actually
  18477.                                    written
  18478.  
  18479.  ────────────────────────────────────────────────────────────────────────────
  18480.  getc - Reads a character from a stream (macro version).
  18481.  
  18482.  Include                           STDIO.H
  18483.  
  18484.  Prototype                         int getc( FILE *stream  );
  18485.  
  18486.  Argument                          stream      Pointer to FILE structure
  18487.  
  18488.  Returns                           The character read; EOF may indicate
  18489.                                    error
  18490.  
  18491.  ────────────────────────────────────────────────────────────────────────────
  18492.  getchar - Reads a character from stdin (macro version).
  18493.  
  18494.  Include                           STDIO.H
  18495.  
  18496.  Prototype                         int getchar( void );
  18497.  
  18498.  Arguments                         None
  18499.  
  18500.  Returns                           The character read; EOF may indicate
  18501.                                    error
  18502.  
  18503.  ────────────────────────────────────────────────────────────────────────────
  18504.  gets - Reads a line from stdin.
  18505.  
  18506.  Include                           STDIO.H
  18507.  
  18508.  Prototype                         char *gets( char *buffer  );
  18509.  
  18510.  Argument                          buffer      Storage location for input
  18511.                                                string
  18512.  
  18513.  Returns                           A pointer to its argument if successful,
  18514.                                    a NULL  pointer if at
  18515.  
  18516.                                    end-of-file or unsuccessful
  18517.  
  18518.  ────────────────────────────────────────────────────────────────────────────
  18519.  printf - Writes formatted data to stdout.
  18520.  
  18521.  Include                           STDIO.H
  18522.  
  18523.  Prototype                         int printf( const char *format  [[,
  18524.                                    argument]]... );
  18525.  
  18526.  Argument                          format      Format-control string
  18527.  
  18528.  Returns                           The number of characters printed
  18529.  
  18530.  ────────────────────────────────────────────────────────────────────────────
  18531.  putc - Writes a character to a stream (macro version).
  18532.  
  18533.  Include                           STDIO.H
  18534.  
  18535.  Prototype                         int putc( int c, FILE *stream  );
  18536.  
  18537.  Arguments                         c           Character to be written
  18538.  
  18539.                                    stream      Pointer to FILE structure
  18540.  
  18541.  Returns                           The character written; EOF may indicate
  18542.                                    error
  18543.  
  18544.  ────────────────────────────────────────────────────────────────────────────
  18545.  putchar - Writes a character to stdout (macro version).
  18546.  
  18547.  Include                           STDIO.H
  18548.  
  18549.  Prototype                         int putchar( int c );
  18550.  
  18551.  Argument                          c           Character to be written
  18552.  
  18553.  Returns                           The character written; EOF may indicate
  18554.                                    error
  18555.  
  18556.  ────────────────────────────────────────────────────────────────────────────
  18557.  puts - Writes a line to a stream.
  18558.  
  18559.  Include                           STDIO.H
  18560.  
  18561.  Prototype                         int puts( const char *string );
  18562.  
  18563.  Argument                          string      String to be output
  18564.  
  18565.  Returns                           0 if successful, nonzero if not
  18566.  
  18567.  ────────────────────────────────────────────────────────────────────────────
  18568.  rewind - Repositions FILE pointer to beginning of a stream.
  18569.  
  18570.  Include                           STDIO.H
  18571.  
  18572.  Prototype                         void rewind( FILE *stream  );
  18573.  
  18574.  Argument                          stream      Pointer to FILE structure
  18575.  
  18576.  Returns                           Void
  18577.  
  18578.  ────────────────────────────────────────────────────────────────────────────
  18579.  scanf - Reads formatted data from stdin.
  18580.  
  18581.  Include                           STDIO.H
  18582.  
  18583.  Prototype                         int scanf( const char *format [[,
  18584.                                    argument]]... );
  18585.  
  18586.  Argument                          format      Format control string
  18587.  
  18588.  Returns                           The number of fields converted and
  18589.                                    assigned if  successful, 0 if
  18590.  
  18591.                                    no fields were assigned, EOF for an
  18592.                                    attempt to read  end-of-file
  18593.  
  18594.  ────────────────────────────────────────────────────────────────────────────
  18595.  sprintf - Writes formatted data to string.
  18596.  
  18597.  Include                           STDIO.H
  18598.  
  18599.  Prototype                         int sprintf( char *buffer, const  char *
  18600.                                    format [[, argument]]  ... );
  18601.  
  18602.  Arguments                         buffer      Storage location for output
  18603.  
  18604.                                    format      Format-control string
  18605.  
  18606.  Returns                           The number of characters stored in
  18607.                                    buffer
  18608.  
  18609.  ────────────────────────────────────────────────────────────────────────────
  18610.  sscanf - Reads formatted data from string.
  18611.  
  18612.  Include                           STDIO.H
  18613.  
  18614.  Prototype                         int sscanf( const char *buffer,  const
  18615.                                    char *format [[, argument]]  ... );
  18616.  
  18617.  Arguments                         buffer      Stored data
  18618.  
  18619.                                    format      Format-control string
  18620.  
  18621.  Returns                           The number of fields converted and
  18622.                                    assigned if  successful, 0 if
  18623.  
  18624.                                    no fields were assigned, EOF for an
  18625.                                    attempt to read  at end-of-string
  18626.  
  18627.  ────────────────────────────────────────────────────────────────────────────
  18628.  tmpfile - Creates a temporary file.
  18629.  
  18630.  Include                           STDIO.H
  18631.  
  18632.  Prototype                         FILE *tmpfile( void );
  18633.  
  18634.  Arguments                         None
  18635.  
  18636.  Returns                           A stream pointer if successful, NULL  if
  18637.                                    not
  18638.  
  18639.  ────────────────────────────────────────────────────────────────────────────
  18640.  tmpnam - Generates a temporary file name.
  18641.  
  18642.  Include                           STDIO.H
  18643.  
  18644.  Prototype                         char *tmpnam( char *string  );
  18645.  
  18646.  Argument                          string      Pointer to temporary name
  18647.  
  18648.  Returns                           A pointer to the new name if successful,
  18649.                                    NULL  if not
  18650.  
  18651.  ────────────────────────────────────────────────────────────────────────────
  18652.  ungetc - Places a character in the input stream buffer.
  18653.  
  18654.  Include                           STDIO.H
  18655.  
  18656.  Prototype                         int ungetc( int c, FILE  *stream );
  18657.  
  18658.  Arguments                         c           Character to be pushed
  18659.  
  18660.                                    stream      Pointer to FILE structure
  18661.  
  18662.  Returns                           The character argument c if successful,
  18663.                                    EOF if not
  18664.  
  18665.  
  18666.  Low-Level Routines
  18667.  
  18668.  The low-level input and output calls do not buffer or format data.
  18669.  
  18670.  Files opened by low-level calls are referenced by a "file handle," an
  18671.  integer value used by the operating system to refer to the file.
  18672.  
  18673.  ────────────────────────────────────────────────────────────────────────────
  18674.  close - Closes a file.
  18675.  
  18676.  Include                           IO.H
  18677.  
  18678.  Prototype                         int close( int handle );
  18679.  
  18680.  Argument                          handle      Handle referring to open
  18681.                                                file
  18682.  
  18683.  Returns                           0 if successful, -1 if not
  18684.  
  18685.                                    errno: EBADF
  18686.  
  18687.  ────────────────────────────────────────────────────────────────────────────
  18688.  creat  - Creates a file.
  18689.  
  18690.  Include                           IO.H, SYS\TYPES.H, SYS\STAT.H
  18691.  
  18692.  Prototype                         int creat( char *filename, int  pmode );
  18693.  
  18694.  Arguments                         filename    Path name of new file
  18695.  
  18696.                                    pmode       Permission setting (
  18697.                                                S_IWRITE , S_IREAD,
  18698.  
  18699.                                    S_IREAD | S_IWRITE)
  18700.  
  18701.  Returns                           A handle if successful, -1 if not
  18702.  
  18703.                                    errno:  EACCES, EMFILE, ENOENT
  18704.  
  18705.  ────────────────────────────────────────────────────────────────────────────
  18706.  eof  - Tests for end-of-file.
  18707.  
  18708.  Include                           IO.H
  18709.  
  18710.  Prototype                         int eof( int handle );
  18711.  
  18712.  Argument                          handle      Handle referring to open
  18713.                                                file
  18714.  
  18715.  Returns                           1 if the current position is the
  18716.                                    end-of-file  and 0 if it is not,
  18717.  
  18718.                                    -1 to indicate an error
  18719.  
  18720.                                    errno:  EBADF
  18721.  
  18722.  ────────────────────────────────────────────────────────────────────────────
  18723.  lseek  - Repositions file pointer to a given location.
  18724.  
  18725.  Include                           IO.H, STDIO.H
  18726.  
  18727.  Prototype                         long lseek( int handle, long offset,
  18728.                                    int origin );
  18729.  
  18730.  Arguments                         handle      Handle referring to open
  18731.                                                file
  18732.  
  18733.                                    offset      Number of bytes from origin
  18734.  
  18735.                                    origin      Initial position (SEEK_SET,
  18736.                                                SEEK_CUR,  SEEK_END)
  18737.  
  18738.  Returns                           The new position offset (in bytes) from
  18739.                                    the beginning  of
  18740.  
  18741.                                    the file if successful, -1L if not
  18742.  
  18743.                                    errno:  EBADF, EINVAL
  18744.  
  18745.  ────────────────────────────────────────────────────────────────────────────
  18746.  open  - Opens a file.
  18747.  
  18748.  Include                           FCNTL.H, IO.H, SYS\TYPES.H, SYS\STAT.H
  18749.  
  18750.  Prototype                         int open( char *path, int oflag [[,  int
  18751.                                    pmode]] );
  18752.  
  18753.  Arguments                         path        File path name
  18754.  
  18755.                                    oflag       Type of operations allowed
  18756.                                                such as O_APPEND,
  18757.  
  18758.                                    O_BINARY, O_CREAT,  O_EXCL,   O_RDONLY,
  18759.  
  18760.                                    O_RDWR,   O_TEXT,   O_TRUNC,  O_WRONLY
  18761.  
  18762.                                    (may be joined by | )
  18763.  
  18764.                                    pmode       Permission setting (S_IWRITE
  18765.                                                ,  S_IREAD,
  18766.  
  18767.                                    S_IREAD | S_IWRITE)
  18768.  
  18769.  Returns                           A handle if successful, -1 if not
  18770.  
  18771.                                    errno:  EACCES, EEXIST, EMFILE,  ENOENT
  18772.  
  18773.  ────────────────────────────────────────────────────────────────────────────
  18774.  read  - Reads data from a file.
  18775.  
  18776.  Include                           IO.H
  18777.  
  18778.  Prototype                         int read( int handle, char *buffer,
  18779.                                    unsigned int count );
  18780.  
  18781.  Arguments                         handle      Handle referring to open
  18782.                                                file
  18783.  
  18784.                                    buffer      Storage location of data
  18785.  
  18786.                                    count       Maximum number of bytes
  18787.  
  18788.  Returns                           The number of bytes actually read or 0
  18789.                                    at end-of-file  if
  18790.  
  18791.                                    successful; -1 if not
  18792.  
  18793.                                    errno:  EBADF
  18794.  
  18795.  ────────────────────────────────────────────────────────────────────────────
  18796.  tell  - Gets current file-pointer position.
  18797.  
  18798.  Include                           IO.H
  18799.  
  18800.  Prototype                         long tell( int handle );
  18801.  
  18802.  Argument                          handle      Handle referring to open
  18803.                                                file
  18804.  
  18805.  Returns                           The current position if successful, -1L
  18806.                                    if  not
  18807.  
  18808.                                    errno:  EBADF
  18809.  
  18810.  ────────────────────────────────────────────────────────────────────────────
  18811.  write  - Writes data to a file.
  18812.  
  18813.  Include                           IO.H
  18814.  
  18815.  Prototype                         int write( int handle, void *buffer,
  18816.                                    unsigned int count );
  18817.  
  18818.  Arguments                         handle      Handle referring to open
  18819.                                                file
  18820.  
  18821.                                    buffer      Data to be written
  18822.  
  18823.                                    count       Number of bytes
  18824.  
  18825.  Returns                           The number of bytes actually written if
  18826.                                    successful,  -1 if not
  18827.  
  18828.                                    errno:  EBADF, ENOSPC
  18829.  
  18830.  
  18831.  
  18832.  
  18833.  Console and Port I/O Routines
  18834.  
  18835.  The console and port I/O routines perform reading and writing operations on
  18836.  your console or on the specified port.
  18837.  
  18838.  The cgets, cscanf, getch, getche, and kbhit routines take input from the
  18839.  console.
  18840.  
  18841.  The cprintf, cputs, putch, and ungetch routines write to the console.
  18842.  
  18843.  The console or port does not have to be opened or closed before I/O is
  18844.  performed.
  18845.  
  18846.  The console I/O routines use the corresponding MS-DOS system calls to read
  18847.  and write characters. Since these routines are not compatible with stream or
  18848.  low-level library routines, console routines should not be used with them.
  18849.  
  18850.  ────────────────────────────────────────────────────────────────────────────
  18851.  cgets - Reads a string from the console.
  18852.  
  18853.  Include                           CONIO.H
  18854.  
  18855.  Prototype                         char *cgets( char *buffer  );
  18856.  
  18857.  Argument                          buffer      Storage location for data
  18858.  
  18859.  Returns                           A pointer to the start of the string,
  18860.                                    which is  at str[2]
  18861.  
  18862.  ────────────────────────────────────────────────────────────────────────────
  18863.  cprintf - Writes formatted data to the console.
  18864.  
  18865.  Include                           CONIO.H
  18866.  
  18867.  Prototype                         int cprintf( char *format [[,  argument]]
  18868.                                    ... );
  18869.  
  18870.  Argument                          format      Format-control string
  18871.  
  18872.  Returns                           The number of characters printed
  18873.  
  18874.  ────────────────────────────────────────────────────────────────────────────
  18875.  cputs - Writes a string to the console.
  18876.  
  18877.  Include                           CONIO.H
  18878.  
  18879.  Prototype                         int cputs( char *string );
  18880.  
  18881.  Argument                          string      Output string
  18882.  
  18883.  Returns                           0 if successful, nonzero if not
  18884.  
  18885.  ────────────────────────────────────────────────────────────────────────────
  18886.  cscanf - Reads formatted data from the console.
  18887.  
  18888.  Include                           CONIO.H
  18889.  
  18890.  Prototype                         int cscanf( char *format [[,  argument
  18891.                                    ]]... );
  18892.  
  18893.  Argument                          format      Format-control string
  18894.  
  18895.  Returns                           The number of fields converted and
  18896.                                    assigned if  successful
  18897.  
  18898.                                    (0 means no fields were assigned), EOF
  18899.                                    for an attempt  to read
  18900.  
  18901.                                    end-of-file
  18902.  
  18903.  ────────────────────────────────────────────────────────────────────────────
  18904.  getch - Reads a character from the console.
  18905.  
  18906.  Include                           CONIO.H
  18907.  
  18908.  Prototype                         int getch( void );
  18909.  
  18910.  Arguments                         None
  18911.  
  18912.  Returns                           The character read
  18913.  
  18914.  ────────────────────────────────────────────────────────────────────────────
  18915.  getche - Reads a character from the console and echoes it.
  18916.  
  18917.  Include                           CONIO.H
  18918.  
  18919.  Prototype                         int getche( void );
  18920.  
  18921.  Arguments                         None
  18922.  
  18923.  Returns                           The character read
  18924.  
  18925.  ────────────────────────────────────────────────────────────────────────────
  18926.  kbhit - Checks for a keystroke at the console.
  18927.  
  18928.  Include                           CONIO.H
  18929.  
  18930.  Prototype                         int kbhit( void );
  18931.  
  18932.  Arguments                         None
  18933.  
  18934.  Returns                           A nonzero value if a key has been
  18935.                                    pressed, 0  if not
  18936.  
  18937.  ────────────────────────────────────────────────────────────────────────────
  18938.  putch - Writes a character to the console.
  18939.  
  18940.  Include                           CONIO.H
  18941.  
  18942.  Prototype                         int putch( int c );
  18943.  
  18944.  Argument                          c           Character to be output
  18945.  
  18946.  Returns                           The argument c if successful, EOF  if
  18947.                                    not
  18948.  
  18949.  ────────────────────────────────────────────────────────────────────────────
  18950.  ungetch - "Ungets" the last character read from the console so that it
  18951.  becomes the next character read.
  18952.  
  18953.  Include                           CONIO.H
  18954.  
  18955.  Prototype                         int ungetch( int c );
  18956.  
  18957.  Argument                          c           Character to be pushed
  18958.  
  18959.  Returns                           The argument c if successful, EOF  if
  18960.                                    not
  18961.  
  18962.  
  18963.  Math Routines
  18964.  
  18965.  The math routines allow you to perform common mathematical calculations.
  18966.  
  18967.  All math routines work with floating-point values and therefore require
  18968.  floating-point support.
  18969.  
  18970.  ────────────────────────────────────────────────────────────────────────────
  18971.  abs, fabs, labs - The abs, fabs, and labs routines return the absolute value
  18972.  of an integer, a double, and a long argument, respectively.
  18973.  
  18974.  Includes                          STDLIB.H (abs, labs), MATH.H (fabs)
  18975.  
  18976.  Prototypes                        int abs( int n );
  18977.  
  18978.  
  18979.  
  18980.                                    double fabs( double x );
  18981.  
  18982.  
  18983.  
  18984.                                    long labs( long x );
  18985.  
  18986.  Arguments                         n           Integer (abs) or long (labs)
  18987.                                                value
  18988.  
  18989.                                    x           Floating-point value
  18990.  
  18991.  Returns                           Absolute value of its argument
  18992.  
  18993.  ────────────────────────────────────────────────────────────────────────────
  18994.  acos - Calculates the arccosine.
  18995.  
  18996.  Includes                          FLOAT.H, MATH.H
  18997.  
  18998.  Prototype                         double acos( double x );
  18999.  
  19000.  Argument                          x           Value whose arccosine is to
  19001.                                                be calculated
  19002.  
  19003.  Returns                           The arccosine result if successful, or 0
  19004.                                    if x  > 1
  19005.  
  19006.                                    errno:  EDOM
  19007.  
  19008.  ────────────────────────────────────────────────────────────────────────────
  19009.  asin - Calculates the arcsine.
  19010.  
  19011.  Includes                          FLOAT.H, MATH.H
  19012.  
  19013.  Prototype                         double asin( double x );
  19014.  
  19015.  Argument                          x           Value whose arcsine is to be
  19016.                                                calculated
  19017.  
  19018.  Returns                           The arcsine result if successful, or 0
  19019.                                    if x  >1
  19020.  
  19021.                                    errno:  EDOM
  19022.  
  19023.  ────────────────────────────────────────────────────────────────────────────
  19024.  atan, atan2 - Calculates the arctangent of x (atan) or the arctangent of y/x
  19025.  (atan2).
  19026.  
  19027.  Includes                          FLOAT.H, MATH.H
  19028.  
  19029.  Prototypes                        double atan( double x );
  19030.  
  19031.  
  19032.  
  19033.                                    double atan2( double y, double x );
  19034.  
  19035.  Argument                          x, y        Floating-point values
  19036.  
  19037.  Returns                           atan: the arctangent result
  19038.  
  19039.                                    atan2: the arctangent of y/x, or 0 if
  19040.                                    both arguments  are 0
  19041.  
  19042.                                    errno:  EDOM
  19043.  
  19044.  ────────────────────────────────────────────────────────────────────────────
  19045.  ceil - Rounds the argument up to an integer.
  19046.  
  19047.  Includes                          FLOAT.H, MATH.H
  19048.  
  19049.  Prototype                         double ceil( double x );
  19050.  
  19051.  Argument                          x           Floating-point value
  19052.  
  19053.  Returns                           The double result
  19054.  
  19055.  ────────────────────────────────────────────────────────────────────────────
  19056.  cos, cosh - Calculates the cosine (cos) or the hyperbolic cosine (cosh).
  19057.  
  19058.  Includes                          FLOAT.H, MATH.H
  19059.  
  19060.  Prototypes                        double cos( double x );
  19061.  
  19062.  
  19063.  
  19064.                                    double cosh( double x );
  19065.  
  19066.  Argument                          x           Angle (in radians)
  19067.  
  19068.  Returns                           cos: the cosine result if successful, 0
  19069.                                    if not
  19070.  
  19071.                                    cosh: the hyperbolic result if
  19072.                                    successful, or HUGE_VAL  if the
  19073.  
  19074.                                    result is too large
  19075.  
  19076.                                    errno:  ERANGE
  19077.  
  19078.  ────────────────────────────────────────────────────────────────────────────
  19079.  exp - Calculates the exponential function.
  19080.  
  19081.  Includes                          FLOAT.H, MATH.H
  19082.  
  19083.  Prototype                         double exp( double x );
  19084.  
  19085.  Argument                          x           Floating-point value
  19086.  
  19087.  Returns                           The exponential value if successful,
  19088.                                    HUGE_VAL  on overflow,
  19089.  
  19090.                                    0 on underflow
  19091.  
  19092.                                    errno:  ERANGE
  19093.  
  19094.  ────────────────────────────────────────────────────────────────────────────
  19095.  floor - Rounds the argument down to an integer.
  19096.  
  19097.  Includes                          FLOAT.H, MATH.H
  19098.  
  19099.  Prototype                         double floor( double x );
  19100.  
  19101.  Argument                          x           Floating-point value
  19102.  
  19103.  Returns                           The floating-point result
  19104.  
  19105.  ────────────────────────────────────────────────────────────────────────────
  19106.  fmod - Finds the floating-point remainder.
  19107.  
  19108.  Includes                          FLOAT.H, MATH.H
  19109.  
  19110.  Prototype                         double fmod( double x, double y  );
  19111.  
  19112.  Argument                          x, y        Floating-point values
  19113.  
  19114.  Returns                           The floating-point remainder, or 0 if y
  19115.                                    is 0
  19116.  
  19117.  ────────────────────────────────────────────────────────────────────────────
  19118.  frexp - Calculates an exponential value.
  19119.  
  19120.  Includes                          FLOAT.H, MATH.H
  19121.  
  19122.  Prototype                         double frexp( double x, int *expptr  );
  19123.  
  19124.  Argument                          x           Floating-point value
  19125.  
  19126.                                    expptr      Pointer to stored integer
  19127.                                                exponent
  19128.  
  19129.  Returns                           The mantissa, or 0 if x is 0
  19130.  
  19131.  ────────────────────────────────────────────────────────────────────────────
  19132.  ldexp - Calculates the argument times 2exp.
  19133.  
  19134.  Includes                          FLOAT.H, MATH.H
  19135.  
  19136.  Prototype                         double ldexp( double x, int exp  );
  19137.  
  19138.  Arguments                         x           Floating-point value
  19139.  
  19140.                                    exp         Integer exponent
  19141.  
  19142.  Returns                           An exponential value if successful,
  19143.                                    HUGE_VAL  on overflow
  19144.  
  19145.                                    errno:  ERANGE
  19146.  
  19147.  ────────────────────────────────────────────────────────────────────────────
  19148.  log, log10 - Calculates the natural logarithm (log) or the base-10 log
  19149.  (log10).
  19150.  
  19151.  Includes                          FLOAT.H, MATH.H
  19152.  
  19153.  Prototypes                        double log( double x );
  19154.  
  19155.  
  19156.  
  19157.                                    double log10( double x );
  19158.  
  19159.  Argument                          x           Floating-point value
  19160.  
  19161.  Returns                           A logarithm result if successful,
  19162.                                    -HUGE_VAL  if not
  19163.  
  19164.                                    errno: EDOM (if x < 0), ERANGE  (if x =
  19165.                                    0)
  19166.  
  19167.  ────────────────────────────────────────────────────────────────────────────
  19168.  modf - Breaks argument into integer and fractional parts.
  19169.  
  19170.  Includes                          FLOAT.H, MATH.H
  19171.  
  19172.  Prototype                         double modf( double x, double *intptr
  19173.                                    );
  19174.  
  19175.  Arguments                         x           Floating-point value
  19176.  
  19177.                                    intptr      Pointer to stored integer
  19178.                                                position
  19179.  
  19180.  Returns                           The signed fractional portion of x
  19181.  
  19182.  ────────────────────────────────────────────────────────────────────────────
  19183.  pow - Calculates a value raised to a power.
  19184.  
  19185.  Includes                          FLOAT.H, MATH.H
  19186.  
  19187.  Prototype                         double pow( double x, double y  );
  19188.  
  19189.  Arguments                         x           Number to be raised
  19190.  
  19191.                                    y           Power of x
  19192.  
  19193.  Returns                           The argument x raised to the y  power if
  19194.                                    successful,
  19195.  
  19196.                                    HUGE_VAL if not
  19197.  
  19198.  ────────────────────────────────────────────────────────────────────────────
  19199.  rand, srand - The rand function returns a pseudorandom integer in the range
  19200.  0-32,767. The srand function initializes the random number generator.
  19201.  
  19202.  Include                           STDLIB.H
  19203.  
  19204.  Prototypes                        int rand( void );
  19205.  
  19206.  
  19207.  
  19208.                                    void srand( unsigned seed );
  19209.  
  19210.  Argument                          seed        Seed for random-number
  19211.                                                generation  (srand)
  19212.  
  19213.  Returns                           rand: a pseudorandom number
  19214.  
  19215.                                    srand: void
  19216.  
  19217.  ────────────────────────────────────────────────────────────────────────────
  19218.  sin, sinh - Calculates the sine (sin) or hyperbolic sine (sinh).
  19219.  
  19220.  Includes                          FLOAT.H, MATH.H
  19221.  
  19222.  Prototypes                        double sin( double x );
  19223.  
  19224.  
  19225.  
  19226.                                    double sinh( double x );
  19227.  
  19228.  Argument                          x           Angle (in radians)
  19229.  
  19230.  Returns                           sin: the sine of x if successful,  0 if
  19231.                                    not
  19232.  
  19233.                                    sinh: the hyperbolic sine of x if
  19234.                                    successful, HUGE_VAL  if not
  19235.  
  19236.                                    errno:  ERANGE
  19237.  
  19238.  ────────────────────────────────────────────────────────────────────────────
  19239.  sqrt - Finds the square root.
  19240.  
  19241.  Includes                          FLOAT.H, MATH.H
  19242.  
  19243.  Prototype                         double sqrt( double x );
  19244.  
  19245.  Argument                          x           Nonnegative floating-point
  19246.                                                value
  19247.  
  19248.  Returns                           A square root if successful, 0 if not
  19249.  
  19250.                                    errno:  EDOM
  19251.  
  19252.  ────────────────────────────────────────────────────────────────────────────
  19253.  tan, tanh - Calculates the tangent (tan) or hyperbolic tangent (tanh).
  19254.  
  19255.  Includes                          FLOAT.H, MATH.H
  19256.  
  19257.  Prototypes                        double tan( double x );
  19258.  
  19259.  
  19260.  
  19261.                                    double tanh( double x );
  19262.  
  19263.  Argument                          x           Angle (in radians)
  19264.  
  19265.  Returns                           tan: the tangent of x if successful,  0
  19266.                                    if not
  19267.  
  19268.                                    tanh: the hyperbolic tangent of x
  19269.  
  19270.                                    errno:  ERANGE (tan only)
  19271.  
  19272.  
  19273.  Memory-Allocation Routines
  19274.  
  19275.  The memory-allocation routines allocate, free, analyze, and reallocate
  19276.  blocks of memory.
  19277.  
  19278.  Many of the memory-allocation functions are prefixed by an _f or an _n. This
  19279.  notation means use the far (_f) heap or the near (_n) heap.
  19280.  
  19281.  The malloc family of routines (malloc, _fmalloc, and _nmalloc) allocates
  19282.  memory blocks of a specified size. The calloc function allocates storage for
  19283.  an array. The halloc function allocates storage for a huge array.
  19284.  
  19285.  The realloc routine changes the size of an allocated block.
  19286.  
  19287.  ────────────────────────────────────────────────────────────────────────────
  19288.  calloc - Allocates storage for an array.
  19289.  
  19290.  Includes                          MALLOC.H, STDLIB.H
  19291.  
  19292.  Prototype                         void *calloc( size_t num,  size_t size
  19293.                                    );
  19294.  
  19295.  Arguments                         num         Number of elements
  19296.  
  19297.                                    size        Length in bytes of each
  19298.                                                element
  19299.  
  19300.  Returns                           A void pointer to the allocated space if
  19301.                                    successful,
  19302.  
  19303.                                    NULL if not
  19304.  
  19305.  ────────────────────────────────────────────────────────────────────────────
  19306.  free, _ffree, hfree, _nfree - Frees a block of memory previously allocated
  19307.  by the corresponding malloc routine. The corresponding routines are listed
  19308.  below:
  19309.  
  19310.  Free Function                     Allocation Function
  19311.  ────────────────────────────────────────────────────────────────────────────
  19312.  _ffree                            _fmalloc
  19313.  
  19314.  free                              calloc, malloc, realloc
  19315.  
  19316.  hfree                             halloc
  19317.  
  19318.  _nfree                            _nmalloc
  19319.  
  19320.  
  19321.  
  19322.  Includes                          MALLOC.H, STDLIB.H (ANSI-compatible free
  19323.                                    only)
  19324.  
  19325.  Prototypes                        void _ffree( void _far *memblock  );
  19326.  
  19327.  
  19328.  
  19329.                                    void free( void *memblock );
  19330.  
  19331.  
  19332.  
  19333.                                    void _nfree( void near *memblock );
  19334.  
  19335.  
  19336.  
  19337.                                                void hfree( void huge *
  19338.                                                memblock );
  19339.  
  19340.  Argument                          memblock    Allocated memory block
  19341.  
  19342.  Returns                           Void
  19343.  
  19344.  ────────────────────────────────────────────────────────────────────────────
  19345.  malloc , _fmalloc,  _nmalloc - Allocates a block of memory. The _fmalloc
  19346.  function allocates the block in the far heap. The _nmalloc function
  19347.  allocates the block in the near heap.
  19348.  
  19349.  Includes                          MALLOC.H, STDLIB.H (ANSI-compatible
  19350.                                    malloc  only)
  19351.  
  19352.  Prototypes                        void *malloc( size_t size );
  19353.  
  19354.  
  19355.  
  19356.                                    void _far *_fmalloc( size_t size );
  19357.  
  19358.  
  19359.  
  19360.                                    void near *_nmalloc( size_t size );
  19361.  
  19362.  Argument                          size        Bytes to allocate
  19363.  
  19364.  Returns                           A void pointer to the allocated space if
  19365.                                    successful,  NULL if not
  19366.  
  19367.  ────────────────────────────────────────────────────────────────────────────
  19368.  realloc - Reallocates a block.
  19369.  
  19370.  Include                           MALLOC.H, STDLIB.H
  19371.  
  19372.  Prototype                         void *realloc( void *memblock,  size_t
  19373.                                    size );
  19374.  
  19375.  Arguments                         memblock    Pointer to previously
  19376.                                                allocated  memory block
  19377.  
  19378.                                    size        New size in bytes
  19379.  
  19380.  Returns                           A pointer to the reallocated memory if
  19381.                                    successful,  NULL
  19382.  
  19383.                                    if not
  19384.  
  19385.  
  19386.  Process-Control Routines
  19387.  
  19388.  The term "process" refers to a program being executed by the operating
  19389.  system.
  19390.  
  19391.  Use the process-control routines to
  19392.  
  19393.  
  19394.    ■   Terminate a process (abort, exit, and _exit)
  19395.  
  19396.    ■   Call a new function when a process terminates (atexit)
  19397.  
  19398.    ■   Start a new process (system)
  19399.  
  19400.  
  19401.  Use the abort and _exit functions to exit without flushing stream buffers.
  19402.  Use the exit function to exit after flushing stream buffers.
  19403.  
  19404.  Use the atexit function to create a list of functions to be executed when
  19405.  the calling program exits.
  19406.  
  19407.  Use the system call to execute a given MS-DOS command.
  19408.  
  19409.  ────────────────────────────────────────────────────────────────────────────
  19410.  abort - Aborts a process.
  19411.  
  19412.  Include                           PROCESS.H or STDLIB.H
  19413.  
  19414.  Prototype                         void abort( void );
  19415.  
  19416.  Arguments                         None
  19417.  
  19418.  Returns                           Void
  19419.  
  19420.  ────────────────────────────────────────────────────────────────────────────
  19421.  atexit - Executes functions at program termination.
  19422.  
  19423.  Include                           STDLIB.H
  19424.  
  19425.  Prototype                         int atexit( void (*func)( void  ) );
  19426.  
  19427.  Argument                          func        Function to be called
  19428.  
  19429.  Returns                           A pointer to func if successful, NULL
  19430.                                    if not
  19431.  
  19432.  ────────────────────────────────────────────────────────────────────────────
  19433.  exit, _exit - Terminates the process after flushing buffers (exit);
  19434.  terminates the process without flushing buffers (_exit).
  19435.  
  19436.  Include                           PROCESS.H or STDLIB.H
  19437.  
  19438.  Prototypes                        void exit( int status );
  19439.  
  19440.  
  19441.  
  19442.                                    void _exit( int status );
  19443.  
  19444.  Argument                          status      Exit status
  19445.  
  19446.  Returns                           Void
  19447.  
  19448.  ────────────────────────────────────────────────────────────────────────────
  19449.  system - Executes an MS-DOS command.
  19450.  
  19451.  Include                           PROCESS.H, STDLIB.H
  19452.  
  19453.  Prototype                         int system( const char *command );
  19454.  
  19455.  Argument                          command     Command to be executed
  19456.  
  19457.  Returns                           0 if successful, -1 if not
  19458.  
  19459.                                    errno:  E2BIG, ENOENT, ENOEXEC, ENOMEM
  19460.  
  19461.  
  19462.  
  19463.  
  19464.  
  19465.  
  19466.  Searching and Sorting Routines
  19467.  
  19468.  The bsearch, lfind, lsearch, and qsort routines provide helpful
  19469.  binary-search, linear-search, and quick-sort utilities.
  19470.  
  19471.  ────────────────────────────────────────────────────────────────────────────
  19472.  bsearch - Performs a binary search.
  19473.  
  19474.  Includes                          STDLIB.H, SEARCH.H
  19475.  
  19476.  Prototype                         void *bsearch( const void *key,  const
  19477.                                    void *base,
  19478.  
  19479.                                    size_t num, size_t width, int( *compare
  19480.                                    )(  const void *elem1,
  19481.  
  19482.                                    const void *elem2 ) );
  19483.  
  19484.  Arguments                         key         Object to search for
  19485.  
  19486.                                    base        Pointer to base of search
  19487.                                                data
  19488.  
  19489.                                    num         Number of elements
  19490.  
  19491.                                    width       Width of elements
  19492.  
  19493.                                    compare     Compare function
  19494.  
  19495.                                    elem1,      Array elements to compare
  19496.                                    elem2
  19497.  
  19498.  Returns                           A pointer if successful, NULL if  not
  19499.  
  19500.  ────────────────────────────────────────────────────────────────────────────
  19501.  lfind, lsearch - Performs a linear search for given value. If the value is
  19502.  not found, lsearch adds it to the end of the list.
  19503.  
  19504.  Includes                          STDLIB.H, SEARCH.H
  19505.  
  19506.  Prototypes                        char *lfind( char *key,  char *base,
  19507.                                    unsigned *num,
  19508.  
  19509.                                    unsigned width, int( *compare )( const
  19510.                                    void  *elem1,
  19511.  
  19512.                                    const void *elem2 ) );
  19513.  
  19514.  
  19515.  
  19516.                                    char *lsearch( const char *key, const
  19517.                                    char  *base,
  19518.  
  19519.                                    unsigned *num, unsigned width, int( *
  19520.                                    compare  )
  19521.  
  19522.                                    ( const void *elem1, const void *elem2 )
  19523.                                    );
  19524.  
  19525.  Arguments                         key         Object to search for
  19526.  
  19527.                                    base        Pointer to base of search
  19528.                                                data
  19529.  
  19530.                                    num         Number of elements
  19531.  
  19532.                                    width       Width of elements
  19533.  
  19534.                                    compare     Compare function
  19535.  
  19536.                                    elem1,      Array elements to compare
  19537.                                    elem2
  19538.  
  19539.  Returns                           A pointer if successful, NULL if  not
  19540.  
  19541.  ────────────────────────────────────────────────────────────────────────────
  19542.  qsort - Performs a quick sort.
  19543.  
  19544.  Includes                          STDLIB.H, SEARCH.H
  19545.  
  19546.  Prototype                         void qsort( void *base, size_t  num,
  19547.                                    size_t width,
  19548.  
  19549.                                    int( *compare )( const void *elem1,
  19550.                                    const  void *elem2 ) );
  19551.  
  19552.  Arguments                         base        Start of target array
  19553.  
  19554.                                    num         Array size in elements
  19555.  
  19556.                                    width       Element size in bytes
  19557.  
  19558.                                    compare     Compare function
  19559.  
  19560.                                    elem1,      Array elements to compare
  19561.                                    elem2
  19562.  
  19563.  Returns                           Void
  19564.  
  19565.  
  19566.  String-Manipulation Routines
  19567.  
  19568.  A wide variety of string routines is available in the run-time library. With
  19569.  these functions, you can do the following:
  19570.  
  19571.  
  19572.    ■   Copy strings (strcat, strcpy, strdup, strncat, strncpy)
  19573.  
  19574.    ■   Search for strings, individual characters, or characters from a given
  19575.        set (strchr, strcspn, strpbrk, strrchr, strspn, strstr)
  19576.  
  19577.    ■   Perform string comparisons (strcmp, strcmpi, stricmp, strncmp,
  19578.        strnicmp)
  19579.  
  19580.    ■   Find the length of a string (strlen)
  19581.  
  19582.    ■   Convert strings to a different case (strlwr, strupr)
  19583.  
  19584.    ■   Set characters of the string to a given character (strnset, strset)
  19585.  
  19586.    ■   Break strings into tokens (strtok)
  19587.  
  19588.  
  19589.  All string functions work on null-terminated character strings.
  19590.  
  19591.  Use the buffer-manipulation routines described earlier in this appendix for
  19592.  manipulating character arrays that do not end with a null character.
  19593.  
  19594.  ────────────────────────────────────────────────────────────────────────────
  19595.  strcat, strcpy, strdup, strncat, strncpy - Use these routines to copy and
  19596.  concatenate strings. The list below describes each function.
  19597.  
  19598.  Function                          Action
  19599.  ────────────────────────────────────────────────────────────────────────────
  19600.  strcat                            Append (concatenate) a string
  19601.  
  19602.  strcpy                            Copy one string to another
  19603.  
  19604.  strdup                            Duplicate a string
  19605.  
  19606.  strncat                           Append a specified number of characters
  19607.                                    to a string
  19608.  
  19609.  strncpy                           Copy a specified number of characters
  19610.                                    from one string to another
  19611.  
  19612.  Include                           STRING.H
  19613.  
  19614.  Prototypes                        char *strcat( char *dest,  const char *
  19615.                                    src );
  19616.  
  19617.  
  19618.  
  19619.                                    char *strcpy( char *dest, const char *
  19620.                                    src  );
  19621.  
  19622.  
  19623.  
  19624.                                    char *strdup( const char *string );
  19625.  
  19626.  
  19627.  
  19628.                                    char *strncat( char *dest, const char *
  19629.                                    src,  size_t n );
  19630.  
  19631.  
  19632.  
  19633.                                    char *strncpy( char *dest, const char *
  19634.                                    src,  size_t n );
  19635.  
  19636.  Arguments                         dest        Destination string
  19637.  
  19638.                                    src         Source string
  19639.  
  19640.                                    string      Null-terminated string
  19641.  
  19642.                                    n           Number of characters
  19643.  
  19644.  Returns                           strcat: a pointer to the concatenated
  19645.                                    string
  19646.  
  19647.                                    strcpy: dest string
  19648.  
  19649.                                    strdup: a pointer if successful, NULL if
  19650.                                    not
  19651.  
  19652.                                    strncat, strncpy: a pointer to dest
  19653.                                    string
  19654.  
  19655.  ────────────────────────────────────────────────────────────────────────────
  19656.  strchr, strcspn, strpbrk, strrchr, strspn, strstr - Use these routines to
  19657.  search strings. The list below describes each function.
  19658.  
  19659.  Function                          Action
  19660.  ────────────────────────────────────────────────────────────────────────────
  19661.  strchr                            Finds first occurrence of a given
  19662.                                    character in a string
  19663.  
  19664.  strcspn                           Finds first occurrence of a character
  19665.                                    from a given character set in a string
  19666.  
  19667.  strpbrk                           Finds first occurrence of a character
  19668.                                    from one string in another
  19669.  
  19670.  strrchr                           Finds last occurrence of a given
  19671.                                    character in a string
  19672.  
  19673.  strspn                            Finds first substring from a given
  19674.                                    character set in a string
  19675.  
  19676.  strstr                            Finds first occurrence of a given string
  19677.                                    in another string
  19678.  
  19679.  Include                           STRING.H
  19680.  
  19681.  Prototypes                        char *strchr( const char *string,  int c
  19682.                                     );
  19683.  
  19684.  
  19685.  
  19686.                                    size_t strcspn( const char *string1,
  19687.                                    const char *string2  );
  19688.  
  19689.  
  19690.  
  19691.                                    char *strpbrk( const char *string1,
  19692.                                    const char  *string2 );
  19693.  
  19694.  
  19695.  
  19696.                                    char *strrchr( const char *string, int c
  19697.                                      );
  19698.  
  19699.  
  19700.  
  19701.                                    size_t strspn( const char *string1,
  19702.                                    const char *string2  );
  19703.  
  19704.  
  19705.  
  19706.                                    char *strstr( const char *string1, const
  19707.                                    char  *string2 );
  19708.  
  19709.  Arguments                         string,     Null-terminated  strings
  19710.                                    string1,
  19711.                                    string2
  19712.  
  19713.                                    c           Character
  19714.  
  19715.  Returns                           strchr: a pointer if successful, NULL
  19716.                                    if not
  19717.  
  19718.                                    strcspn: an offset into string1
  19719.  
  19720.                                    strpbrk: a pointer to the first matching
  19721.                                    character in string1,
  19722.  
  19723.                                    NULL if no match is found
  19724.  
  19725.                                    strrchr: a pointer to the last
  19726.                                    occurrence of c in  string, NULL
  19727.  
  19728.                                    if c is not found
  19729.  
  19730.                                    strspn: the position of the first
  19731.                                    nonmatching character in  string1
  19732.  
  19733.                                    strstr: a pointer to the first
  19734.                                    occurrence of string2  in string1,
  19735.  
  19736.                                    or NULL if string2 is not found
  19737.  
  19738.  ────────────────────────────────────────────────────────────────────────────
  19739.  strcmp, strcmpi, stricmp, strncmp, strnicmp - Use these routines to compare
  19740.  strings. The list below describes the operation of each function. An "n" in
  19741.  the function name means to use up to n characters; "i" in the name means to
  19742.  operate without regard to the case of the string.
  19743.  
  19744.  Function                          Action
  19745.  ────────────────────────────────────────────────────────────────────────────
  19746.  strcmp                            Compares two strings
  19747.  
  19748.  strcmpi                           Compares two strings without regard to
  19749.                                    case ("i"
  19750.                                    indicates that this function is case
  19751.                                    insensitive)
  19752.  
  19753.  stricmp                           Compares two strings without regard to
  19754.                                    case (identical to strcmpi)
  19755.  
  19756.  strncmp                           Compares characters of two strings
  19757.  
  19758.  strnicmp                          Compares characters of two strings
  19759.                                    without regard to case
  19760.  
  19761.  Include                           STRING.H
  19762.  
  19763.  Prototypes                        int strcmp( const char *string1,  const
  19764.                                    char *string2 );
  19765.  
  19766.  
  19767.  
  19768.                                    int strcmpi( const char *string1, const
  19769.                                    char *string2  );
  19770.  
  19771.  
  19772.  
  19773.                                    int stricmp( const char *string1, const
  19774.                                    char *string2  );
  19775.  
  19776.  
  19777.  
  19778.                                    int strncmp( const char *string1, const
  19779.                                    char *string2,  size_t n );
  19780.  
  19781.  
  19782.  
  19783.                                    int strnicmp( const char *string1, const
  19784.                                    char *string2,  size_t n );
  19785.  
  19786.  Arguments                         string1     Destination string
  19787.  
  19788.                                    string2     Source string
  19789.  
  19790.                                    n           Number of characters
  19791.  
  19792.  Returns                           A negative value if string1, 0  if
  19793.                                    string1 = string2,
  19794.  
  19795.                                    a positive value if string1>string2
  19796.  
  19797.  ────────────────────────────────────────────────────────────────────────────
  19798.  strlen - The strlen function returns the length in bytes of the string, not
  19799.  including the terminating null character (\0).
  19800.  
  19801.  Include                           STRING.H
  19802.  
  19803.  Prototype                         size_t strlen( const char *string  );
  19804.  
  19805.  Argument                          string      Null-terminated string
  19806.  
  19807.  Returns                           The string length
  19808.  
  19809.  ────────────────────────────────────────────────────────────────────────────
  19810.  strlwr, strupr - The strlwr and strupr routines convert the characters of a
  19811.  string to lowercase and uppercase, respectively.
  19812.  
  19813.  Include                           STRING.H
  19814.  
  19815.  Prototypes                        char *strlwr( char *string  );
  19816.  
  19817.  
  19818.  
  19819.                                    char *strupr( char *string );
  19820.  
  19821.  Argument                          string      String to be converted
  19822.  
  19823.  Returns                           A pointer to a copy of the converted
  19824.                                    input string
  19825.  
  19826.  ────────────────────────────────────────────────────────────────────────────
  19827.  strnset, strset - The routines strnset and strset set the characters of a
  19828.  string to a specified character. The strnset function sets the first n
  19829.  characters in the string to the specified character. The strset function
  19830.  sets the entire string to the specified character.
  19831.  
  19832.  Include                           STRING.H
  19833.  
  19834.  Prototypes                        char *strnset( char *string,  int c,
  19835.                                    size_t n );
  19836.  
  19837.  
  19838.  
  19839.                                    char*strset( char *string, int c );
  19840.  
  19841.  Arguments                         string      String to be set
  19842.  
  19843.                                    c           Character setting
  19844.  
  19845.                                    n           Number of characters set
  19846.  
  19847.  Returns                           A pointer to string
  19848.  
  19849.  
  19850.  
  19851.  
  19852.  
  19853.  
  19854.  
  19855.  ────────────────────────────────────────────────────────────────────────────
  19856.  strtok - The strtok function finds a token in a string. A "token" is a
  19857.  series of characters delimited by a character from a specified set. For
  19858.  example, use the strtok function to break an input line into the component
  19859.  words.
  19860.  
  19861.  Include                           STRING.H
  19862.  
  19863.  Prototype                         char *strtok( char *string1,  const char
  19864.                                    *string2 );
  19865.  
  19866.  Arguments                         string1     String containing tokens
  19867.  
  19868.                                    string2     Set of delimiter characters
  19869.  
  19870.  Returns                           A pointer to a token in string1
  19871.  
  19872.  
  19873.  Time Routines
  19874.  
  19875.  Use the time routines to get the current time, convert it to a convenient
  19876.  format, and store it according to your particular needs.
  19877.  
  19878.  The current time is always taken from the system time.
  19879.  
  19880.  The time function returns the current time as the number of seconds elapsed
  19881.  since Greenwich mean time, January 1, 1970.
  19882.  
  19883.  Use the asctime, ctime, gmtime, and mktime functions to manipulate the time
  19884.  value.
  19885.  
  19886.  ────────────────────────────────────────────────────────────────────────────
  19887.  asctime - Converts a time from a structure to a character string.
  19888.  
  19889.  Include                           TIME.H
  19890.  
  19891.  Prototype                         char *asctime( const struct tm *timeptr
  19892.                                    );
  19893.  
  19894.  Argument                          timeptr     Time structure
  19895.  
  19896.  Returns                           A pointer to string result
  19897.  
  19898.  ────────────────────────────────────────────────────────────────────────────
  19899.  clock - Returns the elapsed CPU time for a process.
  19900.  
  19901.  Include                           TIME.H
  19902.  
  19903.  Prototype                         clock_t clock( void );
  19904.  
  19905.  Arguments                         None
  19906.  
  19907.  Returns                           The elapsed processor time if successful,
  19908.                                    -1  if not
  19909.  
  19910.  ────────────────────────────────────────────────────────────────────────────
  19911.  ctime - Converts time from a long integer to a character string.
  19912.  
  19913.  Include                           TIME.H
  19914.  
  19915.  Prototype                         char *ctime( const time_t *timer  );
  19916.  
  19917.  Argument                          timer       Pointer to stored time
  19918.  
  19919.  Returns                           A pointer to string result; NULL  if
  19920.                                    time represents a date
  19921.  
  19922.                                    before 1980
  19923.  
  19924.  ────────────────────────────────────────────────────────────────────────────
  19925.  difftime - Computes the difference between two times.
  19926.  
  19927.  Include                           TIME.H
  19928.  
  19929.  Prototype                         double difftime( time_t timer1, time_t
  19930.                                    timer0 );
  19931.  
  19932.  Arguments                         timer0,     Beginning and ending  times
  19933.                                    timer1
  19934.  
  19935.  Returns                           The difference in elapsed time between
  19936.                                    timer1  and timer0
  19937.  
  19938.  ────────────────────────────────────────────────────────────────────────────
  19939.  ftime - Gets current system time as structure.
  19940.  
  19941.  Includes                          SYS\TYPES.H, SYS\TIMEB.H
  19942.  
  19943.  Prototype                         void ftime( struct timeb *timeptr  );
  19944.  
  19945.  Argument                          timeptr     Pointer to time structure
  19946.  
  19947.  Returns                           Void
  19948.  
  19949.  ────────────────────────────────────────────────────────────────────────────
  19950.  gmtime - Converts time from integer to structure.
  19951.  
  19952.  Include                           TIME.H
  19953.  
  19954.  Prototype                         struct tm *gmtime( const time_t *timer
  19955.                                    );
  19956.  
  19957.  Argument                          timer       Pointer to stored time
  19958.  
  19959.  Returns                           A pointer to a structure
  19960.  
  19961.  ────────────────────────────────────────────────────────────────────────────
  19962.  mktime - Converts time to a calendar value.
  19963.  
  19964.  Include                           TIME.H
  19965.  
  19966.  Prototype                         time_t mktime( struct tm *timeptr  );
  19967.  
  19968.  Argument                          timeptr     Local time structure
  19969.  
  19970.  Returns                           The encoded calendar time if successful,
  19971.                                    -1  if not
  19972.  
  19973.  ────────────────────────────────────────────────────────────────────────────
  19974.  time - Gets current system time as a long integer.
  19975.  
  19976.  Include                           TIME.H
  19977.  
  19978.  Prototype                         time_t time( time_t *timer );
  19979.  
  19980.  Argument                          timer       Storage location for time
  19981.  
  19982.  Returns                           The elapsed time
  19983.  
  19984.  
  19985.  
  19986.  
  19987.  
  19988.  
  19989.  
  19990.  
  19991.  
  19992.  Glossary
  19993.  ────────────────────────────────────────────────────────────────────────────
  19994.  
  19995.  8087 or 80287 coprocessor:
  19996.  Intel hardware products that provide very fast and precise floating-point
  19997.  number processing.
  19998.  
  19999.  aggregate types:
  20000.  Arrays, structures, and unions.
  20001.  
  20002.  ANSI (American National Standards Institute):
  20003.  The national institute responsible for defining programming-language
  20004.  standards to promote portability of these languages between different
  20005.  computer systems. The ANSI standard for C will become official in 1990.
  20006.  
  20007.  argc:
  20008.  The traditional name for the first argument to the main function in a C
  20009.  source program. It is an integer that specifies how many arguments are
  20010.  passed to the program from the command line.
  20011.  
  20012.  argument:
  20013.  A value passed to a function.
  20014.  
  20015.  argv:
  20016.  The traditional name for the second argument to the main function in a C
  20017.  source program. It is a pointer to an array of strings. Traditionally, the
  20018.  first string is the program name, and each following string is an argument
  20019.  passed to the program from the command line.
  20020.  
  20021.  array:
  20022.  A set of elements with the same type.
  20023.  
  20024.  array pointer:
  20025.  A pointer that holds the address of any element of an array.
  20026.  
  20027.  ASCII (American Standard Code for Information Interchange):
  20028.  A set of 256 codes that many computers use to represent letters, digits,
  20029.  special characters, and other symbols. Only the first 128 of these codes are
  20030.  standardized; the remaining 128 are special characters that are defined by
  20031.  the computer manufacturer.
  20032.  
  20033.  automatic variable:
  20034.  A variable, declared in a block, whose value is discarded when the program
  20035.  exits from the block. See "static variable" and "lifetime."
  20036.  
  20037.  background color:
  20038.  A long integer representing the background color of the display screen. In
  20039.  graphics modes, the background color applies to the entire screen. In text
  20040.  modes, the background color specifies the text background for each
  20041.  character. See "foreground color."
  20042.  
  20043.  basic data types:
  20044.  The integral, enumerated, floating-point, and pointer types in the C
  20045.  language.
  20046.  
  20047.  binary file:
  20048.  A file that is not used for text processing. It may be an executable file, a
  20049.  data file, or some other nontext file.
  20050.  
  20051.  binary format:
  20052.  A method of data representation in which data are stored directly from
  20053.  memory to disk with no translations. In binary format, numeric values are
  20054.  stored as binary numbers and are not translated to ASCII characters.
  20055.  
  20056.  binary mode:
  20057.  A method of accessing files in which no translations are performed. There is
  20058.  no specific end-of-file character.
  20059.  
  20060.  binary operator:
  20061.  An operator that takes two operands. Binary operators in the C language are
  20062.  the multiplicative operators (*/), additive operators (+ -), shift operators
  20063.  (<<  >>), relational operators (< >>  <=  >=  ==  !=), bitwise operators (&
  20064.  | ^), logical operators (&& ||), and the sequential-evaluation operator (,).
  20065.  
  20066.  bit:
  20067.  A binary digit (either 0 or 1), the smallest unit of information used with
  20068.  computers. Eight bits make up one byte.
  20069.  
  20070.  bit field:
  20071.  A type of structure that allows manipulation of individual bits or groups of
  20072.  bits.
  20073.  
  20074.  bit-mapped font:
  20075.  A font in which each character is defined by (mapped to) the bits of an
  20076.  array.
  20077.  
  20078.  bitwise operator:
  20079.  
  20080.  An operator used to manipulate bits in an integer expression. Bitwise
  20081.  operators in the C language are & (AND), | (inclusive OR), ^ (exclusive OR),
  20082.   (left shift), >> (right shift), and ~ (one's complement).
  20083.  
  20084.  block:
  20085.  A sequence of declarations, definitions, and statements enclosed within
  20086.  curly braces ({}).
  20087.  
  20088.  bounding rectangle:
  20089.  An imaginary rectangle that defines the outer limits of a rounded shape such
  20090.  as an ellipse, arc, or pie.
  20091.  
  20092.  byte:
  20093.  The unit of measure used for computer memory and data storage. One byte
  20094.  contains eight bits and can store one ASCII character.
  20095.  
  20096.  case label:
  20097.  The case keyword and the constant, or constant expression, that follows it.
  20098.  
  20099.  CGA:
  20100.  IBM's Color Graphics Adapter.
  20101.  
  20102.  character code:
  20103.  A numeric code that represents a character. The default ASCII character set
  20104.  used in all PCs and PS/2s comprises 256 eight-bit character codes.
  20105.  
  20106.  character constant:
  20107.  A character enclosed in single quotes, for example, 'p'. A character
  20108.  constant has a type of char. See "string constant."
  20109.  
  20110.  character set:
  20111.  A set of alphabetic and numeric characters and symbols.
  20112.  
  20113.  clipping:
  20114.  The process of determining which parts of a graphics image lie within the
  20115.  clipping region. Parts of the image that lie outside this region are
  20116.  "clipped"; that is, they are not displayed.
  20117.  
  20118.  clipping region:
  20119.  The rectangular area of the screen where graphics display occurs.
  20120.  
  20121.  color index:
  20122.  A short integer that represents a displayable color. See "remapping" and
  20123.  "color value."
  20124.  
  20125.  color value:
  20126.  A long integer representing an absolute color. See "remapping" and "color
  20127.  index."
  20128.  
  20129.  command-line argument:
  20130.  A value passed to a program when the program begins execution.
  20131.  
  20132.  conditional expression:
  20133.  An expression consisting of three operands joined by the ternary (? :)
  20134.  operator. Similar to an if-else construct, a conditional expression is used
  20135.  to evaluate either of two expressions depending on the value of a third
  20136.  expression.
  20137.  
  20138.  constant expression:
  20139.  An expression that evaluates to a constant. A constant expression may
  20140.  involve integer constants, character constants, floating-point constants,
  20141.  enumeration constants, type casts to integral and floating-point types, and
  20142.  other constant expressions.
  20143.  
  20144.  current color:
  20145.  The color index for the color in which graphics pixels are displayed. The
  20146.  current color can be examined with _getcolor or changed with _setcolor.
  20147.  
  20148.  declaration:
  20149.  A construct that associates the name and the attributes of a variable,
  20150.  function, or type.
  20151.  
  20152.  default:
  20153.  A condition that is assumed by a program if not specified.
  20154.  
  20155.  definition:
  20156.  A construct that initializes and allocates storage for a variable or that
  20157.  specifies the name, formal parameters, body, and return type of a function.
  20158.  
  20159.  dimension:
  20160.  The number of subscripts required to specify a single array element.
  20161.  
  20162.  directive:
  20163.  An instruction to the C preprocessor to perform an action on source-program
  20164.  text before compilation.
  20165.  
  20166.  double precision:
  20167.  A real (floating-point) value that occupies eight bytes of memory. Double
  20168.  precision values are accurate to 15 or 16 digits.
  20169.  
  20170.  EGA:
  20171.  Enhanced Graphics Adapter.
  20172.  
  20173.  enumeration type:
  20174.  A user-defined data type with values that range over a set of named integral
  20175.  constants.
  20176.  
  20177.  escape sequence:
  20178.  A specific combination of a backslash (\) followed by a letter or
  20179.  combination of digits, which represents white space and nonprinting
  20180.  characters within strings and character constants.
  20181.  
  20182.  expression:
  20183.  A combination of operands and operators that yields a single value.
  20184.  
  20185.  external variable:
  20186.  A variable that is defined outside any function in a C source file and is
  20187.  used in other source files in the same program.
  20188.  
  20189.  file handle:
  20190.  An integer value that is returned when a library function that performs
  20191.  low-level input/output opens or creates a file. The file handle is used to
  20192.  refer to that file in later operations.
  20193.  
  20194.  file pointer:
  20195.  A value that keeps track of the current position in an input or output
  20196.  stream. It is updated to reflect the new position each time a read or write
  20197.  operation takes place.
  20198.  
  20199.  FILE pointer:
  20200.  A pointer to a structure of type FILE that contains information about a
  20201.  file. It is returned by library functions that create or open files and use
  20202.  stream input/output.
  20203.  
  20204.  fill flag:
  20205.  A parameter that determines whether a shape will be drawn as a solid.
  20206.  
  20207.  fill mask:
  20208.  A group of pixels that defines the pattern used to fill a graphics shape.
  20209.  
  20210.  fill pattern:
  20211.  The design defined by the fill mask and used to fill a shape.
  20212.  
  20213.  font:
  20214.  A description of the style and shapes of the characters in a character set.
  20215.  
  20216.  foreground color:
  20217.  The color index for the color in which text is displayed. See "background
  20218.  color."
  20219.  
  20220.  format specification:
  20221.  A string that specifies how the printf and scanf families of functions
  20222.  interpret input and output data.
  20223.  
  20224.  function:
  20225.  A collection of declarations and statements that has a unique name and can
  20226.  return a value.
  20227.  
  20228.  function body:
  20229.  A statement block containing the local variable declarations and statements
  20230.  of a function.
  20231.  
  20232.  function call:
  20233.  An expression that passes control and arguments (if any) to a function.
  20234.  
  20235.  function declaration:
  20236.  A declaration that states the name, return type, and storage class of a
  20237.  function that is defined explicitly elsewhere in the program.
  20238.  
  20239.  function definition:
  20240.  A definition that specifies a function's name, its formal parameters, the
  20241.  declarations and statements that define what it does, and (optionally) its
  20242.  return type and storage class.
  20243.  
  20244.  function pointer:
  20245.  A pointer that holds the address of a function.
  20246.  
  20247.  function prototype:
  20248.  A function declaration that includes a list of the names and types of formal
  20249.  parameters in the parentheses following the function name.
  20250.  
  20251.  global:
  20252.  See "visibility."
  20253.  
  20254.  graphics mode:
  20255.  See "video mode."
  20256.  
  20257.  header file:
  20258.  An external source file that contains commonly used declarations and
  20259.  definitions. The #include directive is used to insert the contents of a
  20260.  header file into a C source file.
  20261.  
  20262.  hexadecimal:
  20263.  The base-16 numbering system whose digits are 0 through F. The letters A
  20264.  through F represent the decimal numbers 10 through 15. It is often used in
  20265.  computer programming because it is easily converted to and from binary, the
  20266.  base-2 numbering system the computer itself uses.
  20267.  
  20268.  HGC:
  20269.  Hercules monochrome Graphics Card.
  20270.  
  20271.  identifier:
  20272.  A user-defined name in a C program. Identifiers name variables, functions,
  20273.  macros, constants, and data types.
  20274.  
  20275.  include file:
  20276.  See "header file."
  20277.  
  20278.  Incolor Card:
  20279.  Hercules InColor Card, a 16-color version of the HGC+.
  20280.  
  20281.  indirection:
  20282.  Accessing a data object through a pointer, rather than directly by name.
  20283.  
  20284.  initialize:
  20285.  To assign a value to a variable, often at the time the variable is declared.
  20286.  
  20287.  in-line assembler:
  20288.  The part of QuickC that converts assembly-language instructions into machine
  20289.  language.
  20290.  
  20291.  in-line assembly code:
  20292.  Assembly language instructions that appear within a QuickC source program.
  20293.  
  20294.  input/output:
  20295.  The processes involved in reading (input) and writing (output) data.
  20296.  
  20297.  integer:
  20298.  A whole number represented in the machine as a 16-bit two's-complement
  20299.  binary number. A signed integer has a range of -32,768 to 32,767. An
  20300.  unsigned integer has a range of 0 to 65,535. See "long integer."
  20301.  
  20302.  I/O:
  20303.  Abbreviation for input/output.
  20304.  
  20305.  keyword:
  20306.  A word with a special, predefined meaning for the C compiler.
  20307.  
  20308.  label:
  20309.  A unique name followed by a colon. Labels are used to denote statements to
  20310.  which a goto statement can branch. See "case label."
  20311.  
  20312.  library:
  20313.  A file containing compiled modules. The linker extracts modules from the
  20314.  library file and combines them with the user-created object file to form an
  20315.  executable program.
  20316.  
  20317.  lifetime:
  20318.  The time, during program execution, that a variable or function exists. An
  20319.  "automatic" variable has storage and a defined value only in the block where
  20320.  it is defined or declared. A "static" variable exists for the duration of
  20321.  the program.
  20322.  
  20323.  line style:
  20324.  An unsigned short integer (16 bits) that specifies the pattern with which
  20325.  lines will be drawn. Each bit specifies whether a corresponding pixel in the
  20326.  line will be displayed. The default line style is a solid line.
  20327.  
  20328.  local:
  20329.  See "visibility."
  20330.  
  20331.  long integer:
  20332.  A whole number represented inside the machine as a 32-bit two's-complement
  20333.  binary number. A signed long integer has a range of -2,147,483,648 to
  20334.  2,147,483,647. An unsigned long integer has a range of 0 to 4,294,967,295.
  20335.  See "integer."
  20336.  
  20337.  low-level input and output routines:
  20338.  Run-time library routines that perform unbuffered, unformatted I/O
  20339.  operations, for example, creat, read, write, and lseek.
  20340.  
  20341.  lvalue:
  20342.  An expression (such as a variable name) that refers to a memory location and
  20343.  is required as the left-hand operand of an assignment operation, or as the
  20344.  single operand of a unary operator.
  20345.  
  20346.  machine language:
  20347.  A series of binary numbers that a computer executes as program instructions.
  20348.  
  20349.  
  20350.  macro:
  20351.  An identifier defined in a #define preprocessor directive to represent
  20352.  another series of characters.
  20353.  
  20354.  main function:
  20355.  The function with which program execution begins (the program's entry
  20356.  point).
  20357.  
  20358.  manifest constant:
  20359.  See "symbolic constant."
  20360.  
  20361.  MCGA (Multicolor Graphics Array):
  20362.  The video subsystem integrated into the PS/2 Model 30. Also, Memory
  20363.  Controller Gate Array, one of the components of the Model 30's video
  20364.  subsystem.
  20365.  
  20366.  member:
  20367.  One of the elements of a structure or union.
  20368.  
  20369.  member-of operator:
  20370.  The dot operator (.), which is used with the name of a structure and one or
  20371.  more fields to identify a structure member.
  20372.  
  20373.  mode:
  20374.  See "video mode."
  20375.  
  20376.  monochrome display:
  20377.  A computer monitor capable of showing only two colors─black and a second
  20378.  color such as white, green, or amber. Some monochrome monitors can also show
  20379.  the second color with higher intensity or with underlined text.
  20380.  
  20381.  Monochrome Display Adapter (MDA):
  20382.  A printed-circuit card that controls the display and can show text only at
  20383.  medium resolution in one color.
  20384.  
  20385.  newline character:
  20386.  The character used to mark the end of a line in a text file, or the escape
  20387.  sequence (\n) used to represent this character.
  20388.  
  20389.  null character:
  20390.  The ASCII character encoded as the value 0, represented as the escape
  20391.  sequence (\0) in a source file. A null character marks the end of a string.
  20392.  
  20393.  null pointer:
  20394.  A pointer to nothing, expressed as the value 0.
  20395.  
  20396.  one's complement:
  20397.  The arithmetic operation in which all 1 bits are converted to 0 bits and
  20398.  vice versa. The tilde character (~) is the one's-complement operator.
  20399.  
  20400.  operand:
  20401.  A constant or variable value that is manipulated in an expression.
  20402.  
  20403.  operator:
  20404.  One or more symbols that specify how the operand or operands of an
  20405.  expression are manipulated. See "unary operator," "binary operator," and
  20406.  "ternary operator."
  20407.  
  20408.  origin:
  20409.  The point on the screen at which the x and y coordinates are both equal to
  20410.  0. On the physical screen, the origin is at the upper left corner.
  20411.  
  20412.  palette:
  20413.  The displayable colors for a given video mode. The CGA modes operate with a
  20414.  set of predetermined palette colors. The EGA, VGA, and MCGA color modes
  20415.  operate with a redefinable palette of colors.
  20416.  
  20417.  parameter:
  20418.  An identifier that receives a value passed to a function.
  20419.  
  20420.  path:
  20421.  The name that defines the location of a file or directory. A path may
  20422.  include a drive name and one or more directory names.
  20423.  
  20424.  PGA (Professional Graphics Adapter):
  20425.  Another name for IBM's PGC.
  20426.  
  20427.  physical coordinates:
  20428.  The coordinate system defined by the hardware. The physical coordinate
  20429.  system has the origin (0, 0) at the upper left corner of the screen. The
  20430.  value of x increases from left to right, and the value of y increases from
  20431.  top to bottom. See "viewport coordinates."
  20432.  
  20433.  pixel:
  20434.  A single dot on the screen. It is the smallest item that may be manipulated
  20435.  with the graphics library, and it is the basic unit of the
  20436.  viewport-coordinate system.
  20437.  
  20438.  pointer:
  20439.  A variable containing the address of another variable, function, or
  20440.  constant.
  20441.  
  20442.  pointer arithmetic:
  20443.  The use of addition or subtraction to change a pointer's value. Pointer
  20444.  arithmetic is typically used with array pointers, though it is not illegal
  20445.  on other kinds of pointers.
  20446.  
  20447.  pointer-member operator:
  20448.  The -> operator, used with structure pointers to name a structure member.
  20449.  
  20450.  pragma:
  20451.  An instruction to the compiler to perform an action at compile time.
  20452.  
  20453.  precedence:
  20454.  The relative position of an operator in the hierarchy that determines the
  20455.  order in which expressions are evaluated.
  20456.  
  20457.  preprocessor:
  20458.  A text processor that manipulates the contents of a C source file during the
  20459.  first phase of compilation.
  20460.  
  20461.  preprocessor directive:
  20462.  See "directive."
  20463.  
  20464.  prototype:
  20465.  See "function prototype."
  20466.  
  20467.  recursion:
  20468.  The process by which a function calls itself.
  20469.  
  20470.  register variable:
  20471.  An integer variable that is placed in a machine register, which may cause
  20472.  the program to be smaller and faster.
  20473.  
  20474.  remapping:
  20475.  The process of assigning new color values to color indexes. Remapping a
  20476.  color index changes the screen color of any pixels that have been drawn with
  20477.  that color index.
  20478.  
  20479.  reserved word:
  20480.  See "keyword."
  20481.  
  20482.  return value:
  20483.  The value that a function returns to the calling function.
  20484.  
  20485.  run time:
  20486.  The time during which a previously compiled and linked program is executing.
  20487.  
  20488.  run-time library:
  20489.  A file containing the routines needed to implement certain functions of the
  20490.  Microsoft QuickC language.
  20491.  
  20492.  scaling:
  20493.  The mapping of real-window coordinates to viewport coordinates.
  20494.  
  20495.  scope:
  20496.  The parts of a program in which an item can be referenced by name. The scope
  20497.  of an item may be limited to the file, function, block, or function
  20498.  prototype in which it appears.
  20499.  
  20500.  screen mode:
  20501.  See "video mode."
  20502.  
  20503.  single precision:
  20504.  A real (floating-point) value that occupies four bytes of memory. Single-
  20505.  precision values are accurate to seven decimal places.
  20506.  
  20507.  sizeof operator:
  20508.  A C operator that returns the amount of storage, in bytes, associated with
  20509.  an identifier or a type.
  20510.  
  20511.  source file:
  20512.  A text file containing C language code.
  20513.  
  20514.  standard error:
  20515.  The device to which a program sends its error messages unless the error
  20516.  output is redirected. In normal DOS operation, standard error is the
  20517.  display. The predefined stream stderr is associated with standard error in
  20518.  the C language.
  20519.  
  20520.  standard input:
  20521.  The device from which a program reads its input unless the input is
  20522.  redirected. In normal DOS operation, standard input is the keyboard. The
  20523.  predefined stream stdin is associated with standard input in the C language.
  20524.  
  20525.  standard output:
  20526.  The device to which a program sends its output unless the output is
  20527.  redirected. In normal DOS operation, standard output is the display. The
  20528.  predefined stream stdout is associated with standard output in the C
  20529.  language.
  20530.  
  20531.  static variable:
  20532.  A variable that keeps its value even after the program exits the block in
  20533.  which the variable is declared.
  20534.  
  20535.  stream:
  20536.  A sequence of bytes flowing into (input) or out of (output) a program.
  20537.  
  20538.  stream functions:
  20539.  Run-time library functions that treat data files and data items as "streams"
  20540.  of individual characters.
  20541.  
  20542.  string:
  20543.  An array of characters, terminated by a null character (\0).
  20544.  
  20545.  string constant:
  20546.  A string of characters and escape sequences enclosed in double quotes ("").
  20547.  Every string constant is an array of elements of type char. See "character
  20548.  constant."
  20549.  
  20550.  structure:
  20551.  A set of elements, which may be of different types, grouped under a single
  20552.  name.
  20553.  
  20554.  structure member:
  20555.  One of the elements of a structure.
  20556.  
  20557.  structure pointer:
  20558.  A pointer to a structure. Structure pointers identify structure members by
  20559.  specifying the name of the structure, the pointer-member operator (->), and
  20560.  the member name.
  20561.  
  20562.  symbolic constant:
  20563.  An identifier defined in a #define preprocessor directive to represent a
  20564.  constant value.
  20565.  
  20566.  tag:
  20567.  The name assigned to a structure, union, or enumeration type.
  20568.  
  20569.  ternary operator:
  20570.  An operator used in ternary (three-part) expressions. C has one ternary
  20571.  operator, the conditional operator (? :).
  20572.  
  20573.  text:
  20574.  Ordinary, readable characters, including the uppercase and lowercase letters
  20575.  of the alphabet, the numerals 0-9, and punctuation marks.
  20576.  
  20577.  text file:
  20578.  A file of ASCII characters that you can read with the TYPE command or a word
  20579.  processor.
  20580.  
  20581.  text format:
  20582.  A method of disk storage in which all data are converted to ASCII format.
  20583.  
  20584.  text mode:
  20585.  See "video mode."
  20586.  
  20587.  text window:
  20588.  A window defined in row and column coordinates where text output to the
  20589.  screen will be displayed. Text printed beyond the edge of the text window is
  20590.  not visible. The default text window is the whole screen.
  20591.  
  20592.  two's complement:
  20593.  A kind of base-2 notation used to represent positive and negative numbers in
  20594.  which negative values are formed by complementing all bits and adding 1 to
  20595.  the results.
  20596.  
  20597.  type:
  20598.  A description of a set of values. For example, the type char comprises the
  20599.  256 values in the ASCII character set.
  20600.  
  20601.  type cast:
  20602.  An operation in which a value of one type is converted to a value of a
  20603.  different type.
  20604.  
  20605.  type checking:
  20606.  An operation in which the compiler verifies that the operands of an operator
  20607.  are valid, or that the actual arguments in a function call are of the same
  20608.  types as the corresponding formal parameters in the function definition and
  20609.  function prototype.
  20610.  
  20611.  type declaration:
  20612.  A declaration that defines the name and members of a structure or union
  20613.  type, or the name and enumeration set of an enumeration type.
  20614.  
  20615.  typedef declaration:
  20616.  A declaration that defines a shorter or more meaningful name for an existing
  20617.  C data type or for a user-defined data type. Names defined in a typedef
  20618.  declaration are often referred to as "typedefs."
  20619.  
  20620.  typeface:
  20621.  The style of displayed text.
  20622.  
  20623.  type name:
  20624.  The name of a data type. See "type."
  20625.  
  20626.  type qualifier:
  20627.  The keywords short, long, signed, and unsigned, which modify a basic data
  20628.  type.
  20629.  
  20630.  type size:
  20631.  A measure of the screen area occupied by individual characters in a font,
  20632.  typically specified in pixels.
  20633.  
  20634.  unary expression:
  20635.  An expression consisting of a single operand preceded or followed by a unary
  20636.  operator.
  20637.  
  20638.  unary operator:
  20639.  An operator that takes a single operand. Unary operators in the C language
  20640.  are the complement operators (- ~ !), indirection operator (*), increment
  20641.  (++) and decrement (- -) operators, address-of operator (&), and sizeof
  20642.  operator. The unary plus (+) operator is legal but has no effect.
  20643.  
  20644.  union:
  20645.  A set of values of different types that occupy the same storage space.
  20646.  
  20647.  vector-mapped font:
  20648.  A font in which each character is defined in terms of lines and arcs.
  20649.  
  20650.  VGA (Video Graphics Array):
  20651.   Many users refer to the video subsystem integrated into the PS/2 Models 50,
  20652.  60, and 80, as well as the IBM PS/2 Display Adapter, as the "VGA."
  20653.  
  20654.  video adapter:
  20655.  A printed-circuit card that generates video output. Well-known IBM PC video
  20656.  adapters include the MDA, CGA, HGC, EGA, MCGA, and VGA Adapters.
  20657.  
  20658.  video mode:
  20659.  An integer that specifies the resolution and other characteristics of video
  20660.  output. QuickC supports 17 different video modes, although some of them are
  20661.  available only with certain video adapters.
  20662.  
  20663.  viewport:
  20664.  A clipping region in which the origin (0, 0) may be redefined. The initial
  20665.  origin of a viewport is the upper left corner.
  20666.  
  20667.  viewport coordinates:
  20668.  The integer coordinate system defined by the programmer for a specific
  20669.  viewport. By default, the viewport-coordinate system has the origin (0, 0)
  20670.  at the upper left corner of the viewport, but this may be changed by a call
  20671.  to _setvieworg.
  20672.  
  20673.  visibility:
  20674.  The parts of the program in which a particular variable or function can be
  20675.  referenced by name. An item has global visibility if it is visible in all
  20676.  source files constituting the program and local visibility if its use is
  20677.  restricted.
  20678.  
  20679.  white-space character:
  20680.  A space, tab, line-feed, carriage-return, form-feed, vertical-tab, or
  20681.  newline character.
  20682.  
  20683.  window:
  20684.  An imaginary rectangle on the screen where output takes place. See "text
  20685.  window" and "window coordinates."
  20686.  
  20687.  window coordinates:
  20688.  The coordinate system defined by the programmer.
  20689.  
  20690.