home *** CD-ROM | disk | FTP | other *** search
Wrap
Text File | 1991-03-01 | 900.0 KB | 19,668 lines
%@1@%%@AB@%Microsoft QuickC Compiler - C FOR YOURSELF%@AE@%%@EH@%%@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AB@%Microsoft(R) QuickC(R) Compiler - C FOR YOURSELF%@AE@%%@NL@% %@NL@% %@AB@%VERSION 2.5%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% %@NL@% MICROSOFT CORPORATION %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@%%@NL@% %@NL@% Information in this document is subject to change without notice and does not represent a commitment on the part of Microsoft Corporation. The software described in this document is furnished under a license agreement or nondisclosure agreement. The software may be used or copied only in accordance with the terms of the agreement. It is against the law to copy the software on any medium except as specifically allowed in the license or nondisclosure agreement. No part of this manual may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying and recording, for any purpose without the express written permission of Microsoft. (C) Copyright Microsoft Corporation, 1988, 1990. All rights reserved.%@NL@% %@NL@% Printed and bound in the United States of America.%@NL@% %@NL@% Microsoft, MS, MS-DOS, CodeView, QuickC, and XENIX are registered trademarks and Windows is a trademark of Microsoft Corporation.%@NL@% %@NL@% AT&T is a registered trademark of American Telephone and Telegraph Company.%@NL@% %@NL@% IBM and PS/2 are registered trademarks of International Business Machines Corporation.%@NL@% %@NL@% Hercules is a registered trademark and InColor is a trademark of Hercules Computer Technology.%@NL@% %@NL@% Intel is a registered trademark of Intel Corporation.%@NL@% %@NL@% Olivetti is a registered trademark of Ing. C. Olivetti.%@NL@% %@NL@% VAX is a registered trademark of Digital Equipment Corporation.%@NL@% %@NL@% %@AI@%%@AE@%%@NL@% %@NL@% Document No. SY10423-0290 OEM D703-2Z 10 9 8 7 6 5 4 3 2 1 %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@1@%%@AB@%Table of Contents%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@NL@% %@NL@% %@NL@% %@AB@%Introduction%@AE@%%@BO: 5099@%%@NL@% About This Book%@BO: 5274@%%@NL@% Using the Example Programs%@BO: 5b81@%%@NL@% Programming Style Used in This Manual%@BO: 6260@%%@NL@% Key to Document Conventions%@BO: 692a@%%@NL@% Other Books on C Programming%@BO: 7490@%%@NL@% %@NL@% %@NL@% %@AB@%PART I%@AE@%%@BO: 81fd@% %@AB@%Learning C%@AE@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@NL@% %@NL@% %@NL@% %@AB@%Chapter 1%@AE@%%@BO: 86b5@% %@AB@%Anatomy of a C Program%@AE@%%@NL@% %@NL@% A Typical C Program%@BO: 89da@%%@NL@% Comments%@BO: 8bf6@%%@NL@% Statements%@BO: 8eb7@%%@NL@% Keywords and Names%@BO: 923e@%%@NL@% Preprocessor Directives%@BO: 94b5@%%@NL@% Functions%@BO: 9a77@%%@NL@% Calling Functions%@BO: a080@%%@NL@% Declaring and Initializing Variables%@BO: a7c9@%%@NL@% External and Local Variables%@BO: ac47@%%@NL@% Function Prototypes%@BO: b186@%%@NL@% A Few Words about printf%@BO: b5ef@%%@NL@% %@NL@% %@AB@%Chapter 2%@AE@%%@BO: c3e4@% %@AB@%Functions%@AE@%%@NL@% %@NL@% Functions and Structured Programming%@BO: c690@%%@NL@% The main Function%@BO: cd12@%%@NL@% Placement and Visibility of Functions%@BO: d49b@%%@NL@% Function Definitions and Prototypes%@BO: db70@%%@NL@% Calling a Function%@BO: e170@%%@NL@% Passing Arguments to a Function%@BO: ea85@%%@NL@% Arguments Versus Parameters%@BO: f4f6@%%@NL@% Assigning Parameters%@BO: f8fd@%%@NL@% Passing by Value%@BO: 10322@%%@NL@% Returning Values from Functions%@BO: 1128e@%%@NL@% Using Return Values%@BO: 1211e@%%@NL@% Declaring a Function's Return Type%@BO: 12a14@%%@NL@% Function Prototypes%@BO: 1329c@%%@NL@% Prototyping Functions without Parameters%@BO: 13e13@%%@NL@% Prototyping Functions with Variable Parameters%@BO: 140ab@%%@NL@% Old-Style Function Declarations and Definitions%@BO: 145b0@%%@NL@% %@NL@% %@AB@%Chapter 3%@AE@%%@BO: 15403@% %@AB@%Flow Control%@AE@%%@NL@% %@NL@% Loops: while, do, and for%@BO: 157a0@%%@NL@% The while Statement%@BO: 1590a@%%@NL@% The do Statement%@BO: 164be@%%@NL@% The for Statement%@BO: 16e08@%%@NL@% Decision-Making Statements: if, else, switch, break, continue, and goto%@BO: 181f0@%%@NL@% The if Statement%@BO: 183ac@%%@NL@% The else Clause%@BO: 18f6a@%%@NL@% The switch Statement%@BO: 1989f@%%@NL@% The break Statement%@BO: 1b74e@%%@NL@% The continue Statement%@BO: 1c4c1@%%@NL@% The goto Statement%@BO: 1cb4f@%%@NL@% %@NL@% %@AB@%Chapter 4%@AE@%%@BO: 1d5ce@% %@AB@%Data Types%@AE@%%@NL@% %@NL@% Basic Data Types%@BO: 1d825@%%@NL@% Specifying Basic Types%@BO: 1db1a@%%@NL@% Specifying Variables%@BO: 1f426@%%@NL@% Specifying Constants%@BO: 1fa02@%%@NL@% Aggregate Data Types%@BO: 20f98@%%@NL@% Arrays%@BO: 2145d@%%@NL@% Structures%@BO: 2479f@%%@NL@% Unions%@BO: 288e4@%%@NL@% %@NL@% %@AB@%Chapter 5%@AE@%%@BO: 29488@% %@AB@%Advanced Data Types%@AE@%%@NL@% %@NL@% Visibility%@BO: 2980f@%%@NL@% Local Variables%@BO: 29ed3@%%@NL@% External Variables%@BO: 2ade4@%%@NL@% Visibility in Multiple Source Files%@BO: 2b898@%%@NL@% Visibility of Functions%@BO: 2c75c@%%@NL@% Lifetime%@BO: 2cddf@%%@NL@% Extending the Lives of Local Variables%@BO: 2d4b4@%%@NL@% Converting Data Types%@BO: 2df7f@%%@NL@% Ranking of Data Types%@BO: 2e47d@%%@NL@% Promotions and Demotions%@BO: 2e7b8@%%@NL@% Automatic Type Conversions%@BO: 2ecf4@%%@NL@% Manual Type Conversions through Casting%@BO: 302b3@%%@NL@% Register Variables%@BO: 30c2e@%%@NL@% Renaming Existing Types with typedef%@BO: 31945@%%@NL@% The Enumeration Type%@BO: 31ecb@%%@NL@% %@NL@% %@AB@%Chapter 6%@AE@%%@BO: 32e30@% %@AB@%Operators%@AE@%%@NL@% %@NL@% Introducing C's Operators%@BO: 33370@%%@NL@% Arithmetic Operators%@BO: 3358d@%%@NL@% Relational Operators%@BO: 33a53@%%@NL@% Assignment Operators%@BO: 3429e@%%@NL@% C's Unique Operators%@BO: 34b0c@%%@NL@% Increment and Decrement Operators%@BO: 34c2c@%%@NL@% Bitwise Operators%@BO: 35648@%%@NL@% Logical Operators%@BO: 362e1@%%@NL@% Address Operators%@BO: 36dbb@%%@NL@% Conditional Operator%@BO: 375c8@%%@NL@% The sizeof Operator%@BO: 37974@%%@NL@% Comma Operator%@BO: 37dcb@%%@NL@% Base Operator%@BO: 384e1@%%@NL@% Operator Precedence%@BO: 38659@%%@NL@% %@NL@% %@AB@%Chapter 7%@AE@%%@BO: 39f56@% %@AB@%Preprocessor Directives%@AE@%%@NL@% %@NL@% The #include Directive%@BO: 3a6f3@%%@NL@% Specifying Include Files%@BO: 3b19f@%%@NL@% The #define and #undef Directives%@BO: 3b7a3@%%@NL@% Simple Text Replacement%@BO: 3b937@%%@NL@% Function-Like Macros%@BO: 3bfdb@%%@NL@% The #undef Directive%@BO: 3cc72@%%@NL@% Conditional Directives%@BO: 3cf7c@%%@NL@% The defined Operator%@BO: 3dd70@%%@NL@% Pragmas%@BO: 3ec24@%%@NL@% %@NL@% %@AB@%Chapter 8%@AE@%%@BO: 3f2a2@% %@AB@%Pointers%@AE@%%@NL@% %@NL@% Using Pointers in C%@BO: 3f671@%%@NL@% Pointers to Simple Variables%@BO: 3faa0@%%@NL@% Declaring a Pointer Variable%@BO: 40199@%%@NL@% How Pointers Are Stored%@BO: 413dd@%%@NL@% Initializing a Pointer Variable%@BO: 4196c@%%@NL@% Using a Pointer Variable%@BO: 42427@%%@NL@% Summary of Pointer Basics%@BO: 42d9e@%%@NL@% Pointers to Arrays%@BO: 430d5@%%@NL@% Arrays and Pointer Arithmetic%@BO: 43c05@%%@NL@% Comparing Pointers%@BO: 44c3c@%%@NL@% PARRAY.C Revisited%@BO: 45138@%%@NL@% Pointers and Strings%@BO: 45ade@%%@NL@% Passing Pointers to Functions%@BO: 471d9@%%@NL@% Passing Address Constants Versus Passing Pointer Variables%@BO: 48a6d@%%@NL@% Arrays of Pointers%@BO: 49648@%%@NL@% A Pause for Reflection%@BO: 4b45c@%%@NL@% %@NL@% %@AB@%Chapter 9%@AE@%%@BO: 4b6ea@% %@AB@%Advanced Pointers%@AE@%%@NL@% %@NL@% Pointers to Pointers%@BO: 4b8e2@%%@NL@% Equivalence of Array and Pointer Notation%@BO: 4c4df@%%@NL@% Getting Command-Line Arguments%@BO: 4d72b@%%@NL@% Null Pointers%@BO: 4e1ed@%%@NL@% Pointers to Structures%@BO: 4e98e@%%@NL@% Pointers to Functions%@BO: 5010b@%%@NL@% Passing Function Pointers as Arguments%@BO: 51379@%%@NL@% A Parting Word on Pointers%@BO: 51b50@%%@NL@% %@NL@% %@AB@%Chapter 10%@AE@%%@BO: 51f42@% %@AB@%Programming Pitfalls%@AE@%%@NL@% %@NL@% Operator Problems%@BO: 52215@%%@NL@% Confusing Assignment and Equality Operators%@BO: 52307@%%@NL@% Confusing Operator Precedence%@BO: 52aab@%%@NL@% Confusing Structure-Member Operators%@BO: 53400@%%@NL@% Array Problems%@BO: 53843@%%@NL@% Array Indexing Errors%@BO: 53941@%%@NL@% Omitting an Array Subscript in Multidimensional Arrays%@BO: 53d4f@%%@NL@% Overrunning Array Boundaries%@BO: 542c0@%%@NL@% String Problems%@BO: 54694@%%@NL@% Confusing Character Constants and Character Strings%@BO: 54791@%%@NL@% Forgetting the Null Character That Terminates Strings%@BO: 54b82@%%@NL@% Forgetting to Allocate Memory for a String%@BO: 551dd@%%@NL@% Pointer Problems%@BO: 557b2@%%@NL@% Using the Wrong Address Operator to Initialize a Pointer%@BO: 5591b@%%@NL@% Declaring a Pointer with the Wrong Type%@BO: 5609e@%%@NL@% Using Dangling Pointers%@BO: 56776@%%@NL@% Library-Function Problems%@BO: 56f72@%%@NL@% Failing to Check Return Values from Library Functions%@BO: 57106@%%@NL@% Duplicating Library-Function Names%@BO: 57615@%%@NL@% Forgetting to Include Header Files for Library Functions%@BO: 57cf3@%%@NL@% Omitting the Address-Of Operator When Calling scanf%@BO: 58545@%%@NL@% Macro Problems%@BO: 58b2d@%%@NL@% Omitting Parentheses from Macro Arguments%@BO: 58ca3@%%@NL@% Using Increment and Decrement Operators in Macro Arguments%@BO: 593cc@%%@NL@% Miscellaneous Problems%@BO: 5a43c@%%@NL@% Mismatching if and else Statements%@BO: 5a4fb@%%@NL@% Misplacing Semicolons%@BO: 5ab17@%%@NL@% Omitting Double Backslashes in DOS Path Specifications%@BO: 5b5dd@%%@NL@% Omitting break Statements from a switch Statement%@BO: 5ba10@%%@NL@% Mixing Signed and Unsigned Values%@BO: 5bfed@%%@NL@% %@NL@% %@NL@% %@AB@%PART II%@AE@%%@BO: 5c92a@% %@AB@%Using C%@AE@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@NL@% %@NL@% %@NL@% %@AB@%Chapter 11%@AE@%%@BO: 5cd0a@% %@AB@%Input and Output%@AE@%%@NL@% %@NL@% Input and Output Streams%@BO: 5d111@%%@NL@% Screen and Keyboard I/O%@BO: 5d691@%%@NL@% Manipulating and Printing Strings%@BO: 5d89d@%%@NL@% Printing Numeric Values%@BO: 5fce6@%%@NL@% Using scanf for Keyboard Input%@BO: 61d67@%%@NL@% Standard Disk I/O%@BO: 63951@%%@NL@% Creating and Writing to a Text File%@BO: 63da7@%%@NL@% Reading a Text File in Binary Mode%@BO: 6575f@%%@NL@% Binary and Text Files%@BO: 669bd@%%@NL@% Text Format for Numeric Variables%@BO: 67d2f@%%@NL@% Using Binary Format%@BO: 6a107@%%@NL@% Low-Level Input and Output%@BO: 6c9fd@%%@NL@% Low-Level Reading and Writing%@BO: 6cf9a@%%@NL@% %@NL@% %@AB@%Chapter 12%@AE@%%@BO: 6ea5f@% %@AB@%Dynamic Memory Allocation%@AE@%%@NL@% %@NL@% Why Allocate?%@BO: 6ed94@%%@NL@% Memory Allocation Basics%@BO: 6f425@%%@NL@% Preparing to Allocate Memory%@BO: 7028c@%%@NL@% Specifying the Size of the Allocated Block%@BO: 70937@%%@NL@% A Graphic Illustration%@BO: 70d10@%%@NL@% Assigning the Address that malloc Returns%@BO: 71653@%%@NL@% Checking the Return from malloc%@BO: 71ae1@%%@NL@% Accessing an Allocated Memory Block%@BO: 722b1@%%@NL@% Allocating Memory for Different Data Types%@BO: 72758@%%@NL@% Deallocating Memory with the free Function%@BO: 73367@%%@NL@% Specialized Memory-Allocating Functions%@BO: 738b2@%%@NL@% The calloc Function%@BO: 73a39@%%@NL@% The realloc Function%@BO: 73f87@%%@NL@% Keeping Out of Trouble%@BO: 745d9@%%@NL@% %@NL@% %@AB@%Chapter 13%@AE@%%@BO: 74e41@% %@AB@%Graphics%@AE@%%@NL@% %@NL@% Graphics Mode%@BO: 750c7@%%@NL@% Checking the Current Video Mode%@BO: 75988@%%@NL@% Setting the Video Mode%@BO: 75f2c@%%@NL@% Writing a Graphics Program%@BO: 76931@%%@NL@% Using Color Graphics Modes%@BO: 79fdf@%%@NL@% Using the Color Video Text Modes%@BO: 7e660@%%@NL@% Text Coordinates%@BO: 7f578@%%@NL@% Graphics Coordinates%@BO: 7f95a@%%@NL@% The Physical Screen%@BO: 7fb3b@%%@NL@% Viewport Coordinates%@BO: 80c43@%%@NL@% Real Coordinates in a Window%@BO: 80e8f@%%@NL@% %@NL@% %@AB@%Chapter 14%@AE@%%@BO: 8470a@% %@AB@%Presentation Graphics%@AE@%%@NL@% %@NL@% Terminology%@BO: 84d2f@%%@NL@% Presentation Graphics Program Structure%@BO: 86fcf@%%@NL@% Five Example Chart Programs%@BO: 87d38@%%@NL@% Palettes%@BO: 8afe9@%%@NL@% Color Pool%@BO: 8b52d@%%@NL@% Style Pool%@BO: 8bf55@%%@NL@% Pattern Pool%@BO: 8c444@%%@NL@% Character Pool%@BO: 8d543@%%@NL@% Customizing Presentation Graphics%@BO: 8d6e6@%%@NL@% Chart Environment%@BO: 8d8a7@%%@NL@% titletype%@BO: 8e478@%%@NL@% axistype%@BO: 8edea@%%@NL@% windowtype%@BO: 91ee0@%%@NL@% legendtype%@BO: 92eed@%%@NL@% chartenv%@BO: 93e61@%%@NL@% An Overview of the Presentation Graphics Functions%@BO: 951d7@%%@NL@% %@NL@% %@AB@%Chapter 15%@AE@%%@BO: 95d73@% %@AB@%Fonts%@AE@%%@NL@% %@NL@% QuickC Fonts%@BO: 960d5@%%@NL@% Using QuickC's Font Library%@BO: 96dbe@%%@NL@% Register Fonts%@BO: 97290@%%@NL@% Set Current Font%@BO: 97732@%%@NL@% Display Text%@BO: 98eaa@%%@NL@% An Example Program%@BO: 9906f@%%@NL@% A Few Hints%@BO: 99e94@%%@NL@% %@NL@% %@AB@%Chapter 16%@AE@%%@BO: 9a669@% %@AB@%In-Line Assembly%@AE@%%@NL@% %@NL@% Advantages of In-Line Assembly%@BO: 9aa4c@%%@NL@% The _asm Keyword%@BO: 9af33@%%@NL@% Using Assembly Language in _asm Blocks%@BO: 9b744@%%@NL@% Instruction Set%@BO: 9b8c8@%%@NL@% Expressions%@BO: 9bba5@%%@NL@% Data Directives and Operators%@BO: 9bc91@%%@NL@% EVEN and ALIGN Directives%@BO: 9bf0b@%%@NL@% Macros%@BO: 9c0fc@%%@NL@% Segment References%@BO: 9c2fe@%%@NL@% Type and Variable Sizes%@BO: 9c41b@%%@NL@% Using C in _asm Blocks%@BO: 9cf42@%%@NL@% Using Operators%@BO: 9d42a@%%@NL@% Using C Symbols%@BO: 9d950@%%@NL@% Accessing C Data%@BO: 9de3d@%%@NL@% Writing Functions%@BO: 9e5cd@%%@NL@% Using and Preserving Registers%@BO: 9f2f2@%%@NL@% Jumping to Labels%@BO: 9fbd3@%%@NL@% Calling C Functions%@BO: a0498@%%@NL@% Defining _asm Blocks as C Macros%@BO: a09db@%%@NL@% Optimizing%@BO: a1697@%%@NL@% References and Books on Assembly Language%@BO: a2124@%%@NL@% %@NL@% %@AB@%Appendix A%@AE@%%@BO: a28b2@% %@AB@%C Language Guide%@AE@%%@NL@% %@NL@% General Syntax%@BO: a2c28@%%@NL@% User-Defined Names%@BO: a2fdd@%%@NL@% Keywords%@BO: a343d@%%@NL@% Functions%@BO: a393a@%%@NL@% Flow Control%@BO: a3efa@%%@NL@% The break Statement%@BO: a418e@%%@NL@% The continue Statement%@BO: a44ad@%%@NL@% The do Statement%@BO: a4846@%%@NL@% The for Statement%@BO: a4c3b@%%@NL@% The goto Statement%@BO: a52f6@%%@NL@% The if Statement%@BO: a55e8@%%@NL@% The return Statement%@BO: a5a3c@%%@NL@% The switch Statement%@BO: a5bdd@%%@NL@% The while Statement%@BO: a646c@%%@NL@% Data Types%@BO: a67e8@%%@NL@% Basic Data Types%@BO: a68be@%%@NL@% Aggregate Data Types%@BO: a893e@%%@NL@% Advanced Data Types%@BO: a92e4@%%@NL@% Visibility%@BO: a93be@%%@NL@% Lifetime%@BO: a9557@%%@NL@% Type Conversions%@BO: a9699@%%@NL@% User-Defined Types%@BO: a9922@%%@NL@% Enumerated Types%@BO: a9ce9@%%@NL@% Operators%@BO: aa0ec@%%@NL@% Preprocessor Directives%@BO: ab6ec@%%@NL@% Pointers%@BO: ac78b@%%@NL@% %@NL@% %@AB@%Appendix B%@AE@%%@BO: ace49@% %@AB@%C Library Guide%@AE@%%@NL@% %@NL@% Overview of the C Run-Time Library%@BO: ad133@%%@NL@% Buffer-Manipulation Routines%@BO: aefe3@%%@NL@% Character Classification and Conversion Routines%@BO: b02f5@%%@NL@% Data Conversion Routines%@BO: b143e@%%@NL@% Error Message Routines%@BO: b259d@%%@NL@% Graphics 1: Low-Level Graphics Routines%@BO: b352c@%%@NL@% Graphics 2: Presentation Graphics Routines%@BO: bf8f5@%%@NL@% Graphics 3: Font Display Routines%@BO: c254d@%%@NL@% Input and Output Routines%@BO: c3528@%%@NL@% Math Routines%@BO: cca69@%%@NL@% Memory-Allocation Routines%@BO: d00e5@%%@NL@% Process-Control Routines%@BO: d1476@%%@NL@% Searching and Sorting Routines%@BO: d20b7@%%@NL@% String-Manipulation Routines%@BO: d343e@%%@NL@% Time Routines%@BO: d6b62@%%@NL@% %@NL@% %@AB@%Glossary%@AE@%%@BO: d7f4f@%%@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A-Intro @%%@1@%%@AB@%Introduction%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% Ever since Microsoft introduced the QuickC(R) Compiler, version 1.0 in 1987, QuickC users have asked for more information on the C programming language. %@AI@%C for Yourself%@AE@% answers that need, particularly for those who have some programming experience but are new to the C language. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00000001 @%%@AB@%About This Book%@AE@%%@EH@%%@NL@% %@NL@% %@AI@%C for Yourself%@AE@% assumes you have programmed before but are not familiar with C. Thus, it doesn't explain basic programming ideas such as why program loops are useful. It assumes that you already know about loops in general and now want to learn how to write them in the C language. The following list summarizes the book's contents: %@NL@% %@NL@% %@NL@% ■ Part 1, "Learning C," covers basic C language topics such as functions and data types. The chapters in this section are designed to be read in order, from beginning to end.%@NL@% %@NL@% ■ Part 2, "Using C," covers practical programming topics such as input/output and graphics. This section is organized topically, so you don't have to read the chapters in any particular order.%@NL@% %@NL@% ■ Appendix A, "C Language Guide," summarizes the QuickC implementation of the C language. You can use this appendix as a quick reference once you have read Part 1 and have some familiarity with C.%@NL@% %@NL@% ■ Appendix B, "C Library Guide," summarizes the most commonly used functions in the QuickC run-time library. This appendix is designed mainly for browsing when you're not using QuickC. When you are in the QuickC environment, use the Microsoft(R) QuickC Advisor (online help) to get information about C language features and run-time library functions. %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The pages that follow use the term "OS/2" to refer to the OS/2 systems─ %@AI@%Microsoft %@AI@%(R)%@AE@%%@AI@%%@AE@%%@AI@% Operating System/2 (MS %@AE@%%@AI@%(R)%@AE@%%@AI@%%@AE@%%@AI@% OS/2) and IBM%@AE@%%@AI@% %@AE@%%@AI@%(R)%@AE@%%@AI@%%@AE@%%@AI@% OS/2. Similarly, %@AI@%the term "DOS" refers to both the MS-DOS%@AE@%%@AI@% (R)%@AE@%%@AI@%%@AE@%%@AI@% and IBM%@AE@%%@AI@% %@AE@%%@AI@%(R) %@AE@%%@AI@%%@AE@%%@AI@%Personal Computer %@AI@%DOS operating systems. The name of a specific operating system is used when %@AI@%it is necessary to note features that are unique to that system.%@AE@%%@AI@%%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00000002 @%%@AB@%Using the Example Programs%@AE@%%@EH@%%@NL@% %@NL@% The example programs in this book are available through online help. This feature allows you to load, run, and experiment with example programs as you read. %@NL@% %@NL@% %@AU@% You can use online help to load and run example programs.%@AE@% %@NL@% %@NL@% You must be using the QuickC environment to load an example. To load the program, select Contents from the Help menu, then select the title of this book. Find the desired program in Help, then copy it into the editor using QuickC's Copy and Paste functions. %@NL@% %@NL@% After you copy a sample program into the QuickC Editor, you can treat it as you would any C source program. You can compile or edit the program, save it on disk, and so on. %@NL@% %@NL@% QuickC online help includes all the significant examples in this book (it doesn't include code fragments and some very short programs). Every program that is in online help begins with a line in this general form: %@NL@% %@NL@% %@AS@% /* POINTER.C: Demonstrate pointer basics. */%@AE@%%@NL@% %@NL@% The line contains the program's name and a brief description of what it does. The program containing the above line is listed as POINTER.C in online help. %@NL@% %@NL@% All the examples available in online help compile without errors at Warning Level 3, in which QuickC does the most stringent error-checking. At this Warning Level, some examples will generate the following harmless warnings: %@NL@% %@NL@% %@AS@% C4103: 'main' : function definition used as prototype %@AS@% C4035: 'main' : no return value %@AS@% C4051: data conversion%@AE@%%@NL@% %@NL@% You can eliminate these warnings by compiling at a lower Warning Level. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00000003 @%%@AB@%Programming Style Used in This Manual%@AE@%%@EH@%%@NL@% %@NL@% The C language allows considerable flexibility in formatting source code. The style used in this book is recommended for program readability, but you do not have to use it when writing your programs. Below is a list of style guidelines used in this book for example programs: %@NL@% %@NL@% %@NL@% ■ Each example program begins with a comment that names the program and states what it does.%@NL@% %@NL@% ■ Each statement or function is listed on its own line.%@NL@% %@NL@% ■ Variable and function names are in lowercase. The names of symbolic constants, such as TRUE or FALSE, are in uppercase.%@NL@% %@NL@% ■ If a function doesn't take any arguments, an opening and a closing parenthesis follow the function name with no extra space: %@NL@% %@AS@% getch();%@AE@%%@NL@% %@NL@% %@NL@% ■ If a function takes arguments, a space appears after the opening parenthesis and before the closing parenthesis: %@NL@% %@AS@% printf( "Number = %i", num_penguins );%@AE@%%@NL@% %@NL@% %@NL@% ■ Binary operators such as addition and subtraction are preceded and followed by a space: %@NL@% %@AS@% 3 + 5%@AE@%%@NL@% %@NL@% %@NL@% ■ If parentheses are used to control operator precedence, no extra spaces are included: %@NL@% %@AS@% (3 + 5) * 2%@AE@%%@NL@% %@NL@% %@NL@% ■ Opening and closing braces are aligned under the first character of the controlling keyword. The block underneath is indented 3 spaces: %@NL@% %@AS@% if( a == b ) %@AS@% { %@AS@% c = 50; %@AS@% printf( "%i\n", a ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00000004 @%%@AB@%Key to Document Conventions%@AE@%%@EH@%%@NL@% %@NL@% This book uses the following document conventions: %@NL@% %@NL@% %@AB@%Example%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% COPY TEST.OBJ C: Uppercase letters represent DOS commands and file names. %@AB@%printf%@AE@% Boldface letters indicate standard features of the C language: keywords, operators, and standard library functions. %@AI@%expression%@AE@% Words in italics indicate placeholders for information you must supply, such as a file name. Italics are also occasionally used for emphasis in the text. %@AS@%main()%@AE@% This typeface is used for example %@AS@%{%@AE@% programs, program fragments, and the %@AS@%}%@AE@% names of user-defined functions and variables. It also indicates user input and screen output. %@AS@% %@AE@% %@AB@%CL%@AE@% %@AI@%options%@AE@% «%@AI@%files...%@AE@%» A horizontal ellipsis following an item indicates that more items having the same form may follow. %@AS@%while( )%@AE@%%@AS@%%@AE@% A vertical ellipsis tells you that part %@AS@%{%@AE@% of the example program has been %@AS@% .%@AE@% intentionally omitted. %@AS@% .%@AE@% %@AS@% .%@AE@% %@AS@%}%@AE@% SHIFT Small capital letters denote names of keys on the keyboard. A plus sign ( + ) indicates a combination of keys. For example, SHIFT+F5 tells you to hold down the SHIFT key while pressing the F5 key. "array pointer" The first time a new term is defined, it is enclosed in quotation marks. Since some knowledge of programming is assumed, common terms such as memory or branch are not defined. American National Standards The first time an acronym appears, it is Institute (ANSI) spelled out. %@NL@% %@2@%%@CR:C6A00000005 @%%@AB@%Other Books on C Programming%@AE@%%@EH@%%@NL@% %@NL@% This book provides an introduction to the C language and some practical programming topics. It does not attempt to teach you basic computer programming or advanced C programming techniques. The following books cover a variety of topics that you may find useful. They are listed only for your convenience. With the exception of its own publications, Microsoft does not endorse these books or recommend them over others on the same subject. %@NL@% %@NL@% Feibel, Werner. %@AI@%Advanced QuickC%@AE@%, 2d ed. Berkeley, California: Osborne McGraw-Hill, 1989.%@NL@% %@NL@% %@STUB@% An intermediate-level C programming guide using QuickC. It includes data structures, parsing, simulations, and the DOS interface.%@NL@% %@NL@% Hancock, Les, and Morris Krieger. %@AI@%The C Primer%@AE@%, 2d ed. New York: McGraw-Hill, 1986.%@NL@% %@NL@% %@STUB@% A beginner's guide to C programming.%@NL@% %@NL@% Hansen, Augie. %@AI@%Proficient C%@AE@%. Redmond, Washington: Microsoft Press, 1987.%@NL@% %@NL@% %@STUB@% An intermediate-level guide to C programming.%@NL@% %@NL@% Harbison, Samuel P., and Guy L. Steele. %@AI@%C: A Reference Manual%@AE@%, 2d ed. Englewood Cliffs, New Jersey: Prentice-Hall, 1987.%@NL@% %@NL@% %@STUB@% A comprehensive guide to the C language and the standard library.%@NL@% %@NL@% Hergert, Douglas. %@AI@%The ABC's of QuickC%@AE@%. Alameda, California: SYBEX, Inc., 1989.%@NL@% %@NL@% %@STUB@% A beginner's guide to QuickC programming.%@NL@% %@NL@% Kernighan, Brian W., and Dennis M. Ritchie. %@AI@%The C Programming Language%@AE@%, 2d ed. Englewood Cliffs, New Jersey: Prentice Hall, 1988.%@NL@% %@NL@% %@STUB@% The first edition of this book is the classic definition of the C language. The second edition includes new information on the proposed ANSI C standard.%@NL@% %@NL@% Lafore, Robert. %@AI@%Microsoft C Programming for the IBM%@AE@%. Indianapolis, Indiana: Howard W. Sams & Company, 1987.%@NL@% %@NL@% %@STUB@% The first half of the book teaches C. The second half concentrates on specifics of the PC environment, such as BIOS calls, memory, and video displays.%@NL@% %@NL@% Plum, Thomas. %@AI@%Learning to Program in C%@AE@%. Hasbrouck Heights, New Jersey: Hayden Book Company, 1983.%@NL@% %@NL@% %@STUB@% A widely used introductory college text on computer programming in C.%@NL@% %@NL@% Schustack, Steve. %@AI@%Variations in C%@AE@%. Redmond, Washington: Microsoft Press, 1985.%@NL@% %@NL@% %@STUB@% An intermediate-level guide to developing business applications in C.%@NL@% %@NL@% Waite, Mitchell, Stephen Prate, Bryan Costales, and Harry Henderson (The Waite Group). %@AI@%Microsoft QuickC Programming%@AE@%. Redmond, Washington: Microsoft Press, 1988.%@NL@% %@NL@% %@STUB@% Beginning- to intermediate-level C programming, with special emphasis on the QuickC Compiler.%@NL@% %@NL@% Ward, Robert. %@AI@%Debugging C%@AE@%. Indianapolis, Indiana: Que Corporation, 1986.%@NL@% %@NL@% %@STUB@% An advanced guide to the theory and practice of debugging C programs.%@NL@% %@NL@% Wilton, Richard. %@AI@%Programmer's Guide to PC and PS/2 Video Systems%@AE@%. Redmond, Washington: Microsoft Press, 1987.%@NL@% %@NL@% %@STUB@% An advanced guide to all the PC and PS/2(R) video modes.%@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A-Part 01 @%%@1@%%@AB@%PART I Learning C%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% The C language has steadily increased in popularity since it was created in the early 1970s. C is currently the language of choice for many professional software developers and is becoming quite popular among nonprofessional programmers, as well. %@NL@% %@NL@% %@AI@%C for Yourself%@AE@% is divided into two parts. Part 1 is called "Learning C" and discusses the C language itself. This part assumes you know the fundamentals of computer programming but do not know C. Experienced C programmers may only want to skim these chapters. Part 2, "Using C," discusses practical programming capabilities, such as graphics, which are provided in the QuickC run-time library. It should be read after you have finished Part 1 and have some familiarity with the C language. %@NL@% %@NL@% Part 1 begins with basic topics such as data types and functions, and it progresses to more advanced subjects such as pointers. This part of the book closes with a discussion of common C programming pitfalls. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00010001 @%%@1@%%@AB@%Chapter 1 Anatomy of a C Program%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% As a knowledgeable programmer, you'll probably be tempted to immerse yourself in C immediately. But before taking that plunge, you should know the basic model for all C programs. This chapter sketches the anatomy of a C program without getting bogged down in formal definitions or exceptions to the rules. (You'll find plenty of rules in the chapters that follow.) %@NL@% %@NL@% The discussion revolves around a short, reasonably typical C program named VOLUME.C. To get comfortable with the look of C programs, as well as the basic ideas that shape them, refer to VOLUME.C frequently as you read. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010002 @%%@AB@%A Typical C Program%@AE@%%@EH@%%@NL@% %@NL@% VOLUME.C is a simple program that calculates the volume of a sphere and prints the following result on the screen: %@NL@% %@NL@% %@AS@% Volume: 113.040001%@AE@%%@NL@% %@NL@% Like all of the sample programs in this book, you'll find VOLUME.C in QuickC's online help. The "Introduction" explains how to load sample programs. Figure 1.1 illustrates the VOLUME.C program. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010003 @%%@AB@%Comments%@AE@%%@EH@%%@NL@% %@NL@% The first line in VOLUME.C is a comment: %@NL@% %@NL@% %@AS@% /* VOLUME.C: Calculate sphere's volume. */%@AE@%%@NL@% %@NL@% %@AU@% Comments make a program more readable.%@AE@% %@NL@% %@NL@% In C, a comment begins with a slash-asterisk (%@AB@%/*%@AE@%) and ends with an asterisk-slash (%@AB@%*/ %@AE@%). Because C is a compact language with very few keywords, comments play an important role in making your programs readable. %@NL@% %@NL@% You can't nest comments (put one comment inside another). The following line creates a syntax error: %@NL@% %@NL@% %@AS@% /* Error! /* You can't */ nest comments in C. */%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010004 @%%@AB@%Statements%@AE@%%@EH@%%@NL@% %@NL@% C statements always end with semicolons. Here is a statement from the VOLUME.C program: %@NL@% %@NL@% %@AS@% result = 4 * PI * result;%@AE@%%@NL@% %@NL@% %@AU@% Statement blocks are enclosed in braces.%@AE@% %@NL@% %@NL@% You can also enclose a group of statements in braces, making a "statement block." Statement blocks contain related statements, such as the statements in the body of a function. %@NL@% %@NL@% The C language ignores white space (tabs, blanks, and line breaks) in your source program, so you can arrange your program in almost any style. However, a few de facto rules help promote readability. A typical C program is written with one statement per line. Braces align vertically, and statements inside braces are indented. The "Introduction" describes the programming style used in this book. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010005 @%%@AB@%Keywords and Names%@AE@%%@EH@%%@NL@% %@NL@% C is a case-sensitive language (it distinguishes between uppercase and lowercase letters). All of C's keywords are spelled completely in lowercase; online help contains a complete list of C keywords. %@NL@% %@NL@% You can declare names in any combination of either case, but many programmers prefer to use lowercase for variable and function names, saving uppercase for declaring symbolic constants. (A "symbolic constant" is a descriptive name that represents a constant value. In VOLUME.C, %@AS@% PI %@AE@% is a symbolic constant.) %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010006 @%%@AB@%Preprocessor Directives%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A preprocessor directive is a command to the QuickC compiler.%@AE@% %@NL@% %@NL@% Not every line in a C program is an executable statement. Programs can also contain "preprocessor directives"─ commands for the QuickC compiler. A directive begins with a number sign (%@AB@%#%@AE@%) and does not end with a semicolon. %@NL@% %@NL@% The second and third lines of VOLUME.C contain preprocessor directives. The %@AB@%#include%@AE@% directive in the second line tells QuickC to insert the file STDIO.H when it compiles VOLUME.C: %@NL@% %@NL@% %@AS@% #include <stdio.h>%@AE@%%@NL@% %@NL@% STDIO.H is one of the many "header files" supplied with QuickC. Header files contain declarations and definitions required by C library functions. ("Library functions" are supplied with QuickC rather than written by you.) In the VOLUME.C program, the %@AB@%printf%@AE@% library function requires information from the STDIO.H header file. %@NL@% %@NL@% The %@AB@%#define%@AE@% directive in the third line defines a symbolic constant named %@AS@% %@AS@%PI%@AE@%: %@NL@% %@NL@% %@AS@% #define PI 3.14%@AE@%%@NL@% %@NL@% Wherever %@AS@% PI %@AE@% appears later in the source program, QuickC substitutes the text %@AS@% 3.14%@AE@%. The text can be any combination of letters, digits, or other characters. The effect is much like a search and replace operation in a word processor. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010007 @%%@AB@%Functions%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A function performs a specific task and can also return a value.%@AE@% %@NL@% %@NL@% Functions are the building blocks of C. Every C program has at least one function, and every executable C statement appears inside some function or another. In plain English, a "function" is a group of statements that performs a specific task and often returns a value to the statement that calls it. %@NL@% %@NL@% C functions serve the same purposes as QuickPascal procedures and functions or BASIC %@AB@%SUB%@AE@% and %@AB@%FUNCTION%@AE@% procedures. They allow you to write wellorganized programs that perform different tasks in separate parts. %@NL@% %@NL@% %@AU@% The C language has no input/output statements.%@AE@% %@NL@% %@NL@% C also uses functions to perform all input and output (I/O). Unlike other high-level languages, C has no I/O statements such as %@AB@%PRINT%@AE@% or %@AB@%READ%@AE@%. Instead, all I/O is done by calling C library functions such as %@AB@%printf%@AE@%. %@NL@% %@NL@% %@AU@% Every C program has a function named%@AE@%%@AB@% main.%@AE@% %@NL@% %@NL@% The VOLUME.C program contains two functions, named %@AB@%main%@AE@% and %@AS@%sphere%@AE@% (see Figure 1.1). The main execution section of every C program is itself a function named %@AB@%main,%@AE@% which marks where execution starts and ends. When you run VOLUME.C, execution starts at the beginning of the %@AB@%main%@AE@% function and stops at the end of %@AB@%main%@AE@%. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010008 @%%@AB@%Calling Functions%@AE@%%@EH@%%@NL@% %@NL@% Functions can be called (executed) from anywhere in a program, and they can receive values as well as return them. A value that you pass (send) to a function is called an "argument." %@NL@% %@NL@% Calling a C function is a simple matter. You state the name of the function and supply in parentheses any arguments you want to pass to it. You must place a comma between arguments. %@NL@% %@NL@% The VOLUME.C program contains two function calls, one to the %@AB@%printf%@AE@% library function and the other to the %@AS@% sphere %@AE@% function, which is defined in the program. The following statement calls the %@AB@%printf%@AE@% function: %@NL@% %@NL@% %@AS@% printf( "Volume: %f\n", volume );%@AE@%%@NL@% %@NL@% The statement passes two arguments to %@AB@%printf%@AE@%. The first, %@AS@%"Volume: %f\n"%@AE@%, supplies text and some formatting information. The second, %@AS@% volume%@AE@%, supplies a numeric value. See "A Few Words about %@AB@%printf%@AE@%," below, for more information. %@NL@% %@NL@% In C, a function does not necessarily have to return a value. It can either return a value (like a QuickPascal function) or return nothing (like a QuickPascal procedure). %@NL@% %@NL@% When a function returns a value, the value is often assigned to a variable. The following statement from VOLUME.C calls the %@AS@% sphere %@AE@% function and assigns its return value to the variable %@AS@% volume%@AE@%: %@NL@% %@NL@% %@AS@% volume = sphere( radius );%@AE@%%@NL@% %@NL@% A function uses the %@AB@%return%@AE@% keyword to return a value. In VOLUME.C, the last statement in the %@AS@% sphere %@AE@% function returns the value of the variable %@AS@% result %@AS@%%@AE@% to the statement that calls %@AS@% sphere%@AE@%: %@NL@% %@NL@% %@AS@% return result;%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010009 @%%@AB@%Declaring and Initializing Variables%@AE@%%@EH@%%@NL@% %@NL@% You must "declare" every variable in a C program by stating its name and type. If you refer to an undeclared variable, QuickC displays an error message when you compile the program. %@NL@% %@NL@% The following statement from VOLUME.C declares a %@AB@%float%@AE@% (floating-point) type variable named %@AS@% volume%@AE@%: %@NL@% %@NL@% %@AS@% float volume;%@AE@%%@NL@% %@NL@% After declaring a variable, you should "initialize" it─give it an initial value─before using it. Uninitialized variables might have any value, so they are dangerous to use. The VOLUME.C program initializes the variable %@AS@% volume %@AE@% by as- signing it the return value from a function call: %@NL@% %@NL@% %@AS@% volume = sphere( radius );%@AE@%%@NL@% %@NL@% You can also initialize a variable when it is declared, a convenient and common practice. The following statement from VOLUME.C declares the variable %@AS@% radius %@AE@% as an %@AB@%int%@AE@% (integer) variable and initializes it with the value 3: %@NL@% %@NL@% %@AS@% int radius = 3;%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010010 @%%@AB@%External and Local Variables%@AE@%%@EH@%%@NL@% %@NL@% The place where you declare a variable controls where it is visible. A variable declared outside any function is "external": you can refer to it anywhere within the program. (External variables are called "global" in some other languages.) %@NL@% %@NL@% A variable declared inside the braces of a function is "local." You can refer to it inside the function but nowhere else. In VOLUME.C, the %@AS@% result %@AE@% variable is declared inside the %@AS@% sphere %@AE@% function: %@NL@% %@NL@% %@AS@% float sphere( int rad ) %@AS@% { %@AS@% float result; %@AS@% . %@AS@% . %@AS@% . %@AS@% }%@AE@%%@NL@% %@NL@% %@AU@% Use external variables only when necessary.%@AE@% %@NL@% %@NL@% Because it is local to the %@AS@% sphere %@AE@% function, the %@AS@% result %@AE@% variable cannot be used elsewhere in VOLUME.C. Making variables local whenever possible minimizes the risk that a variable's value will be changed accidentally in some other part of the program. %@NL@% %@NL@% When a function receives arguments, the arguments become local variables within the function. The %@AS@% sphere %@AE@% function requires one argument, which it names %@AS@% rad%@AE@%. Within the function, %@AS@% rad %@AE@% is a local variable. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010011 @%%@AB@%Function Prototypes%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Function prototypes allow QuickC to check every function reference for %@AU@%accuracy.%@AE@% %@NL@% %@NL@% A function can be declared in much the same way as a variable. Function declarations, often called "prototypes," allow QuickC to do "type checking." Given the information in the prototype, QuickC can check every subsequent use of the function to make sure you pass the right number and type of arguments and use the correct return type. %@NL@% %@NL@% A function prototype gives the following information: %@NL@% %@NL@% %@NL@% ■ The function's name%@NL@% %@NL@% ■ The type of value the function returns%@NL@% %@NL@% ■ A list of arguments the function requires%@NL@% %@NL@% %@NL@% The VOLUME.C program contains one function prototype, for the %@AS@% sphere %@AE@% function: %@NL@% %@NL@% %@AS@% float sphere( int rad );%@AE@%%@NL@% %@NL@% The prototype states that the %@AS@% sphere %@AE@% function returns a %@AB@%float%@AE@% (floating-point) value and requires one %@AB@%int%@AE@% (integer) argument. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00010012 @%%@AB@%A Few Words about printf%@AE@%%@EH@%%@NL@% %@NL@% The VOLUME.C program, like most examples in this book, uses the %@AB@%printf%@AE@% library function to display text. You won't need to know all of the details of %@AB@%printf%@AE@% to read the rest of this book, but the examples will be easier to follow if you know a few basic concepts. %@NL@% %@NL@% The %@AB@%printf%@AE@% function works like the QuickBASIC %@AB@%PRINT USING%@AE@% statement or the QuickPascal %@AB@%Writeln%@AE@% procedure. It can display string and numeric data in various formats, and it normally prints to the screen. %@NL@% %@NL@% You can print a simple message by passing %@AB@%printf%@AE@% a string (characters in double quotes) as an argument: %@NL@% %@NL@% %@AS@% printf( "Hi, Mom!" );%@AE@%%@NL@% %@NL@% The statement prints %@NL@% %@NL@% %@AS@% Hi, Mom!%@AE@%%@NL@% %@NL@% The %@AB@%printf%@AE@% function doesn't automatically add a newline character at the end of a line. The statements %@NL@% %@NL@% %@AS@% printf( "Le Nozze di Figaro" ); %@AS@% printf( " by W. A. Mozart" );%@AE@%%@NL@% %@NL@% print the following message on one line: %@NL@% %@NL@% %@AS@% Le Nozze di Figaro by W. A. Mozart%@AE@%%@NL@% %@NL@% To start a new line, use the escape sequence %@AB@%\n%@AE@% as follows: %@NL@% %@NL@% %@AS@% printf( "Hi,\nMom!" );%@AE@%%@NL@% %@NL@% The statement prints two words on separate lines: %@NL@% %@NL@% %@AS@% Hi, %@AS@% Mom!%@AE@%%@NL@% %@NL@% The%@AB@% f%@AE@% in %@AB@%printf%@AE@% stands for formatting. To print the values of variables and other items, you supply %@AB@%printf%@AE@% with format codes that tell %@AB@%printf%@AE@% the proper format for each item. The codes are placed in the first argument, which is enclosed in double quotes. %@NL@% %@NL@% The following statement uses the %@AB@%%x%@AE@% code to print the integer 553 in hexadecimal format. It passes two arguments to %@AB@%printf%@AE@%: %@NL@% %@NL@% %@AS@% printf( "%x", 553 );%@AE@%%@NL@% %@NL@% The first argument (%@AS@%"%x"%@AE@%) contains the format code and the second argument (%@AS@%553%@AE@%) contains the item to be formatted. The line displays the following: %@NL@% %@NL@% %@AS@% 229%@AE@%%@NL@% %@NL@% The %@AB@%printf%@AE@% function accepts several other format codes. For instance, the VOLUME.C program uses %@AB@%%f%@AE@% to print a floating-point number. Some programs in later chapters use %@AB@%%d%@AE@% to print integers or %@AB@%%ld%@AE@% to print long integers. %@NL@% %@NL@% The first argument passed to %@AB@%printf%@AE@% can contain any combination of characters and format codes. The other arguments contain the items that you want %@AB@%printf%@AE@% to format. The statement %@NL@% %@NL@% %@AS@% printf( "%d times %d = %d\n", 2, 128, 2 * 128 );%@AE@%%@NL@% %@NL@% prints the line: %@NL@% %@NL@% %@AS@% 2 times 128 = 256%@AE@%%@NL@% %@NL@% The %@AB@%printf%@AE@% function matches the format codes to the items you want to format, in left-to-right order. In the code above, the first %@AB@%%d%@AE@% formats the number 2, the second formats the 128, and the third formats the expression 2 * 128 (which evaluates to the number 256). %@NL@% %@NL@% There's much more to say about %@AB@%printf%@AE@% and other I/O functions, but the rest can wait until you reach Chapter 11, "Input and Output," which describes I/O in detail. %@NL@% %@NL@% Now that you've glimpsed the big picture, we can take a closer look at some specifics of C programming, beginning with Chapter 2, "Functions." %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00020001 @%%@1@%%@AB@%Chapter 2 Functions%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% Chapter 1, "Anatomy of a C Program," introduced functions, the building blocks of C programs. In this chapter, you'll learn how to use functions in C programs. %@NL@% %@NL@% We begin by discussing some function basics, including the role of the %@AB@%main%@AE@% function. We then show you how to call functions, pass data to them, return data from them, and declare them. The chapter concludes with a brief look at old-style function declarations, which you may encounter in some programs. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020002 @%%@AB@%Functions and Structured Programming%@AE@%%@EH@%%@NL@% %@NL@% As we mentioned in Chapter 1, a C function is a collection of statements, enclosed in braces (%@AS@%{ }%@AE@%), which performs a particular task. It can receive arguments (data) and also return a value. %@NL@% %@NL@% Functions allow you to program with a "divide and conquer" strategy. Rather than try to solve a large problem all at once, you break the problem into several parts and attack each one separately. This approach, known as "structured programming," allows you to write clear, reliable programs that perform separate tasks in discrete, logically contained modules. In the C language, these modules are called functions. %@NL@% %@NL@% Functions offer several advantages. They can %@NL@% %@NL@% %@NL@% ■ Make programs easier to write and read. All of the statements related to a task are located in one place.%@NL@% %@NL@% ■ Prevent unexpected side effects by using private (local) variables that are not visible to other parts of the program.%@NL@% %@NL@% ■ Eliminate unnecessary repetition of code for frequently performed tasks.%@NL@% %@NL@% ■ Simplify debugging. Once the function works reliably, you can use it with confidence in many different situations.%@NL@% %@NL@% %@NL@% If you know QuickPascal or QuickBASIC, you will see many similarities in the C language. A C function serves the same basic purpose as a QuickPascal function or procedure or a QuickBASIC %@AB@%FUNCTION%@AE@% or %@AB@%SUB%@AE@% procedure. In later sections, we'll note some differences between C and these languages. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020003 @%%@AB@%The main Function%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Every C program must have one and only one main function.%@AE@% %@NL@% %@NL@% Every C program must have a function named %@AB@%main%@AE@%, which tells where program execution begins and ends. Although %@AB@%main%@AE@% is not a C keyword, it has only one use: naming the %@AB@%main%@AE@% function. A program must have only one %@AB@%main%@AE@% function, and you shouldn't use the name anywhere else. %@NL@% %@NL@% Below is the simplest possible C program: %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% }%@AE@%%@NL@% %@NL@% The braces (%@AS@%{ }%@AE@%) mark the %@AB@%main%@AE@% function's beginning and end, as they do in every function. This program doesn't contain any executable statements; it simply begins and ends. %@NL@% %@NL@% Most functions have executable statements, of course, and these appear within the function's braces. The following program contains a statement which prints %@AS@% Hello, world! %@AE@% on the screen: %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% printf( "Hello, world!\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% The %@AB@%main%@AE@% function is called by the operating system when it runs your program. While it's possible to call the %@AB@%main%@AE@% function in a program, you should never do so, just as you wouldn't write a QuickBASIC program containing the line %@NL@% %@NL@% %@AS@% 10 GOSUB 10%@AE@%%@NL@% %@NL@% A program that calls %@AB@%main%@AE@% will start again and again in an endless loop that eventually triggers a run-time error. %@NL@% %@NL@% Like all functions, %@AB@%main%@AE@% can accept arguments and return a value. Through this mechanism, your program can receive command-line arguments from DOS when it begins execution and return a value to DOS when it ends. Chapter 9, "Advanced Pointers," describes how to receive command-line arguments via %@AB@%main%@AE@%. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020004 @%%@AB@%Placement and Visibility of Functions%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A function is normally visible everywhere in the program.%@AE@% %@NL@% %@NL@% Every C function is normally "visible" to all other functions in the same program. That is, it can call and be called by any other function. C functions can even call themselves, a process known as "recursion." %@NL@% %@NL@% In the program below, the functions %@AS@% whiz %@AE@% and %@AS@% bang %@AE@% are visible to %@AB@%main%@AE@% and to each other. The %@AB@%main %@AE@% function can call both %@AS@% whiz %@AE@% and %@AS@% bang%@AE@%. In addition, %@AS@% whiz %@AE@% can call %@AS@% bang%@AE@%, and vice versa. %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% } %@AS@% %@AS@% whiz() %@AS@% { %@AS@% } %@AS@% %@AS@% bang() %@AS@% { %@AS@% }%@AE@%%@NL@% %@NL@% Functions can appear in any order and at almost any place in your program. Since %@AB@%main%@AE@% starts and ends the program's execution, this function often begins the program. But this is a readability convention, not a language requirement. %@NL@% %@NL@% %@AU@% C functions can't be nested.%@AE@% %@NL@% %@NL@% One place where you can't put a function is inside another function. The C language doesn't allow you to nest functions. Here C differs from QuickPascal, in which one procedure can contain other "hidden" functions or procedures. The following program causes a syntax error because the %@AS@% bang %@AE@% function appears within the %@AS@% whiz %@AE@% function: %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% } %@AS@% %@AS@% whiz() %@AS@% { %@AS@% /* Error! Incorrect function placement */ %@AS@% bang() %@AS@% { %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020005 @%%@AB@%Function Definitions and Prototypes%@AE@%%@EH@%%@NL@% %@NL@% Now that you understand some function basics, we can look at functions in more detail. A function, or more precisely, "function definition," contains several parts. Figure 2.1 shows the parts of the %@AS@% sphere %@AE@% function definition from the VOLUME.C example in Chapter 1, "Anatomy of a C Program." %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% The function "header" specifies the type of value a function returns and the function's name. The header also contains an argument list, which specifies the arguments the function requires. The rest of the function definition─everything inside the braces─is the function "body." %@NL@% %@NL@% The ANSI C standard, which QuickC follows, recommends that you supply a function "prototype" (declaration) for every function definition in your program. The prototype is identical to the function header except that it ends with a semicolon. Figure 2.2 shows the %@AS@% sphere %@AE@% function prototype from VOLUME.C. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% The function prototype normally appears near the beginning of the program and serves a purpose similar to a variable declaration. It provides advance information about the function, which QuickC can use to check the accuracy of subsequent calls to the function. We'll examine prototypes in detail in "Function Prototypes," below. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020006 @%%@AB@%Calling a Function%@AE@%%@EH@%%@NL@% %@NL@% You call (execute) a function by stating its name. In the simplest case─when a function doesn't receive or return any data─the function call consists of the function's name, followed by an empty pair of parentheses and a semicolon. The BEEPER.C program, shown below, demonstrates this kind of function call. %@NL@% %@NL@% %@AS@% /* BEEPER.C: Demonstrate simple function. */ %@AS@% #include <stdio.h> %@AS@% %@AS@% void beep( void ); %@AS@% %@AS@% main() %@AS@% { %@AS@% printf( "Time to beep\n" ); %@AS@% beep(); %@AS@% printf( "All done\n" ); %@AS@% } %@AS@% %@AS@% void beep( void ) %@AS@% { %@AS@% printf( "Beep!\a\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% When you run BEEPER.C, the program prints: %@NL@% %@NL@% %@AS@% Time to beep %@AS@% Beep! %@AS@% All done%@AE@%%@NL@% %@NL@% As you may recall from Chapter 1, "Anatomy of a C Program," the %@AB@%\n%@AE@% sequence represents the newline character. The %@AB@%\a%@AE@% sequence is the "alert" character (ASCII 7) which makes an audible beep. %@NL@% %@NL@% In the %@AB@%main%@AE@% function of BEEPER.C, the statement %@NL@% %@NL@% %@AS@% beep();%@AE@%%@NL@% %@NL@% calls the %@AS@% beep %@AE@% function. Since %@AS@% beep %@AE@% takes no arguments, the parentheses of the function call are empty. %@NL@% %@NL@% The prototype and definition for the %@AS@% beep %@AE@% function use the%@AB@% void%@AS@% %@AE@%keyword twice, first to indicate that the function returns no value, and second to indicate that it receives no arguments. We'll return to these points later in this chapter.%@AS@% %@AE@%%@AE@%%@NL@% %@NL@% A function call transfers control to that function. The statements within the function's braces execute in order until the function ends. Then execution resumes where it left off. %@NL@% %@NL@% A function can end in one of two ways. The %@AS@% beep %@AE@% function above ends by "falling off" the closing brace of the function definition. A function can also end by executing a %@AB@%return%@AE@% statement, which we discuss later in the section "Returning Values from Functions." %@NL@% %@NL@% Figure 2.3 illustrates the flow of control in BEEPER.C. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020007 @%%@AB@%Passing Arguments to a Function%@AE@%%@EH@%%@NL@% %@NL@% If a function requires arguments, you list them in the parentheses of the function call. In the BEEPER1.C program below, we revise the %@AS@% beep %@AE@% function from BEEPER.C to take one argument. %@NL@% %@NL@% %@AS@% /* BEEPER1.C: Demonstrate passing arguments. */ %@AS@% #include <stdio.h> %@AS@% %@AS@% void beep( int num_beep ); %@AS@% %@AS@% main() %@AS@% { %@AS@% printf( "Time to beep\n" ); %@AS@% beep( 5 ); %@AS@% printf( "All done\n" ); %@AS@% } %@AS@% %@AS@% void beep( int num_beep ) %@AS@% { %@AS@% while( num_beep > 0 ) %@AS@% { %@AS@% printf( "Beep!\a\n" ); %@AS@% num_beep = num_beep - 1; %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% The function definition states what kind of arguments the function expects. In the %@AS@%beep %@AE@% function definition, the header, %@NL@% %@NL@% %@AS@% void beep( int num_beep )%@AE@%%@NL@% %@NL@% states that %@AS@% beep %@AE@% expects one %@AB@%int%@AE@% (integer) argument named %@AS@% num_beep%@AE@% (number of beeps). %@NL@% %@NL@% The statement that calls %@AS@% beep%@AE@%, %@NL@% %@NL@% %@AS@% beep( 5 );%@AE@%%@NL@% %@NL@% gives the value 5 in parentheses, passing that value as an argument. Figure 2.4 shows argument passing in BEEPER1.C. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@AU@% Function arguments are assigned to local variables inside the function.%@AE@% %@NL@% %@NL@% When %@AS@% beep %@AE@% receives the value 5, the function automatically assigns the value to %@AS@% num_beep%@AE@%, which the function can then treat as a local variable. In this case, the function uses %@AS@% num_beep %@AE@% as a loop counter to repeat the statement %@NL@% %@NL@% %@AS@% printf( "Beep!\a\n" );%@AE@%%@NL@% %@NL@% %@AS@%%@AE@%num_beep times. (The C %@AB@%while%@AE@% loop is very similar to %@AB@%WHILE%@AE@% loops in QuickBASIC or QuickPascal. You don't need to know the details of loops for now; they're explained in Chapter 3, "Flow Control.") %@NL@% %@NL@% If a function expects more than one argument, you separate the arguments with commas. For instance, the statement %@NL@% %@NL@% %@AS@% printf( "%d times %d equals %d\n", 2, 16, 2 * 16 );%@AE@%%@NL@% %@NL@% passes four arguments to the %@AB@%printf%@AE@% function. The first argument is the string %@NL@% %@NL@% %@AS@% "%d times %d equals %d\n"%@AE@%%@NL@% %@NL@% The second and third arguments are constants (%@AS@%2 %@AE@% and %@AS@% 16%@AE@%). The fourth argument is an expression (%@AS@%2 * 16%@AE@%) that evaluates to a constant. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020008 @%%@AB@%Arguments Versus Parameters%@AE@%%@EH@%%@NL@% %@NL@% In the C language, a value passed to a function is called either an "argument" or a "parameter," depending on viewpoint. From the viewpoint of the statement that calls the function, the value is an argument. In the view of the function receiving it, the value is a parameter. %@NL@% %@NL@% Thus, in BEEPER1.C, the following function call passes an argument to the %@AS@% %@AS@%beep %@AE@% function: %@NL@% %@NL@% %@AS@% beep( 5 );%@AE@%%@NL@% %@NL@% Looking at the same value from the receiving end, the header of the %@AS@% beep %@AE@% function declares a parameter named %@AS@% num_beep %@AE@% as follows: %@NL@% %@NL@% %@AS@% void beep( int num_beep );%@AE@%%@NL@% %@NL@% The argument and parameter refer to the same value─in this case, the value 5. The naming distinction is just a matter of viewpoint, similar to the way you call a letter outgoing mail if you're sending it, or incoming mail if you're receiving it. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020009 @%%@AB@%Assigning Parameters%@AE@%%@EH@%%@NL@% %@NL@% When you list a parameter in the function header, it becomes a local variable within the function. This process is easy to follow when it involves only one argument, as in the BEEPER1.C program above. The function call passes one value, which the function assigns to one variable. The variable can be treated like any other variable declared within the function. %@NL@% %@NL@% %@AU@% There is a one-to-one correspondence between arguments and parameters.%@AE@% %@NL@% %@NL@% If a function takes more than one argument, the values are passed in order. The first argument in the function call is assigned to the first variable, the second argument is assigned to the second variable, and so on. %@NL@% %@NL@% The SHOWME.C program below demonstrates this process. Its %@AS@% showme %@AE@% function takes three arguments. The %@AB@%main%@AE@% function defines three integer variables and passes their values to %@AS@% showme%@AE@%, which prints the values that it receives. (You normally wouldn't write a function just to print one line, of course. We'll add more to SHOWME.C in a later revision.) %@NL@% %@NL@% %@AS@% /* SHOWME.C: Demonstrate passing by value. */ %@AS@% #include <stdio.h> %@AS@% %@AS@% void showme( int a, int b, int c );%@AE@%%@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% int x = 10, y = 20, z = 30; %@AS@% showme( z, y, x ); %@AS@% } %@AS@% %@AS@% void showme( int a, int b, int c ) %@AS@% { %@AS@% printf( "a=%d b=%d c=%d", a, b, c ); %@AS@% }%@AE@%%@NL@% %@NL@% Here's the output from SHOWME.C: %@NL@% %@NL@% %@AS@% a=30 b=20 c=10%@AE@%%@NL@% %@NL@% The function call in SHOWME.C passes the values of %@AS@% z%@AE@%, %@AS@% y%@AE@%, and %@AS@% x %@AE@% in the order listed: %@NL@% %@NL@% %@AS@% showme( z, y, x );%@AE@%%@NL@% %@NL@% %@AU@% Functions receive parameters in the order they are passed.%@AE@% %@NL@% %@NL@% These values are assigned, in the same order, to the parameters listed in the %@AS@% showme %@AE@% function header: %@NL@% %@NL@% %@AS@% void showme( int a, int b, int c )%@AE@%%@NL@% %@NL@% The position of the parameters, not their names, controls which arguments the parameters receive. The first argument (%@AS@% z %@AE@%) listed in the function call is assigned to the first parameter (%@AS@% a %@AE@%) in the function header, the second argument (%@AS@% y %@AE@%) to the second parameter (%@AS@% b %@AE@%), and so on. Figure 2.5 shows this process. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020010 @%%@AB@%Passing by Value%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The C language passes copies of function arguments.%@AE@% %@NL@% %@NL@% In C, all function arguments (except arrays) are passed "by value" rather than "by reference." That is, a function receives a local copy of each argument, not the argument itself. These copies are local variables within the function. They are created and initialized automatically when the function begins, and they disappear when it ends. Like all local variables, their values can be changed without affecting variables elsewhere in the program. %@NL@% %@NL@% We can clarify this point by adding a few statements to the SHOWME.C program. The new program, SHOWMORE.C, will change the values of the local variables in the %@AS@% showme %@AE@% function without changing the values of the original variables. %@NL@% %@NL@% %@AS@% /* SHOWMORE.C: Demonstrate passing by value. */ %@AS@% #include <stdio.h> %@AS@% %@AS@% void showme( int any, int old, int name ); %@AS@% %@AS@% main() %@AS@% { %@AS@% int x = 10, y = 20, z = 30; %@AS@% showme( z, y, x ); %@AS@% printf( " z=%d y=%d x=%d\n", z, y, x ); %@AS@% } %@AS@% %@AS@% void showme( int any, int old, int name ) %@AS@% { %@AS@% printf( "any=%d old=%d name=%d\n", any, old, name ); %@AS@% any = 55; %@AS@% old = 66; %@AS@% name = 77; %@AS@% printf( "any=%d old=%d name=%d\n", any, old, name ); %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from SHOWMORE.C: %@NL@% %@NL@% %@AS@% any=30 old=20 name=10 %@AS@% any=55 old=66 name=77 %@AS@% z=30 y=20 x=10%@AE@%%@NL@% %@NL@% First, note that the %@AS@% showme %@AE@% function in SHOWMORE.C uses new names (%@AS@% any%@AE@%, %@AS@% %@AS@%old%@AE@%, and %@AS@% name%@AE@%) when assigning the parameters it receives: %@NL@% %@NL@% %@AS@% void showme( int any, int old, int name )%@AE@%%@NL@% %@NL@% %@AU@% Function parameters can have any legal variable names.%@AE@% %@NL@% %@NL@% Because these variables are local to the function, they can have any legal names. (The rules for variable names are described in Chapter 4, "Data Types.") The %@AS@% showme %@AE@% function prints the values of its parameters immediately after assigning them: %@NL@% %@NL@% %@AS@% printf( "any=%d old=%d name=%d", any, old, name );%@AE@%%@NL@% %@NL@% Then the function assigns new values to the variables and prints them again: %@NL@% %@NL@% %@AS@% any = 55; %@AS@% old = 66; %@AS@% name = 77; %@AS@% printf( "any=%d old=%d name=%d", any, old, name );%@AE@%%@NL@% %@NL@% %@AU@% Local variables are private to the function containing them.%@AE@% %@NL@% %@NL@% Changing the local variables in the %@AS@% showme %@AE@% function doesn't affect the original variables in the %@AB@%main%@AE@% function. Remember, a variable defined inside a function is only visible inside that function. After control returns to %@AB@%main%@AE@%, SHOWMORE.C prints the values of the original variables: %@NL@% %@NL@% %@AS@% printf( " z=%d y=%d x=%d\n", z, y, x );%@AE@%%@NL@% %@NL@% As the program output shows, the original values are unchanged: %@NL@% %@NL@% %@AS@% z=30 y=20 x=10%@AE@%%@NL@% %@NL@% We'll say more about the visibility of variables in Chapter 5, "Advanced Data Types." For now, just remember that when you pass a value to a function, the function makes a local copy of that value. The local copy can be manipulated without changing the original. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%In QuickPascal, you can pass either the value of an argument or the %@AI@%argument's address. In C, function arguments are only passed by value. %@AI@%However, that value can be an address. Chapter 8, "Pointers," explains how %@AI@%to pass addresses to functions.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020011 @%%@AB@%Returning Values from Functions%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The return keyword ends a function and can return one value.%@AE@% %@NL@% %@NL@% Most C functions return a value. This is done with the %@AB@%return%@AE@% statement, which also ends the function. The VOLUME.C program from Chapter 1, "Anatomy of a C Program," (see Figure 2.1) contains such a statement. In that program, the %@AS@% sphere %@AE@% function returns the value of the variable %@AS@% result %@AE@% as follows: %@NL@% %@NL@% %@AS@% return result;%@AE@%%@NL@% %@NL@% The following statement in the %@AB@%main%@AE@% function of VOLUME.C calls the %@AS@% sphere %@AE@% function and assigns its return value to the variable %@AS@% volume%@AE@%: %@NL@% %@NL@% %@AS@% volume = sphere( radius );%@AE@%%@NL@% %@NL@% Figure 2.6 shows the flow of control as the %@AS@% sphere %@AE@% function returns a value in VOLUME.C. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% A %@AB@%return%@AE@% statement can only return a single value. If a function needs to return multiple values, the normal method is to use pointers─a major topic that we'll discuss in Chapter 8, "Pointers." %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%In QuickPascal, a function returns a value and a procedure does not. The %@AI@%same distinction applies to QuickBASIC %@AI@%FUNCTION %@AE@%%@AI@%and %@AE@%%@AI@%%@AB@%SUB %@AE@%%@AE@%%@AI@%procedures, %@AI@%respectively. In the C language, a function can do both. It can return a %@AI@%value or return nothing.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% A function can contain more than one %@AB@%return%@AE@% statement, as shown below: %@NL@% %@NL@% %@AS@% if( error == 0 ) %@AS@% return 0; %@AS@% else %@AS@% return 1;%@AE@%%@NL@% %@NL@% The code returns a different value in different cases. It returns the value 0 when the variable %@AS@% error %@AE@% is 0 and the value 1 when %@AS@% error %@AE@% is nonzero. (In C, the %@AB@%if%@AE@% and %@AB@%else%@AE@% statements work much like those in other languages. Chapter 3, "Flow Control," explains these statements.) %@NL@% %@NL@% %@AU@% A return statement can appear anywhere and need not return a value.%@AE@% %@NL@% %@NL@% You can place the %@AB@%return%@AE@% keyword anywhere within a function, and the statement need not necessarily return a value. In the following fragment, the naked %@AB@%return%@AE@% statement simply ends the function if the value of %@AS@% count %@AE@% exceeds 500: %@NL@% %@NL@% %@AS@% if( count > 500 ) %@AS@% return; %@AS@% else %@AS@% /* execute more statements... */%@AE@%%@NL@% %@NL@% A %@AB@%return%@AE@% statement ends the function immediately, no matter where it appears. In the function shown below, the statements following the %@AB@%return%@AE@% never execute: %@NL@% %@NL@% %@AS@% void do_nothing( void ) %@AS@% { %@AS@% return; %@AS@% /* The following statements do not execute */ %@AS@% printf( "This function " ); %@AS@% printf( "prints nothing.\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% If a function doesn't return a value, and you want the function to end by falling off its closing brace, no %@AB@%return%@AE@% statement is needed. This method is used to end the %@AS@% beep %@AE@% function in BEEPER.C, discussed earlier in this chapter: %@NL@% %@NL@% %@AS@% void beep( void ) %@AS@% { %@AS@% printf( "Beep!\a\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% You could add a %@AB@%return%@AE@% to the end of this function, but it's not necessary. The function ends automatically. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020012 @%%@AB@%Using Return Values%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Function return values are often assigned to variables.%@AE@% %@NL@% %@NL@% A function's return value can be used in the same way you would use any value of its type. In the VOLUME.C program from Chapter 1, "Anatomy of a C Program," the statement that calls %@AS@% sphere %@AE@% assigns the function's return value to the variable %@AS@% volume%@AE@%: %@NL@% %@NL@% %@AS@% volume = sphere( radius );%@AE@%%@NL@% %@NL@% If there's no need to save the return value, you can use it directly. You may have noticed that the variable %@AS@% volume %@AE@% isn't really needed in the VOLUME.C program, which simply prints the variable's value and ends. Most programmers would make the program more compact by replacing the two statements %@NL@% %@NL@% %@AS@% volume = sphere( radius ); %@AS@% printf( "Volume: %f\n", volume );%@AE@%%@NL@% %@NL@% with this one: %@NL@% %@NL@% %@AS@% printf( "Volume: %f\n", sphere( radius ) );%@AE@%%@NL@% %@NL@% The second version puts the %@AS@% sphere %@AE@% function call right in the %@AB@%printf%@AE@% statement, eliminating the superfluous variable. Instead of assigning the return value to a variable and passing that variable's value to %@AB@%printf%@AE@%, the statement uses the value directly. (The %@AS@% sphere %@AE@% function is called first. Then the return value from %@AS@% sphere %@AE@% is passed as an argument to the %@AB@%printf%@AE@% function.) %@NL@% %@NL@% While this change streamlines the program, it also makes the code a little harder to follow. If you don't read carefully, you might overlook the fact that the %@AB@%printf%@AE@% function call contains another function call. %@NL@% %@NL@% %@AU@% Unused return values are discarded.%@AE@% %@NL@% %@NL@% Occasionally, you may have no use for a function's return value. The %@AB@%printf%@AE@% function, for example, returns the number of characters it displayed, but few programs need this information. If you don't use a return value, it's discarded. %@NL@% %@NL@% You should never ignore the error codes that library functions return to show whether the function succeeded. See Chapter 10, "Programming Pitfalls," for more information about library function return values. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020013 @%%@AB@%Declaring a Function's Return Type%@AE@%%@EH@%%@NL@% %@NL@% Thus far, we have explained how a function can return a value─and how the calling statement can use that value─without paying much attention to what type of value the function returns. (The C language supports various data types, such as %@AB@%int%@AE@% for integer values, and %@AB@%float%@AE@% for floating-point values. Chapter 4 describes data types in detail.) %@NL@% %@NL@% The return type is important because it controls what the function returns. If a function returns an integer when you expect a floating-point value, your program may not work correctly. %@NL@% %@NL@% %@AU@% A function's prototype and definition control what type of value it %@AU@%returns.%@AE@% %@NL@% %@NL@% The function's return type is specified in its prototype and definition. Below are the prototype and definition of the %@AS@% sphere %@AE@% function from the VOLUME.C program in Chapter 1, "Anatomy of a C Program." They specify that the function returns a %@AB@%float%@AE@% value. %@NL@% %@NL@% %@AS@% float sphere( int rad ); /* function prototype */ %@AS@% %@AS@% float sphere( int rad ) /* function header */%@AE@%%@NL@% %@NL@% The type name (here, %@AB@%float%@AE@%) in front of the function name shows what type of value the function returns. If the %@AS@% sphere %@AE@% function returned an %@AB@%int%@AE@% value, its prototype and header would look like this: %@NL@% %@NL@% %@AS@% int sphere( int rad ); /* function prototype */ %@AS@% %@AS@% int sphere( int rad ) /* function header */%@AE@%%@NL@% %@NL@% %@AU@% Use the void type name to show a function returns no value.%@AE@% %@NL@% %@NL@% You should declare the return type for every function─even for functions that don't return a value. These functions are declared with the %@AB@%void%@AE@% type name. In the SHOWME.C program, shown above, the prototype of the %@AS@% showme %@AE@% function follows this pattern: %@NL@% %@NL@% %@AS@% void showme( int a, int b, int c );%@AE@%%@NL@% %@NL@% The %@AB@%void%@AE@% that precedes the function name indicates that %@AS@% showme %@AE@% returns nothing. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020014 @%%@AB@%Function Prototypes%@AE@%%@EH@%%@NL@% %@NL@% Function prototyping is the major innovation of the ANSI standard for C. As we mentioned earlier, a function prototype gives the same information as the function's header: the name of the function, the type of value the function returns, and the number and type of parameters the function requires. %@NL@% %@NL@% %@AU@% Function prototypes allow QuickC to check function references for %@AU@%accuracy.%@AE@% %@NL@% %@NL@% Function prototypes normally appear near the start of the program, before the first function definition. Given the information in the prototype, QuickC can perform "type checking." It checks each reference to the function─its definition, as well as every function call─to make sure that the reference uses the right number and type of arguments and the correct return value. Without type checking, it's easy to create bugs by passing the wrong type of value to a function or assuming the wrong return type. %@NL@% %@NL@% C programs normally include one prototype for each function they define, except the %@AB@%main%@AE@% function. Most programmers don't bother to prototype %@AB@%main%@AE@% unless the program receives command-line arguments or returns a value to DOS when it ends. (Command-line arguments are discussed in Chapter 9, "Advanced Pointers.") %@NL@% %@NL@% Here is the function prototype for the %@AS@% sphere %@AE@% function in VOLUME.C: %@NL@% %@NL@% %@AS@% float sphere( int rad );%@AE@%%@NL@% %@NL@% You can see that %@AS@% sphere %@AE@% expects a single %@AB@%int%@AE@%-type parameter and returns a value of type %@AB@%float%@AE@%. On the other hand, the prototype for %@AS@% showme %@AE@% in SHOWME.C indicates that %@AS@% showme %@AE@% expects three %@AB@%int%@AE@%-type parameters and returns nothing: %@NL@% %@NL@% %@AS@% void showme( int a, int b, int c );%@AE@%%@NL@% %@NL@% It's common to use the same parameter names in both the function prototype and the function header. In SHOWME.C, for instance, the %@AS@% showme %@AE@% function prototype, %@NL@% %@NL@% %@AS@% void showme( int a, int b, int c );%@AE@%%@NL@% %@NL@% uses the names %@AS@% a%@AE@%, %@AS@% b%@AE@%, and %@AS@% c%@AE@%, as does the header for that function, %@NL@% %@NL@% %@AS@% void showme( int a, int b, int c )%@AE@%%@NL@% %@NL@% Using the same names in both parameter lists makes the program more readable, but it's not a language requirement. The names in the prototype's parameter list are merely cosmetic. You can use any names you choose, or even omit the names completely. The prototype in SHOWME.C works just as well when written %@NL@% %@NL@% %@AS@% void showme( int, int, int );%@AE@%%@NL@% %@NL@% as when you supply the names %@AS@% a%@AE@%, %@AS@% b%@AE@%, and %@AS@% c%@AE@%. Both versions fully specify the number (three) and type (%@AB@%int%@AE@%) of the parameters the function expects. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020015 @%%@AB@%Prototyping Functions without Parameters%@AE@%%@EH@%%@NL@% %@NL@% If a function doesn't expect any parameters, you might be tempted to leave its parameter list blank. But it's better to put %@AB@%void%@AE@% in its parameter list, as shown here: %@NL@% %@NL@% %@AS@% void beep( void );%@AE@%%@NL@% %@NL@% The %@AB@%void%@AE@% in parentheses specifies that the %@AS@% beep %@AE@% function requires no parameters. If you leave the parentheses empty, the compiler draws no conclusion about what parameters the function takes and won't be able to detect an error if you mistakenly pass an argument to the function. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00020016 @%%@AB@%Prototyping Functions with Variable Parameters%@AE@%%@EH@%%@NL@% %@NL@% Some functions, such as the %@AB@%printf%@AE@% library function, can handle a variable number of parameters. This capability can make functions more flexible. As earlier examples have shown, the %@AB@%printf%@AE@% function can take one parameter or several, depending on how many values you need to print. %@NL@% %@NL@% To declare a function with a variable number of parameters, end the parameter list with a comma and an ellipsis (%@AS@%, . . .%@AE@%). The following prototype, for example, declares that the %@AS@% sample %@AE@% function expects at least one %@AB@%int%@AE@%-type parameter and zero or more additional parameters: %@NL@% %@NL@% %@AS@% void sample( int a,... );%@AE@%%@NL@% %@NL@% The ellipsis stands for an unspecified number of parameters with types that are also unspecified. The parameter list in the function header should follow the same pattern. %@NL@% %@NL@% Don't declare a variable number of parameters unless it's necessary. Giving this sort of prototype for a function that takes a fixed number of parameters defeats the prototype's main purpose. QuickC can't perform type checking for parameters you leave out of a prototype. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00020017 @%%@AB@%Old-Style Function Declarations and Definitions%@AE@%%@EH@%%@NL@% %@NL@% This book explains how to declare and define functions under the ANSI standard for C, which is now the norm. The original C language used slightly different rules for function declarations and definitions. QuickC can compile these "oldstyle" programs, but the ANSI standard recommends you use the full function prototypes we just described. %@NL@% %@NL@% Still, you may encounter old-style function declarations and definitions in many existing C programs. So, you should be familiar with the style. %@NL@% %@NL@% We'll use the VOLUME.C program from Chapter 1, "Anatomy of a C Program," to demonstrate the old style. First, here's the ANSI-style program presented in Chapter 1: %@NL@% %@NL@% %@AS@% /* VOLUME.C: Calculate sphere's volume. */ %@AS@% #include <stdio.h> %@AS@% #define PI 3.14 %@AS@% %@AS@% float sphere( int rad ); %@AS@% %@AS@% main() %@AS@% { %@AS@% float volume; %@AS@% int radius = 3; %@AS@% volume = sphere( radius ); %@AS@% printf( "Volume: %f\n", volume ); %@AS@% } %@AS@% %@AS@% float sphere( int rad ) %@AS@% { %@AS@% float result; %@AS@% result = rad * rad * rad; %@AS@% result = 4 * PI * result; %@AS@% result = result / 3; %@AS@% return result; %@AS@% }%@AE@%%@NL@% %@NL@% The same program written in the old style would look something like this: %@NL@% %@NL@% %@AS@% /* OLDSTYLE.C: Old-style function. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #define PI 3.14 %@AS@% %@AS@% float sphere(); %@AS@% %@AS@% main() %@AS@% { %@AS@% float volume; %@AS@% int radius = 3; %@AS@% volume = sphere( radius ); %@AS@% printf( "Volume: %f\n", volume ); %@AS@% } %@AS@% %@AS@% float sphere( rad ) %@AS@% int rad; %@AS@% { %@AS@% float result; %@AS@% result = rad * rad * rad; %@AS@% result = 4 * PI * result; %@AS@% result = result / 3; %@AS@% return result; %@AS@% }%@AE@%%@NL@% %@NL@% You'll notice two distinct differences. First, the old style doesn't allow a parameter list in the function declaration. In the ANSI version, VOLUME.C, the declaration of the %@AS@% sphere %@AE@% function specifies that the function takes a single %@AB@%int%@AE@% parameter: %@NL@% %@NL@% %@AS@% float sphere( int rad );%@AE@%%@NL@% %@NL@% The corresponding declaration in OLDSTYLE.C omits the parameter list: %@NL@% %@NL@% %@AS@% float sphere();%@AE@%%@NL@% %@NL@% An old-style function declaration cannot provide any information about the function's parameters. %@NL@% %@NL@% The other change is in the way the function definition lists parameters. In VOLUME.C, the function header lists the same information as the function prototype, giving the type (%@AB@%int%@AE@%) and name (%@AS@% rad %@AE@%) of the function's parameter: %@NL@% %@NL@% %@AS@% float sphere( int rad ) %@AS@% { %@AS@% . %@AS@% . %@AS@% . %@AS@% }%@AE@%%@NL@% %@NL@% In OLDSTYLE.C, the function header gives the parameter's name (%@AS@% rad %@AE@%), but not its type. The parameter's type is declared in a statement directly below the function header (and before the left brace that begins the function body): %@NL@% %@NL@% %@AS@% float sphere( rad ) %@AS@% int rad; %@AS@% { %@AS@% . %@AS@% . %@AS@% . %@AS@% }%@AE@%%@NL@% %@NL@% The rest of OLDSTYLE.C is identical to VOLUME.C. %@NL@% %@NL@% Now that you understand the basics of functions, we can turn our attention to the C statements that a function can contain, beginning with flow-control statements, the subject of the next chapter. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00030001 @%%@1@%%@AB@%Chapter 3 Flow Control%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% Flow control─diverting execution by looping and branching─is one area where C closely resembles other languages. If you know how to loop and branch in QuickBASIC or QuickPascal, learning the C equivalents is mainly a matter of adjusting to somewhat different syntax. Here, as elsewhere, C never uses two keywords when one will do. For instance, C has no "then" keyword. Instead, it uses simple punctuation. %@NL@% %@NL@% This chapter has two parts. The first part examines the looping statements: %@AB@%while%@AE@%, %@AB@%do%@AE@%, and %@AB@%for%@AE@%. The second part describes the decision-making statements: %@AB@%if%@AE@%, %@AB@%else%@AE@%, %@AB@%switch%@AE@%, %@AB@%break%@AE@%, %@AB@%continue%@AE@%, and %@AB@%goto%@AE@%. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00030002 @%%@AB@%Loops: while, do, and for%@AE@%%@EH@%%@NL@% %@NL@% This section discusses the C statements that create loops: %@AB@%while%@AE@%, %@AB@%do%@AE@%, and %@AB@%for%@AE@%. These loops repeat while a condition is true or for a set number of times. We'll begin with the simplest loop, the %@AB@%while%@AE@% statement. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00030003 @%%@AB@%The while Statement%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A while loop evaluates its test expression before executing the body of %@AU@%the loop.%@AE@% %@NL@% %@NL@% A %@AB@%while%@AE@% loop repeats as long as a given condition remains true. It consists of the %@AB@%while%@AE@% keyword followed by a test expression in parentheses and a loop body, as shown in Figure 3.1. The "test expression" can be any C expression and is evaluated before the loop body is executed. The loop body is a single statement or a statement block that executes once every time the loop is iterated. The distinguishing feature of a %@AB@%while%@AE@% loop is that it evaluates the test expression before it executes the loop body, unlike the %@AB@%do%@AE@% loop, which we'll examine next. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% We've incorporated the simple %@AB@%while%@AE@% loop from Figure 3.1 in the WHILE.C program, shown below. %@NL@% %@NL@% %@AS@% /* WHILE.C: Demonstrate while loop. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int test = 10; %@AS@% %@AS@% while( test > 0 ) %@AS@% { %@AS@% printf( "test = %d\n", test ); %@AS@% test = test - 2; %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from WHILE.C: %@NL@% %@NL@% %@AS@% test = 10 %@AS@% test = 8 %@AS@% test = 6 %@AS@% test = 4 %@AS@% test = 2%@AE@%%@NL@% %@NL@% In WHILE.C, if the variable %@AS@% test %@AE@% is positive when the loop begins, the test expression evaluates as true and the loop executes. If %@AS@% test %@AE@% has a 0 or negative value when the loop starts, the test expression is false; the loop body does not execute and the action falls through to the statement that follows the loop. %@NL@% %@NL@% (Chapter 6, "Operators," explains true and false values. For now, it's enough to know that an expression is evaluated as false if it equals 0. Any nonzero value is true.) %@NL@% %@NL@% The loop body in WHILE.C happens to be a statement block enclosed in braces. If the loop body is a single statement, as in the following code, no braces are needed. %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% int test = 10; %@AS@% while( test > 0 ) %@AS@% test = test - 2; %@AS@% }%@AE@%%@NL@% %@NL@% Occasionally, you'll see a %@AB@%while%@AE@% loop with a test expression such as %@NL@% %@NL@% %@AS@% while( 1 )%@AE@%%@NL@% %@NL@% or %@NL@% %@NL@% %@AS@% #define TRUE 1 %@AS@% . %@AS@% . %@AS@% . %@AS@% while( TRUE )%@AE@%%@NL@% %@NL@% The test expressions above are always true, creating an indefinite loop that never ends naturally. You can only terminate this kind of loop with some overt action, usually by executing a %@AB@%break%@AE@% statement. (See "The break Statement" later in this chapter.) You can use such a loop to repeat an action for an indefinite time period─until a certain key is pressed, for instance. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00030004 @%%@AB@%The do Statement%@AE@%%@EH@%%@NL@% %@NL@% A %@AB@%do%@AE@% loop is simply a %@AB@%while%@AE@% loop turned on its head. First comes the loop body, then the test expression. Unlike a %@AB@%while%@AE@% loop, a %@AB@%do%@AE@% loop always executes its loop body at least once. %@NL@% %@NL@% %@AU@% A do loop always executes at least once.%@AE@% %@NL@% %@NL@% The difference is important. A %@AB@%while%@AE@% statement evaluates the test expression before it executes the loop body. If the test expression in a %@AB@%while%@AE@% statement is false, the loop body doesn't execute at all. A %@AB@%do%@AE@% statement, on the other hand, evaluates the test expression after executing the loop body. Thus, the body of a %@AB@%do%@AE@% statement always executes at least once, even if the test expression is false when the loop begins. %@NL@% %@NL@% Figure 3.2 contrasts the %@AB@%while%@AE@% loop from WHILE.C with a comparable %@AB@%do%@AE@% loop to emphasize this difference. You'll notice that the %@AB@%do%@AE@% keyword comes right before the loop body, which is followed by the %@AB@%while%@AE@% keyword and a test expression─the same test expression that WHILE.C uses. Notice the semicolon that ends the %@AB@%do%@AE@% loop. A %@AB@%do%@AE@% loop always ends with a semicolon; a %@AB@%while%@AE@% loop never does. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% The DO.C program below uses the %@AB@%do%@AE@% loop from Figure 3.2 to perform the same action that WHILE.C does. %@NL@% %@NL@% %@AS@% /* DO.C: Demonstrate do loop. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int test = 10; %@AS@% do %@AS@% { %@AS@% printf( "test = %d\n", test ); %@AS@% test = test - 2; %@AS@% } while( test > 0 ); %@AS@% }%@AE@%%@NL@% %@NL@% DO.C gives the same output as WHILE.C: %@NL@% %@NL@% %@AS@% test = 10 %@AS@% test = 8 %@AS@% test = 6 %@AS@% test = 4 %@AS@% test = 2%@AE@%%@NL@% %@NL@% The programs do not give the same output if you modify them so that the value of %@AS@% test %@AE@% is 0 when the loop starts. In that case, the loop body in DO.C executes once, but the loop body in WHILE.C doesn't execute at all. You should only use a %@AB@%do%@AE@% loop when you always want the loop body to execute at least once. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00030005 @%%@AB@%The for Statement%@AE@%%@EH@%%@NL@% %@NL@% As in QuickBASIC or QuickPascal, the %@AB@%for%@AE@% statement in C is often used to repeat a statement a set number of times. Let's begin with a simple example. The FORLOOP.C program, shown below, uses %@AB@%for%@AE@% to repeat a %@AB@%printf%@AE@% statement five times. %@NL@% %@NL@% %@AS@% /* FORLOOP.C: Demonstrate for loop. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int test; %@AS@% for( test = 10; test > 0; test = test - 2 ) %@AS@% printf( "test = %d\n", test ); %@AS@% }%@AE@%%@NL@% %@NL@% FORLOOP.C gives the same output as WHILE.C and DO.C: %@NL@% %@NL@% %@AS@% test = 10 %@AS@% test = 8 %@AS@% test = 6 %@AS@% test = 4 %@AS@% test = 2%@AE@%%@NL@% %@NL@% Figure 3.3 shows the parts of the %@AB@%for%@AE@% loop in FORLOOP.C. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% A %@AB@%for%@AE@% statement is more complex than a %@AB@%while%@AE@% or %@AB@%do%@AE@% statement. The part in parentheses can contain three expressions separated by semicolons: %@NL@% %@NL@% %@NL@% ■ An "initializing expression" that often initializes a loop counter%@NL@% %@NL@% ■ A "test expression" that states how long the loop continues%@NL@% %@NL@% ■ A "modifying expression" that often modifies a loop counter%@NL@% %@NL@% %@NL@% Like the test expression in a %@AB@%while%@AE@% statement, the test expression in a %@AB@%for%@AE@% statement causes the loop to continue as long as the test expression evaluates as true. %@NL@% %@NL@% All of the expressions in the parentheses of a %@AB@%for%@AE@% statement are optional. If you omit the test expression (the second one), the statement repeats indefinitely. In the following program, for instance, all of the expressions in the parentheses of the %@AB@%for%@AE@% loop are empty: %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% for( ; ; ) %@AS@% printf( "Hi, Mom!\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% The loop above repeats indefinitely because it has no test expression that specifies when to end the loop. It has the same effect as the following %@AB@%while%@AE@% loop, whose test expression is always true: %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% while( 1 ) %@AS@% printf( "Hi, Mom!\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% You can use multiple expressions for either the initializing expression or the modifying expression, as in FORLOOP1.C: %@NL@% %@NL@% %@AS@% /* FORLOOP1.C: Demonstrate multiple expressions. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int a, b; %@AS@% for( a = 256, b = 1; b < 512; a = a / 2, b = b * 2 ) %@AS@% printf( "a = %d b = %d\n", a, b ); %@AS@% }%@AE@%%@NL@% %@NL@% The output from FORLOOP1.C appears below: %@NL@% %@NL@% %@AS@% a = 256 b = 1 %@AS@% a = 128 b = 2 %@AS@% a = 64 b = 4 %@AS@% a = 32 b = 8 %@AS@% a = 16 b = 16 %@AS@% a = 8 b = 32 %@AS@% a = 4 b = 64 %@AS@% a = 2 b = 128 %@AS@% a = 1 b = 256%@AE@%%@NL@% %@NL@% In the FORLOOP1.C program, the initializing expression of the %@AB@%for%@AE@% loop initializes two variables (%@AS@% a %@AE@% and %@AS@% b %@AE@%) instead of one. The modifying expression changes the values of the same two variables. Use commas to separate multiple expressions in cases such as this. %@NL@% %@NL@% Although %@AB@%for%@AE@% and %@AB@%while%@AE@% might seem quite different, they're interchangeable in most cases. The FORLOOP2.C program demonstrates this principle. Both loops, while constructed differently, produce the same effect─printing the numbers from 0 through 9. %@NL@% %@NL@% %@AS@% /* FORLOOP2.C: Demonstrate similarity of for and while. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int count; %@AS@% %@AS@% for( count = 0; count < 10; count = count + 1 ) %@AS@% printf( "count = %d\n", count ); %@AS@% %@AS@% count = 0; %@AS@% while( count < 10 ) %@AS@% { %@AS@% printf( "count = %d\n", count ); %@AS@% count = count +1; %@AS@% } %@AS@% %@AS@% }%@AE@%%@NL@% %@NL@% The two loops in FORLOOP2.C function identically. The %@AB@%for%@AE@% loop prints the numbers from 0 through 9: %@NL@% %@NL@% %@AS@% for( count = 0; count < 10; count = count + 1; ) %@AS@% printf( "count = %d\n", count );%@AE@%%@NL@% %@NL@% as does the %@AB@%while%@AE@% loop: %@NL@% %@NL@% %@AS@% count = 0; %@AS@% while( count < 10 ) %@AS@% { %@AS@% printf( "count = %d\n", count ); %@AS@% count = count + 1; %@AS@% }%@AE@%%@NL@% %@NL@% Most programmers prefer %@AB@%for%@AE@% over %@AB@%while%@AE@% in a case like this, because %@AB@%for%@AE@% groups all the loop-control statements in one place. The %@AB@%for%@AE@% statement is also appropriate when you need to initialize one or more values at the beginning of the loop. The %@AB@%while%@AE@% and %@AB@%do%@AE@% statements are more appropriate for cases in which the value used in the test expression has already been initialized. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00030006 @%%@AB@%Decision-Making Statements: if, else, switch, break, continue, and goto%@AE@%%@EH@%%@NL@% %@NL@% The C language provides six statements for decision making: %@AB@%if%@AE@%, %@AB@%else%@AE@%, %@AB@%switch%@AE@%, %@AB@%break%@AE@%, %@AB@%continue%@AE@%, and %@AB@%goto%@AE@%. Like their counterparts in other languages, these statements transfer control based on the outcome of a logical test. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00030007 @%%@AB@%The if Statement%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The body of an if statement executes when its test expression is true.%@AE@% %@NL@% %@NL@% An %@AB@%if%@AE@% statement consists of the %@AB@%if%@AE@% keyword followed by a test expression in parentheses and a second statement. The second statement is executed if the test expression is true, or skipped if the expression is false. %@NL@% %@NL@% The IFF.C program contains a simple %@AB@%if%@AE@% test. It prints a prompt and waits for you to press a key. %@NL@% %@NL@% %@AS@% /* IFF.C: Demonstrate if statement. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <conio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% char ch; %@AS@% printf( "Press the b key to hear a bell.\n" ); %@AS@% ch = getch(); %@AS@% if( ch == 'b' ) %@AS@% printf( "Beep!\a\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% In the IFF.C program, the statement %@NL@% %@NL@% %@AS@% ch = getch();%@AE@%%@NL@% %@NL@% calls the %@AB@%getch%@AE@% library function to get a keypress from the keyboard and then assigns the result to the variable %@AS@% ch%@AE@%. If you press the b key, the program prints %@NL@% %@NL@% %@AS@% Beep!%@AE@%%@NL@% %@NL@% and sounds a beep. (To simplify the code, IFF.C tests only for a lowercase b character. A program would normally use a library function such as %@AB@%tolower%@AE@% to test for both upper and lowercase.) %@NL@% %@NL@% Figure 3.4 illustrates the parts of the %@AB@%if%@AE@% statement in the IFF.C program. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% The test expression of the %@AB@%if%@AE@% statement %@NL@% %@NL@% %@AS@% ch == 'b'%@AE@%%@NL@% %@NL@% %@AU@% The equality operator (==) tests if values are equal.%@AE@% %@NL@% %@NL@% is true when the variable %@AS@% ch %@AE@% equals the letter b. In C the equality operator (%@AB@%==%@AE@%) tests if two values are equal. (Chapter 6 discusses operators.) %@NL@% %@NL@% The body of the %@AB@%if%@AE@% statement in IFF.C happens to be a single statement, but the body can also be a statement block, as in the following fragment: %@NL@% %@NL@% %@AS@% if( ch == 'b' ) %@AS@% { %@AS@% printf( "Beep!\a\n" ); %@AS@% printf( "You pressed the 'b' key\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% You can also nest %@AB@%if%@AE@% statements, as shown below: %@NL@% %@NL@% %@AS@% if( ch == 'b' ) %@AS@% { %@AS@% printf( "Beep!\a\n" ); %@AS@% beep_count = beepcount + 1; %@AS@% if( beep_count > 10 ) %@AS@% { %@AS@% printf( "More than 10 beeps...\n" ); %@AS@% if( beep_count > 100 ) %@AS@% printf( "Don't wear out the 'b' key!\n" ); %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% The code nests three %@AB@%if%@AE@% statements. The first %@AB@%if%@AE@% tests whether %@AS@% ch %@AE@% equals the letter b; the second tests whether the variable %@AS@% beep_count %@AE@% is greater than 10. The third tests whether %@AS@% beep_count %@AE@% exceeds 100. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00030008 @%%@AB@%The else Clause%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% An else clause can follow an if statement.%@AE@% %@NL@% %@NL@% The %@AB@%else%@AE@% keyword is used with %@AB@%if%@AE@% to form an either-or construct that executes one statement when an expression is true and another when it's false. The ELSE.C program demonstrates %@AB@%else%@AE@% by adding an %@AB@%else%@AE@% clause to the code from IFF.C. It sounds a beep and prints %@AS@% Beep! %@AE@% if you type the letter b, or it prints %@AS@% Bye bye %@AE@% if you type any other letter. %@NL@% %@NL@% %@AS@% /* ELSE.C: Demonstrate else clause. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <conio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% char ch; %@AS@% printf( "Press the b key to hear a bell.\n" ); %@AS@% ch = getch(); %@AS@% if( ch == 'b' ) %@AS@% printf( "Beep!\a\n" ); %@AS@% else %@AS@% printf( "Bye bye\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% %@AU@% To create an else-if construct, place an if statement after an else.%@AE@% %@NL@% %@NL@% The C language has no "elseif" keyword, but it's easy to create the same effect, because the statement that follows %@AB@%else%@AE@% can be any C statement─including another %@AB@%if%@AE@% statement. The ELSE1.C program uses %@AB@%if%@AE@% and %@AB@%else%@AE@% to test three conditions. It sounds a beep when you type the letter b, it prints %@AS@% Enter %@AE@% when you press the ENTER key, or it prints %@AS@% Bye bye %@AE@% when you press any other key. %@NL@% %@NL@% %@AS@% /* ELSE1.C: Demonstrate else-if construct. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <conio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% char ch; %@AS@% printf( "Press the b key to hear a bell.\n" ); %@AS@% ch = getch(); %@AS@% if( ch == 'b' ) %@AS@% printf( "Beep!\a\n" ); %@AS@% else %@AS@% if( ch == '\r' ) %@AS@% printf( "Enter\n" ); %@AS@% else %@AS@% printf( "Bye bye\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% The %@AB@%else%@AE@% keyword is tied to the closest preceding %@AB@%if%@AE@% that's not already matched by an %@AB@%else%@AE@%. Keep this rule in mind when creating nested %@AB@%if%@AE@%-%@AB@%else%@AE@% constructs. (See the section "Mismatching if and else Statements" in Chapter 10, "Programming Pitfalls.") %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00030009 @%%@AB@%The switch Statement%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The switch statement can perform multiple branches.%@AE@% %@NL@% %@NL@% The %@AB@%switch%@AE@% statement offers an elegant option in situations that require multiple branches. It tests a single expression that can have several values, providing a different action for each value. %@NL@% %@NL@% One disadvantage of %@AB@%if%@AE@% and %@AB@%else%@AE@% is that they only allow one branch per keyword. The program either executes the statement that follows the %@AB@%if%@AE@% or %@AB@%else%@AE@%, or it doesn't. To perform more complex tests, you have to pile on more %@AB@%if%@AE@% and %@AB@%else%@AE@% statements, as in the ELSE1.C program above. %@NL@% %@NL@% A program that handles keyboard input, for instance, may require several different responses to various keypresses. The ELSE1.C program above used combinations of %@AB@%if%@AE@% and %@AB@%else%@AE@% to process keyboard input. We've used a single %@AB@%switch%@AE@% statement in the SWITCH.C program below to do the same job: %@NL@% %@NL@% %@AS@% /* SWITCH.C: Demonstrate switch statement. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <conio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% char ch; %@AS@% printf( "Press the b key to hear a bell.\n" ); %@AS@% ch = getch(); %@AS@% switch( ch ) %@AS@% { %@AS@% case 'b': %@AS@% printf( "Beep!\a\n" ); %@AS@% break; %@AS@% case '\r': %@AS@% printf( "Enter\n" ); %@AS@% break; %@AS@% default: %@AS@% printf( "Bye bye" ); %@AS@% break; %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% The SWITCH.C program produces the same output as ELSE1.C. Figure 3.5 illustrates the %@AB@%switch%@AE@% statement in SWITCH.C, comparing it with the %@AB@%if%@AE@%-%@AB@%else%@AE@% construct in ELSE1.C. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% As in other decision-making statements, the parentheses after the keyword contain the expression to test. This can be any expression that yields a constant value. The test expression in SWITCH.C evaluates the value of the variable %@AS@% ch%@AE@%: %@NL@% %@NL@% %@AS@% switch( ch )%@AE@%%@NL@% %@NL@% %@AU@% The switch statement branches to one of several labeled alternatives.%@AE@% %@NL@% %@NL@% The test expression is followed by a statement block enclosed in curly braces. The block contains alternate sections of code that you want to execute under various circumstances. The program's action branches to one of the alternatives, depending on the value of the test expression. %@NL@% %@NL@% Each alternative in the statement block starts with a "case label," which consists of the %@AB@%case%@AE@% keyword, a constant or constant expression, and a colon. (The only other C statement that uses labels is %@AB@%goto%@AE@%, which we'll discuss later in this chapter.) %@NL@% %@NL@% Below is the first case label in SWITCH.C: %@NL@% %@NL@% %@AS@% case 'b':%@AE@%%@NL@% %@NL@% This case label lists the character constant %@AS@% 'b'%@AE@%. If the variable %@AS@% ch %@AE@% equals %@AS@% 'b'%@AE@%, the program's action branches to this label. If %@AS@% ch %@AE@% equals %@AS@% %@AS@%'\r'%@AE@%, the program branches to the following label: %@NL@% %@NL@% %@AS@% case '\r':%@AE@%%@NL@% %@NL@% The basic effect of %@AB@%switch%@AE@% is similar to the %@AB@%SELECT CASE%@AE@% statement in QuickBASIC. The program can branch to many different alternatives, but only one at a time. %@NL@% %@NL@% A %@AB@%switch%@AE@% statement can have as many %@AB@%case%@AE@% alternatives as you need. Each alternative must be labeled with a constant value. (You can't use a variable in the label.) %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%In previous versions of QuickC, the constant in a case label could only be a%@AI@% %@AI@%%@AE@%%@AI@%%@AB@%char%@AE@%%@AE@%%@AI@% or %@AE@%%@AI@%%@AB@%int%@AE@%%@AE@%%@AI@% value. In QuickC 2.5, the constant can be any integral type, %@AI@%including a %@AE@%%@AI@%%@AB@%long%@AE@%%@AE@%%@AI@% or %@AE@%%@AI@%%@AB@%unsigned%@AE@%%@AE@%%@AI@%%@AB@% %@AE@%%@AE@%%@AI@%%@AB@%long%@AE@%%@AE@%%@AI@% as well as a %@AE@%%@AI@%%@AB@%char%@AE@%%@AE@%%@AI@% or %@AE@%%@AI@%%@AB@%int%@AE@%%@AE@%%@AI@%. %@AI@%hapter 4, "Data Types," describes the %@AE@%%@AI@%%@AB@%char%@AE@%%@AE@%%@AI@%, %@AE@%%@AI@%%@AB@%int%@AE@%%@AE@%%@AI@%, and %@AE@%%@AI@%%@AB@%long%@AE@%%@AE@%%@AI@% types.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@AU@% The default keyword is used only in switch statements.%@AE@% %@NL@% %@NL@% SWITCH.C also shows how to use the %@AB@%default%@AE@% keyword in a %@AB@%switch%@AE@% statement. The statements after the %@AB@%default%@AE@% label execute if the value of the test expression doesn't equal any of the values listed in other labels. In SWITCH.C, the code following %@AB@%default%@AE@% executes when the variable %@AS@% ch %@AE@% equals anything other than %@AS@% 'b' %@AE@% or %@AS@% '\r'%@AE@%. %@NL@% %@NL@% Not every %@AB@%switch%@AE@% statement requires a %@AB@%default%@AE@% label. If no %@AB@%default%@AE@% is present, and the test expression doesn't match any of the values listed in the other %@AB@%case%@AE@% labels, no statements are executed. %@NL@% %@NL@% %@AU@% Use the break keyword to exit a switch statement.%@AE@% %@NL@% %@NL@% You normally place a %@AB@%break%@AE@% statement at the end of each alternative, as shown in SWITCH.C. The %@AB@%break%@AE@% statement exits the %@AB@%switch%@AE@% statement block immediately. If you don't put a %@AB@%break%@AE@% at the end of the alternative, the action falls through to the next statement. %@NL@% %@NL@% For instance, say that you remove all the %@AB@%break%@AE@% statements from SWITCH.C, as shown below: %@NL@% %@NL@% %@AS@% switch( ch ) %@AS@% { %@AS@% case 'b': %@AS@% printf( "Beep!\a\n" ); %@AS@% case '\r': %@AS@% printf( "Enter\n" ); %@AS@% default: %@AS@% printf( "Bye bye" ); %@AS@% }%@AE@%%@NL@% %@NL@% If you run the revised program and type the letter b, the program executes the first alternative, producing this output: %@NL@% %@NL@% %@AS@% Beep!%@AE@%%@NL@% %@NL@% then goes on to execute the statements that follow: %@NL@% %@NL@% %@AS@% Enter %@AS@% Bye bye%@AE@%%@NL@% %@NL@% Occasionally, you may want to fall through from one %@AB@%case%@AE@% alternative to another. But you should be careful not to omit %@AB@%break%@AE@% statements accidentally. (See the section "Omitting break Statements from a switch Statement" in Chapter 10, "Programming Pitfalls.") %@NL@% %@NL@% If you end each alternative with a %@AB@%break%@AE@%, as in SWITCH.C, the order of the alternatives isn't critical. The program branches to the label containing the correct value, no matter where that label appears in the %@AB@%switch%@AE@% statement block. For instance, you can reverse the order of the alternatives in SWITCH.C without changing the program's output. For readability's sake, many programmers put %@AB@%default%@AE@% at the end of a %@AB@%switch %@AE@%statement and arrange the other alternatives alphabetically or numerically. %@NL@% %@NL@% Sometimes you'll want to execute the same code for more than one case. This is done by grouping all the desired labels in front of one alternative. For instance, if you revise the second alternative in SWITCH.C to read %@NL@% %@NL@% %@AS@% case '\r': %@AS@% case '\t': %@AS@% case ' ': %@AS@% printf( "What a boring choice!\n" ); %@AS@% break;%@AE@%%@NL@% %@NL@% the program will print %@NL@% %@NL@% %@AS@% What a boring choice!%@AE@%%@NL@% %@NL@% when you press the ENTER key, the TAB key, or the SPACEBAR. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00030010 @%%@AB@%The break Statement%@AE@%%@EH@%%@NL@% %@NL@% The previous section explained how to use %@AB@%break%@AE@% to exit from a %@AB@%switch%@AE@% statement. You can also use %@AB@%break%@AE@% to end a loop immediately. The BREAKER.C program shows how to do this. The program prints a prompt, then displays characters as they are typed until the TAB key is pressed. %@NL@% %@NL@% %@AS@% /* BREAKER.C: Demonstrate break statement. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <conio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% char ch; %@AS@% printf( "Press any key. Press Tab to quit.\n" ); %@AS@% while( 1 ) %@AS@% { %@AS@% ch = getche(); %@AS@% if( ch == '\t' )%@AE@%%@NL@% %@NL@% %@AS@% { %@AS@% printf( "\a\nYou pressed Tab\n" ); %@AS@% break; %@AS@% } %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% The %@AB@%while%@AE@% statement in BREAKER.C creates an indefinite loop that calls the %@AB@%getche%@AE@% function again and again, assigning the function's return value to the variable %@AS@% ch%@AE@%. The %@AB@%if%@AE@% statement in the loop body compares %@AS@% ch %@AE@% to the tab character. When TAB is pressed, BREAKER.C prints %@AS@% You pressed Tab %@AE@% and executes the %@AB@%break%@AE@% statement, which terminates the %@AB@%while%@AE@% loop and ends the program. %@NL@% %@NL@% %@AU@% A break statement exits only one loop.%@AE@% %@NL@% %@NL@% It's important to remember that the %@AB@%break%@AE@% statement only ends the loop in which it appears. If two loops are nested, executing a %@AB@%break%@AE@% in the inner loop exits that loop but not the outer loop. BREAKER1.C shows how %@AB@%break%@AE@% works within nested loops. The program's inner loop checks for the TAB key and the outer loop checks for the ENTER key. %@NL@% %@NL@% %@AS@% /* BREAKER1.C: Break only exits one loop. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <conio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% char ch; %@AS@% printf( "Press any key. Press Enter to quit.\n" ); %@AS@% do %@AS@% { %@AS@% while( ( ch = getche() ) != '\r' ) %@AS@% { %@AS@% if( ch == '\t' ) %@AS@% { %@AS@% printf( "\a\nYou pressed Tab\n" ); %@AS@% break; %@AS@% } %@AS@% } %@AS@% } while( ch != '\r' ); %@AS@% printf( "\nBye bye." ); %@AS@% }%@AE@%%@NL@% %@NL@% The BREAKER1.C program includes a %@AB@%while%@AE@% loop nested within a %@AB@%do%@AE@% loop. Both loops test the same condition─whether the variable %@AS@% ch %@AE@% equals the ENTER key (%@AB@%\r%@AE@%). The %@AB@%while%@AE@% loop also calls the %@AB@%getche%@AE@% function, assigning the function's return value to %@AS@% ch%@AE@%. %@NL@% %@NL@% When TAB is pressed, the program prints %@AS@% You pressed Tab %@AE@% and executes a %@AB@%break%@AE@% statement, which terminates the inner loop. The %@AB@%break%@AE@% does not end the outer loop, however. The program continues until ENTER is pressed, providing the condition that ends both loops. %@NL@% %@NL@% Note that %@AB@%break%@AE@% can only be used to exit a loop or %@AB@%switch%@AE@% statement. While you might be tempted to use %@AB@%break%@AE@% to jump out of complex %@AB@%if%@AE@% or %@AB@%else%@AE@% statements, the %@AB@%break%@AE@% statement cannot be used for this purpose. It has no effect on %@AB@%if%@AE@% and %@AB@%else%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00030011 @%%@AB@%The continue Statement%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The continue statement skips remaining statements in the loop body where it %@AU@%appears.%@AE@% %@NL@% %@NL@% The %@AB@%continue%@AE@% statement, like %@AB@%break%@AE@%, interrupts the normal flow of execution in a loop body. But instead of ending the loop, %@AB@%continue%@AE@% skips all following statements in the loop body and triggers the next iteration of the loop. This effect can be useful within complex loops, in which you might wish to skip to the next loop iteration from various locations. %@NL@% %@NL@% The CONT.C program shows how %@AB@%continue%@AE@% works. It increments the %@AS@% count %@AE@% variable, counting from 0 through 9, but stops printing the value of %@AS@% count %@AE@% when that value exceeds 3. %@NL@% %@NL@% %@AS@% /* CONT.C: Demonstrate continue statement. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int count; %@AS@% for( count = 0; count < 10; count = count + 1 ) %@AS@% { %@AS@% if( count > 3 ) %@AS@% continue; %@AS@% printf( "count = %d\n", count ); %@AS@% } %@AS@% printf( "Done!\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% Here's the output from CONT.C: %@NL@% %@NL@% %@AS@% count = 0 %@AS@% count = 1 %@AS@% count = 2 %@AS@% count = 3 %@AS@% Done!%@AE@%%@NL@% %@NL@% The %@AB@%continue%@AE@% statement occurs within the body of the %@AB@%for%@AE@% loop. When the value of %@AS@% count %@AE@% exceeds 3, the %@AB@%continue%@AE@% skips the rest of the loop body─a statement that calls %@AB@%printf%@AE@%─and causes the next iteration of the loop. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00030012 @%%@AB@%The goto Statement%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The goto statement jumps from one part of the function to another.%@AE@% %@NL@% %@NL@% Similar to the %@AB@%GOTO%@AE@% statement in BASIC, %@AB@%goto%@AE@% in C performs an unconditional jump from one part of a function to any other part. The target of the %@AB@%goto%@AE@% statement is a label which you supply. The label must end with a colon, as do %@AB@%case%@AE@% labels, which we discussed earlier. %@NL@% %@NL@% Most C programmers avoid using the %@AB@%goto%@AE@% statement. It's a bit inconsistent with the overall philosophy of C, which encourages structured, modular programming. And, regardless of philosophy, it can be very difficult to read and debug a program that is littered with haphazard unconditional jumps. %@NL@% %@NL@% Nevertheless, %@AB@%goto%@AE@% has at least one sensible use. If a serious error occurs deep within a nested series of loops or conditional statements, %@AB@%goto%@AE@% offers the simplest escape. The following code has several levels of nesting, with a %@AB@%goto%@AE@% statement at the innermost level. If the value of %@AS@% error_count %@AE@% exceeds 15, the %@AB@%goto%@AE@% statement executes, transferring control to the label %@AS@% %@AS@%bail_out%@AE@%. %@NL@% %@NL@% %@AS@% if( a == 1 ) %@AS@% { %@AS@% while( b == 2 ) %@AS@% { %@AS@% for( c = 0; c < 3; c = c + 1 ) %@AS@% { %@AS@% if( d == 4 ) %@AS@% { %@AS@% while( e == 6 ) %@AS@% { %@AS@% if( error_count > 15 ) %@AS@% goto bail_out; %@AS@% } %@AS@% } %@AS@% } %@AS@% } %@AS@% } %@AS@% bail_out: /* The goto statement transfers control here. */%@AE@%%@NL@% %@NL@% To achieve the same effect without %@AB@%goto%@AE@%, you'd have to add extra conditional tests to this code, making the code more complex and perhaps less efficient. %@NL@% %@NL@% Names in %@AB@%goto%@AE@% labels are governed by the rules for variable names, which we'll discuss in the next two chapters. For now, just remember that a %@AB@%goto%@AE@% label is visible only in the function in which it appears. You can't execute a %@AB@%goto%@AE@% statement to jump from one function to another function. %@NL@% %@NL@% The next two chapters explain how to create and manipulate data─variables and constants─in C programs. Chapter 4, "Data Types," describes the basics, such as how to declare and initialize variables of different types. Chapter 5, "Advanced Data Types," describes more advanced topics, such as the visibility of variables. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00040001 @%%@1@%%@AB@%Chapter 4 Data Types%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% This chapter explains the C data types and shows how to declare and use C variables. The chapter begins by describing the basic data types from which all other data types are derived. We then discuss more complex data types, including arrays and structures. In Chapter 5, "Advanced Data Types," we'll explore more advanced data-handling topics, such as variable visibility and automatic type conversions. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00040002 @%%@AB@%Basic Data Types%@AE@%%@EH@%%@NL@% %@NL@% All data in C programs is either a constant or variable, and each has an associated data type. The concept of types is common to all high-level languages. For instance, an integer (whole) number has the %@AB@%INTEGER%@AE@% type in QuickBASIC, the %@AB@%Integer%@AE@% type in QuickPascal, and the %@AB@%int%@AE@% type in C. This section describes the basic data types in C and explains how to specify variables and constants using these types. %@NL@% %@NL@% All of the basic data types contain a single value. Types that contain more than one value─arrays, structures, and unions─are called "aggregate types." We'll discuss aggregate types later in this chapter. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040003 @%%@AB@%Specifying Basic Types%@AE@%%@EH@%%@NL@% %@NL@% The C language has four basic data types, which are specified with the keywords %@AB@%char%@AE@%, %@AB@%int%@AE@%, %@AB@%float%@AE@%, and %@AB@%double%@AE@%. The %@AB@%char%@AE@% (character) type is used for text and the %@AB@%int%@AE@% type for integers. The %@AB@%float%@AE@% and %@AB@%double%@AE@% types express real (floating-point) values. %@NL@% %@NL@% The TYPES.C program creates variables of the four basic types and prints their values: %@NL@% %@NL@% %@AS@% /* TYPES.C: Illustrate basic data types. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% char char_val = 'a'; %@AS@% int int_val = 543; %@AS@% float float_val = 11.1; %@AS@% double double_val = 66.123456789; %@AS@% printf( "char_val = %c\n", char_val ); %@AS@% printf( "int_val = %d\n", int_val ); %@AS@% printf( "float_val = %f\n", float_val ); %@AS@% printf( "double_val = %2.9f\n", double_val ); %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from TYPES.C: %@NL@% %@NL@% %@AS@% char_val = a %@AS@% int_val = 543 %@AS@% float_val = 11.100000 %@AS@% double_val = 66.123456789%@AE@%%@NL@% %@NL@% Each basic data type requires a different amount of memory, as illustrated in Figure 4.1. In QuickC, a %@AB@%char%@AE@% contains one byte, an %@AB@%int%@AE@% has two bytes, a %@AB@%float%@AE@% has four bytes, and a %@AB@%double%@AE@% type has eight bytes. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The C language is designed to run on many different computers, with machine %@AI@%architectures that may be quite different. To accommodate these differences, %@AI@%some C data types are "implementation dependent," meaning their sizes depend %@AI@%on which computer you're using. For instance, the%@AI@% %@AE@%%@AI@%%@AB@%int%@AE@%%@AE@%%@AI@% (i%@AE@%%@AI@%nteger) type %@AI@%contains two bytes on IBM PC computers and four bytes on VAX%@AE@%%@AI@%(R) %@AI@%%@AE@%%@AI@%minicomputers. These differences are %@AE@%%@AI@%%@AE@%%@AI@%i%@AE@%%@AI@%mportant only if you're transporting a %@AI@%program%@AE@%%@AI@%%@AE@%%@AI@% f%@AE@%%@AI@%rom one%@AE@%%@AI@%%@AE@%%@AI@% %@AE@%%@AI@%operating system to another. Since QuickC runs only under %@AI@%one operating system (DOS), this book describes C data types in DOS.%@AE@%%@AI@%%@AE@%%@AI@%%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Special Type Specifiers%@AE@%%@EH@%%@NL@% %@NL@% The C language has four special type specifiers─%@AB@%signed%@AE@%, %@AB@%unsigned%@AE@%, %@AB@%long%@AE@%, and %@AB@%short%@AE@%. These act as "adjectives" to modify the range of values expressed by a basic data type. %@NL@% %@NL@% %@AU@% The char and int data types are signed by default.%@AE@% %@NL@% %@NL@% The %@AB@%signed%@AE@% keyword signifies that a value can be either negative or nonnegative. If you don't specify, a %@AB@%char%@AE@% or %@AB@%int%@AE@% value is signed. %@NL@% %@NL@% You can preface a %@AB@%char%@AE@% or %@AB@%int%@AE@% with %@AB@%unsigned%@AE@% to extend the range of nonnegative values. An %@AB@%unsigned int%@AE@% can have a value in the range 0 through 65,535, and an %@AB@%unsigned char%@AE@% can have a value of 0 through 255. %@NL@% %@NL@% The %@AB@%long%@AE@% keyword is used to increase the size of an %@AB@%int%@AE@% or %@AB@%double%@AE@% type. A %@AB@%long int%@AE@% value contains four bytes (twice as many as an %@AB@%int%@AE@%) and expresses an integer in the range -2,147,483,648 through 2,147,483,647. A %@AB@%long double%@AE@% value contains 10 bytes and can express a floating-point number with 19 digits of precision. %@NL@% %@NL@% In QuickC, the %@AB@%short int%@AE@% type is identical to the %@AB@%int%@AE@% type. (This is not the case in some operating systems other than DOS.) %@NL@% %@NL@% Table 4.1 lists the basic data types and the range of values each can express. %@NL@% %@NL@% %@AB@%Table 4.1 %@AB@%Basic Data Types%@AE@%%@AE@% %@TH: 38 1798 02 17 25 34 @%Type Name Other Names Range of Values%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%char%@AE@% %@AB@%signed char%@AE@% -128 to 127%@AB@%unsigned char%@AE@% none 0 to 255%@AB@%int%@AE@% %@AB@%signed%@AE@%, %@AB@%signed int%@AE@% -32,768 to 32,767%@AB@%unsigned%@AE@% %@AB@%unsigned int%@AE@% 0 to 65,535%@AB@%unsigned short%@AE@% %@AB@%unsigned short int %@AE@% 0 to 65,535%@AB@%short%@AE@% %@AB@%short int%@AE@%, %@AB@%signed short%@AE@% -32,768 to 32,767 %@AB@%signed short int%@AE@% %@AB@%long%@AE@% %@AB@%long int%@AE@%, %@AB@%signed long%@AE@% -2,147,483,648 to%@AB@%%@AE@% %@AB@%signed long int%@AE@% 2,147,483,647%@AB@%unsigned long%@AE@% %@AB@%unsigned long int%@AE@% 0 to 4,294,967,295 %@AB@%%@AE@% %@AB@%%@AE@% %@AB@% %@AE@% %@AB@%float%@AE@% none Approximately 1.2E-38 to 3.4E+38 (7-digit precision)%@AB@%double%@AE@% none Approximately 2.2E-308 to 1.8E+308 (15-digit precision)%@AB@%long double%@AE@% none Approximately 3.4E-4932 to 1.2E+4932 (19-digit precision)%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 38 1798 02 17 25 34 @% Most programmers take advantage of type defaults. If a type qualifier appears alone, the type %@AB@%int%@AE@% is implied. By itself, %@AB@%short%@AE@% is a synonym for %@AB@%short int%@AE@%. Where %@AB@%long%@AE@% appears alone it is a synonym for %@AB@%long int%@AE@%, and where %@AB@%unsigned%@AE@% appears alone it is a synonym for %@AB@%unsigned int%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040004 @%%@AB@%Specifying Variables%@AE@%%@EH@%%@NL@% %@NL@% As we mentioned in Chapter 1, "Anatomy of a C Program," you must declare every variable in a C program by stating the variable's name and type. Variable names are governed by the following rules, which also apply to other userdefined names such as function names: %@NL@% %@NL@% %@NL@% ■ C is case-sensitive. For example, %@AS@% myvar%@AE@%, %@AS@% MyVar%@AE@%, and %@AS@% MYVAR %@AE@% are different names.%@NL@% %@NL@% ■ The name can't be a keyword (see online help for a list of keywords).%@NL@% %@NL@% ■ The first character must be a letter or underscore (%@AS@% %@AE@%%@AB@%_ %@AE@%). Many of QuickC's system-defined names, including some library-routine names, begin with underscores. To avoid conflicts with such names, don't create names that begin with underscores.%@NL@% %@NL@% ■ Other characters can be letters, digits, or underscores.%@NL@% %@NL@% ■ The first 31 characters of local variable names are significant. The name can contain more than 31 characters, but QuickC ignores everything beyond the thirty-first character. Global variable names are normally significant to 30 characters.%@NL@% %@NL@% %@NL@% All C keywords are lowercase, and it's common to use lowercase for variable names. Mixed case is becoming popular in some contexts, however. OS/2 and Microsoft Windows(tm) use mixed case for most system-defined names. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040005 @%%@AB@%Specifying Constants%@AE@%%@EH@%%@NL@% %@NL@% Constants─values that don't change during the life of the program─can be numbers, characters, or strings. Your program can also define "symbolic constants," which are names that represent constant values. This section describes how to specify C constants. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Numeric Constants%@AE@%%@EH@%%@NL@% %@NL@% A numeric constant can have any basic data type, and can be specified in decimal, hexadecimal, or octal notation. Table 4.2 shows how to specify numeric constants. %@NL@% %@NL@% %@AB@%Table 4.2 %@AB@%Constant Specifications%@AE@%%@AE@% %@TH: 13 691 02 19 57 @%Constant Type%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%255 decimal %@AB@%int%@AE@%0xFF hexadecimal %@AB@%int%@AE@% (255)0377 octal %@AB@%int %@AE@%(255)255L %@AB@%long int%@AE@%255U %@AB@%unsigned int%@AE@%0xFFul %@AB@%long unsigned %@AE@%hexadecimal %@AB@%int%@AE@% (255)15.75E2 floating point (1575)-.123 floating point.123 floating point3e0f floating point%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 13 691 02 19 57 @% A number without a suffix, such as 255, is treated as decimal. The %@AS@% 0x %@AE@% prefix specifies a hexadecimal number, and the %@AS@% 0 %@AE@% (zero) prefix specifies octal (base 8). %@NL@% %@NL@% If a number doesn't have a decimal point, it is an integer. Integers are signed by default; you can use the suffix %@AS@% U %@AE@% or %@AS@% u %@AE@% to specify an unsigned constant. To specify a %@AB@%long%@AE@% integer, place the suffix %@AS@% L %@AE@% or %@AS@% l %@AE@% after the number. %@NL@% %@NL@% A floating-point constant contains either a decimal point or an exponent preceded by %@AS@% e %@AE@% or %@AS@% E %@AE@%. It can optionally include the suffix %@AS@% F %@AE@% or %@AS@% f %@AE@% to denote the %@AB@%float%@AE@% type or the suffix %@AS@% L %@AE@% or %@AS@% l%@AE@% to denote the %@AB@%long double%@AE@% type. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Character and String Constants%@AE@%%@EH@%%@NL@% %@NL@% The C language uses different notation for character and string constants. A single character enclosed in single quotes is a character constant: %@NL@% %@NL@% %@AS@% 'a'%@AE@%%@NL@% %@NL@% A string constant is 0 or more characters enclosed in double quotes: %@NL@% %@NL@% %@AS@% "Hello"%@AE@%%@NL@% %@NL@% A string also ends with a null character (%@AB@%\0%@AE@%), as we'll see in the section "Strings." %@NL@% %@NL@% The difference between character and string constants is important when you perform comparisons. The character constant %@AS@% 'a' %@AE@% contains 1 character, but the string constant %@AS@% "a" %@AE@% contains 2 characters: the letter %@AS@% a %@AE@% plus a null character. Because the two values have a different number of characters, any comparison of them is invalid. (See "String Problems" in Chapter 10, "Programming Pitfalls.") %@NL@% %@NL@% You can specify special characters, such as the tab and backspace, with a multi-character sequence that begins with a backslash ( \ ). These sequences are sometimes called "escape sequences." Table 4.3 shows the special character sequences. %@NL@% %@NL@% %@AB@%Table 4.3 %@AB@%Special Characters%@AE@%%@AE@% %@TH: 16 906 02 24 52 @%Sequence Character%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%\a%@AE@% Alert (bell)%@AB@%\b %@AE@% Backspace%@AB@%\f%@AE@% Form feed%@AB@%\n%@AE@% Newline%@AB@%\r%@AE@% Carriage return%@AB@%\t%@AE@% Horizontal tab%@AB@%\v%@AE@% Vertical tab%@AB@%\'%@AE@% Single quote%@AB@%\"%@AE@% Double quote%@AB@%\\%@AE@% Backslash%@AB@%\%@AE@%%@AI@%ooo%@AE@% Octal notation%@AB@%\%@AE@%%@AI@%xhh%@AE@% Hexadecimal notation%@AB@%\0%@AE@% Null%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 16 906 02 24 52 @% Some unusual characters don't have a predefined sequence. You can specify these with a backslash ( %@AB@%\ %@AE@%) followed by the hexadecimal or octal number representing the character's ASCII value. For instance, a telecommunications program might need to specify ASCII 21, the NAK ("not acknowledged") character. You can specify this character in either hexadecimal notation, %@AS@% %@AS@%'\x15'%@AE@%, or octal notation, %@AS@%'\25'%@AE@%. Note that the hexadecimal number begins with %@AS@% \x%@AE@%, while the octal number starts with a backslash alone. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Symbolic Constants%@AE@%%@EH@%%@NL@% %@NL@% A "symbolic constant" is a user-defined name that represents a constant. Symbolic constants are usually typed in uppercase. For instance, the directive %@NL@% %@NL@% %@AS@% #define PI 3.14%@AE@%%@NL@% %@NL@% declares a symbolic constant named %@AS@% PI%@AE@%. Wherever %@AS@% PI %@AE@% occurs in the program, the compiler substitutes %@AS@% 3.14%@AE@%. Chapter 7, "Preprocessor Directives," discusses symbolic constants and the %@AB@%#define%@AE@% directive. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00040006 @%%@AB@%Aggregate Data Types%@AE@%%@EH@%%@NL@% %@NL@% This section describes aggregate data types, which contain organized collections of data in a definite order. In C, the aggregate types are arrays, structures, and unions. %@NL@% %@NL@% An "array" is a collection of data items of the same type. Programs use arrays in cases where a standard data format is repeated many times. For example, you might use an array to store numbers representing the population of Minnesota for all the years from 1950 to 2000. C-language arrays are very similar to arrays in QuickPascal and QuickBASIC. %@NL@% %@NL@% A "structure" is a collection of data items of different types. Programs use structures in cases where a variety of data have a close association. For example, you might use a structure to store information about a given employee─name, months of employment, and hourly wage. Structures are similar to QuickPascal records or QuickBASIC user-defined types. %@NL@% %@NL@% A "union" allows you to use different data formats to access the same area of memory. It can hold different kinds of information at different times. Unions are similar to variant records in QuickPascal. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040007 @%%@AB@%Arrays%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% An array is a group of data items of the same type under one name.%@AE@% %@NL@% %@NL@% The simplest aggregate data type is an array: a group of data items that share the same type and a common name. You can make an array from any data type, including basic types such as %@AB@%char%@AE@% and %@AB@%int%@AE@% and more complex types such as structures. This section shows how to declare, initialize, and access arrays, including arrays with more than one dimension. We'll begin with a simple example that creates a one-dimensional array. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Creating a Simple Array%@AE@%%@EH@%%@NL@% %@NL@% The ARRAY.C program creates the array %@AS@% i_array%@AE@%, which contains three integers. %@NL@% %@NL@% %@AS@% /* ARRAY.C: Demonstrate one-dimensional array. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int j; %@AS@% int i_array[3]; %@AS@% %@AS@% i_array[0] = 176; %@AS@% i_array[1] = 4069; %@AS@% i_array[2] = 303; %@AS@% %@AS@% printf( "--- Values -------- --- Addresses -------\n\n" ); %@AS@% %@AS@% for( j = 0; j < 3; j = j + 1 ) %@AS@% { %@AS@% printf( "i_array[%d] = %d", j, i_array[j] ); %@AS@% printf( "\t&i_array[%d] = %u\n", j, &i_array[j] ); %@AS@% } %@AS@% %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from ARRAY.C: %@NL@% %@NL@% %@AS@% --- Values -------- --- Addresses ------- %@AS@% %@AS@% i_array[0] = 176 &i_array[0] = 3506 %@AS@% i_array[1] = 4069 &i_array[1] = 3508 %@AS@% i_array[2] = 303 &i_array[2] = 3510%@AE@%%@NL@% %@NL@% As you can see, ARRAY.C prints the values in %@AS@% i_array %@AE@% and the memory address where each array element is stored. You usually don't have to worry about actual memory addresses in C, but it's useful to have some idea how array elements are stored in memory. Depending on factors such as the amount of memory in your system, you may see different addresses when you run ARRAY.C. %@NL@% %@NL@% (The second %@AB@%printf%@AE@% statement uses the "address-of" operator (%@AB@%&%@AE@%) to determine the address of each array element. Chapter 6, "Operators," explains this operator. For now, it's sufficient to recognize that the operator allows ARRAY.C to print addresses.) %@NL@% %@NL@% Figure 4.2 shows how %@AS@% i_array %@AE@% is stored in the addresses from the ARRAY.C output. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Declaring the Array%@AE@%%@EH@%%@NL@% %@NL@% You declare an array variable by stating its type and its name, as you would a simple variable. You must also declare the size of the array, stating the number of elements with an integer constant in square brackets. For example, the line %@NL@% %@NL@% %@AS@% int i_array[3];%@AE@%%@NL@% %@NL@% from ARRAY.C declares a three-element integer (%@AB@%int%@AE@%) array named %@AS@% i_array%@AE@%. %@NL@% %@NL@% Multidimensional arrays are declared the same way, except you must give the size of each dimension. The following statement, for instance, declares a twodimensional %@AB@%int%@AE@% array named %@AS@% two_dim%@AE@%: %@NL@% %@NL@% %@AS@% int two_dim[2][3];%@AE@%%@NL@% %@NL@% We'll return to multidimensional arrays a little later in this chapter. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Initializing the Array%@AE@%%@EH@%%@NL@% %@NL@% Arrays, like simple variables, should be initialized before use. ARRAY.C initializes %@AS@% i_array %@AE@% with these statements: %@NL@% %@NL@% %@AS@% i_array[0] = 176; %@AS@% i_array[1] = 4069; %@AS@% i_array[2] = 303;%@AE@%%@NL@% %@NL@% %@AU@% An array can be initialized when it is declared.%@AE@% %@NL@% %@NL@% ARRAY.C declares an array in one statement and then initializes its elements one by one. You can also initialize an array when you declare it. The following statement does both jobs at once: %@NL@% %@NL@% %@AS@% int i_array[3] = { 176, 4069, 303 };%@AE@%%@NL@% %@NL@% Note the curly braces around the initializing values. The braces are mandatory in this kind of initialization. %@NL@% %@NL@% Under the ANSI C standard, which QuickC version 2.5 follows, you can simultaneously declare and initialize an array within a function. Pre-ANSI compilers, including QuickC version 1.0, don't allow this unless the %@AB@%static%@AE@% keyword precedes the array declaration. Chapter 5, "Advanced Data Types," discusses %@AB@%static%@AE@%. %@NL@% %@NL@% When you declare and initialize an array at the same time, the initializing values are normally constants, as shown above. Occasionally, you may want to initialize an array as you declare it using variables instead of constants. QuickC version 2.5 allows this, but only within a function. The %@AS@% sample %@AE@% array in the following example is initialized legally under QuickC version 2.5 but illegally under QuickC version 1.0: %@NL@% %@NL@% %@AS@% func() %@AS@% { %@AS@% int val = 5; %@AS@% int sample[3] = { val, val, val }; %@AS@% }%@AE@%%@NL@% %@NL@% If you initialize a local array in this way, you must include the size of the array within the square brackets following the array name. If the example initialized the %@AS@% sample %@AE@% array with the following line: %@NL@% %@NL@% %@AS@% int sample[ ] = {val, val, val};%@AE@%%@NL@% %@NL@% QuickC would issue an error because the size of the array (3) is not specified. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Specifying Array Elements%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Array subscripts are enclosed in square brackets ( [ ] ).%@AE@% %@NL@% %@NL@% You specify an array element by giving its position, using an integer value called a "subscript." Square brackets ([ ]) enclose each subscript. In the ARRAY.C program above we specify the first element of %@AS@% i_array %@AE@% as %@NL@% %@NL@% %@AS@% i_array[0]%@AE@%%@NL@% %@NL@% Notice that the first element of a C array has the subscript 0, not 1. Unlike QuickPascal and QuickBASIC, the C language does not give you the option to start at an index number other than 0. %@NL@% %@NL@% Since array subscripts begin at 0, the subscript of the last array element is 1 less than the number used to declare that dimension of the array. In ARRAY.C, the last element of %@AS@% i_array %@AE@% is %@AS@% i_array[2] %@AE@%, not %@AS@% i_array[3]%@AE@%. %@NL@% %@NL@% %@AU@% C doesn't check array subscripts.%@AE@% %@NL@% %@NL@% Unlike QuickBASIC and QuickPascal, C doesn't check the validity of array subscripts. If the ARRAY.C program included the expression %@NL@% %@NL@% %@AS@% i_array[55];%@AE@%%@NL@% %@NL@% it would refer to a nonexistent array element. (The expression refers to the element 55, but %@AS@% i_array %@AE@% contains only three elements.) This would not trigger a compiler error or run-time error, however. It's your job to remember the size of the array and avoid references that go outside the array's boundaries. This rule is also important when you're accessing arrays with pointers (see Chapter 8, "Pointers"). %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Strings%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A string is an array of characters.%@AE@% %@NL@% %@NL@% You may have wondered why we didn't mention strings in our earlier description of basic data types. The reason is that strings aren't a formal data type. In the C language, a string is simply an array of characters (%@AB@%char%@AE@% values). %@NL@% %@NL@% The STRING.C program below creates the string %@AS@% c_array %@AE@% and displays its contents in the same format as the previous example. The program prints the value of each array element and its address. %@NL@% %@NL@% %@AS@% /* STRING.C: Demonstrate string arrays. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int j; %@AS@% char c_array[] = "Hello"; %@AS@% %@AS@% printf( "--- Values -------- --- Addresses -------\n\n" ); %@AS@% %@AS@% for( j = 0; j < 6; j = j + 1 ) %@AS@% { %@AS@% printf( "c_array[%d] = %x %c", j, c_array[j], c_array[j] ); %@AS@% printf( "\t&c_array[%d] = %u\n", j, &c_array[j] ); %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from STRING.C: %@NL@% %@NL@% %@AS@% --- Values -------- --- Addresses ------- %@AS@% %@AS@% c_array[0] = 48 H &c_array[0] = 3522 %@AS@% c_array[1] = 65 e &c_array[1] = 3523 %@AS@% c_array[2] = 6c l &c_array[2] = 3524 %@AS@% c_array[3] = 6c l &c_array[3] = 3525 %@AS@% c_array[4] = 6f o &c_array[4] = 3526 %@AS@% c_array[5] = 0 &c_array[5] = 3527%@AE@%%@NL@% %@NL@% Figure 4.3 shows how %@AS@% c_array %@AE@% is stored in memory. Again, the addresses in the output may differ depending on factors such as the amount of available memory. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@AU@% A string ends with a null character.%@AE@% %@NL@% %@NL@% The figure illustrates another important feature of strings. Although %@AS@% %@AS@%c_array %@AE@% has five printing characters (%@AS@% Hello %@AE@%), it actually contains six characters─five letters plus a null character (%@AB@%\0%@AE@%) that marks the end of the string. As noted earlier, the C language automatically adds a null character to every string enclosed in double quotes. %@NL@% %@NL@% STRING.C uses a shortcut when it initializes %@AS@% c_array%@AE@%. You may have noticed that the array declaration %@NL@% %@NL@% %@AS@% char c_array[] = "Hello";%@AE@%%@NL@% %@NL@% doesn't declare the array's size (the square brackets are empty). When an array is initialized at the same time it's declared, QuickC can figure out how many elements the array has by counting the number of initializing values to the right of the equal sign. %@NL@% %@NL@% You can use this shortcut for any type of array, not just a %@AB@%char%@AE@% array. If the array has more than one dimension, however, you can only omit the size of the first dimension. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Multidimensional Arrays%@AE@%%@EH@%%@NL@% %@NL@% A "multidimensional" array contains two or more array dimensions. The TWODIM.C program below creates a two-dimensional array named %@AS@% i_array. %@AE@%%@NL@% %@NL@% %@AS@% /* TWODIM.C: Demonstrate multidimensional arrays. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int j, k; %@AS@% int i_array[2][3] = { { 176, 4069, 303 }, { 6, 55, 777 } }; %@AS@% %@AS@% printf( "--- Values -------- --- Addresses -------\n\n" ); %@AS@% %@AS@% for( j = 0; j < 2; j = j + 1 ) %@AS@% { %@AS@% for( k = 0; k < 3; k = k + 1 ) %@AS@% { %@AS@% printf( "i_array[%d][%d] = %d", j, k, i_array[j][k] ); %@AS@% printf( "\t&i_array[%d][%d] = %u\n", j, k, &i_array[j][k] ); %@AS@% } %@AS@% printf( "\n" ); %@AS@% } %@AS@% %@AS@% }%@AE@%%@NL@% %@NL@% Here's the output from TWODIM.C: %@NL@% %@NL@% %@AS@% --- Values -------- --- Addresses ------- %@AS@% %@AS@% i_array[0][0] = 176 &i_array[0][0] = 3498 %@AS@% i_array[0][1] = 4069 &i_array[0][1] = 3500 %@AS@% i_array[0][2] = 303 &i_array[0][2] = 3502 %@AS@% %@AS@% i_array[1][0] = 6 &i_array[1][0] = 3504 %@AS@% i_array[1][1] = 55 &i_array[1][1] = 3506 %@AS@% i_array[1][2] = 777 &i_array[1][2] = 3508%@AE@%%@NL@% %@NL@% Each subscript of a multidimensional array appears in its own set of square brackets, as the TWODIM.C output shows. When you declare the array, the first subscript states the size of the first dimension, the second states the size of the second dimension, and so on. In TWODIM.C, the declaration of %@AS@% i_array%@AE@%, %@NL@% %@NL@% %@AS@% int i_array[2][3]%@AE@%%@NL@% %@NL@% states that %@AS@% i_array %@AE@% contains two rows of values, each row containing three integers. The statement that declares %@AS@% i_array %@AE@% also initializes the array, listing the initializing values in curly braces to the right of the equal sign: %@NL@% %@NL@% %@AS@% int i_array[2][3] = { { 176, 4069, 303 }, { 6, 5, 77 } };%@AE@%%@NL@% %@NL@% The braces clearly show that the array contains two groups of three values. %@NL@% %@NL@% Two-dimensional arrays are often pictured in rows and columns, as in Figure 4.4. Of course, since computer memory is linear, %@AS@% i_array %@AE@% is actually stored with its rows end-for-end, as in Figure 4.5. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% You refer to a multidimensional array element the same way you would a onedimensional array element, except that you use one subscript for each dimension of the array. For instance, the statement %@NL@% %@NL@% %@AS@% printf( "%d\n", i_array[0][1] );%@AE@%%@NL@% %@NL@% specifies two subscripts. It prints the value stored in element 0, 1 of %@AS@% %@AS@%i_array%@AE@%, which is %@AS@% 4069%@AE@%. %@NL@% %@NL@% Figure 4.5 shows how to specify every element of %@AS@% i_array %@AE@% in TWODIM.C. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040008 @%%@AB@%Structures%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A structure is a group of related data items of different types under one %@AU@%name.%@AE@% %@NL@% %@NL@% The second aggregate data type is the structure: a group of related data items under one name. While array elements are all the same type, the elements of a structure, known as its "members," can be of different types. %@NL@% %@NL@% Structures are equivalent to records in QuickPascal or user-defined types in QuickBASIC. As in those languages, the ability to group different types in the same construct provides powerful, very flexible data-handling capabilities. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Creating a Simple Structure%@AE@%%@EH@%%@NL@% %@NL@% We'll write a simple program to demonstrate the basics of structures. Suppose you want to write a payroll program that records these facts about an employee: %@NL@% %@NL@% %@NL@% ■ Name%@NL@% %@NL@% ■ Number of months of service%@NL@% %@NL@% ■ Hourly wage%@NL@% %@NL@% %@NL@% Each of these data items requires a different data type. The name can be stored in a string (character array), while an integer will do for the months of service. The hourly wage may contain a fraction; we'll store it in a floating-point variable. %@NL@% %@NL@% Although each of these variables has a different type, we can group all of them in a single structure. The EMPLOYEE.C program below contains the structure. %@NL@% %@NL@% %@AS@% /* EMPLOYEE.C: Demonstrate structures. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <string.h> %@AS@% %@AS@% struct employee %@AS@% { %@AS@% char name[10]; %@AS@% int months; %@AS@% float wage; %@AS@% }; %@AS@% %@AS@% void display( struct employee show ); %@AS@% %@AS@% main() %@AS@% { %@AS@% struct employee jones; %@AS@% %@AS@% strcpy( jones.name, "Jones, J" ); %@AS@% jones.months = 77; %@AS@% jones.wage = 13.68; %@AS@% %@AS@% display( jones ); %@AS@% } %@AS@% %@AS@% void display( struct employee show ) %@AS@% { %@AS@% printf( "Name: %s\n", show.name ); %@AS@% printf( "Months of service: %d\n", show.months ); %@AS@% printf( "Hourly wage: %6.2f\n", show.wage ); %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output of the EMPLOYEE.C program: %@NL@% %@NL@% %@AS@% Name: Jones, J %@AS@% Months of service: 77 %@AS@% Hourly wage: 13.68%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Declaring a Structure Type%@AE@%%@EH@%%@NL@% %@NL@% Since a structure can (and normally does) contain different data types, creating it is a little more complicated than making an array or simple variable. Before you can create a structure variable, you must declare a structure type that tells the compiler how many members the structure contains and what types they are. %@NL@% %@NL@% A structure-type declaration starts with the keyword %@AB@%struct%@AE@%, which is followed by a list of the structure's members enclosed in braces. Between the %@AB@%struct%@AE@% and the list of members, you can also specify a "structure tag"─a name that other parts of the program can use to refer to the type. %@NL@% %@NL@% The structure declaration from EMPLOYEE.C, %@NL@% %@NL@% %@AS@% struct employee %@AS@% { %@AS@% char name[10]; %@AS@% int months; %@AS@% float wage; %@AS@% };%@AE@%%@NL@% %@NL@% %@AU@% A structure declaration makes a template for variables of the type it %@AU@%defines.%@AE@% %@NL@% %@NL@% creates a "template" for an %@AS@% employee %@AE@% structure that structure variables of this type can use. It's as if you created a brand new data type, tagging it %@AS@%employee%@AE@%. Figure 4.6 illustrates the %@AS@% employee %@AE@% structure type. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Creating a Structure Variable%@AE@%%@EH@%%@NL@% %@NL@% Once you have declared a structure, you can create variables of that type using the structure tag. Each variable can contain values of the types defined in the structure type. In EMPLOYEE.C, the statement %@NL@% %@NL@% %@AS@% struct employee jones;%@AE@%%@NL@% %@NL@% declares a structure variable of the type %@AS@% employee %@AE@% named %@AS@% jones%@AE@%. The %@AB@%struct%@AE@% states that the variable is a structure. The %@AS@% employee %@AE@% tag specifies the variable's structure type, and %@AS@% jones %@AE@% is the variable's name. %@NL@% %@NL@% You can also declare the variable in the same statement that declares the structure type. The following code declares the %@AS@% employee %@AE@% structure type and a variable of that type named %@AS@% jones%@AE@%: %@NL@% %@NL@% %@AS@% struct employee %@AS@% { %@AS@% char name[10]; %@AS@% int months; %@AS@% float wage; %@AS@% } jones;%@AE@%%@NL@% %@NL@% The variable name (%@AS@% jones %@AE@%) appears at the end of the declaration. %@NL@% %@NL@% %@AU@% Use the member-of operator (.) to specify structure members.%@AE@% %@NL@% %@NL@% You specify structure members by name, using the "member-of" operator (%@AB@%.%@AE@%) to separate the variable name and the member name. These are the names of the members of the %@AS@% jones %@AE@% structure variable in EMPLOYEE.C: %@NL@% %@NL@% %@AS@% jones.name %@AS@% jones.months %@AS@% jones.wage%@AE@%%@NL@% %@NL@% Like other variables, structure variables should be initialized before use. After %@AS@% jones %@AE@% is declared in EMPLOYEE.C, the statements %@NL@% %@NL@% %@AS@% strcpy( jones.name, "Jones, J" ); %@AS@% jones.months = 77; %@AS@% jones.wage = 13.68;%@AE@%%@NL@% %@NL@% initialize the members of the %@AS@% jones %@AE@% variable. The first statement initializes the %@AS@% jones.name %@AE@% member by calling the %@AB@%strcpy%@AE@% ("string copy") library function; this function is described in Chapter 11, "Input and Output." %@NL@% %@NL@% Figure 4.7 shows how the %@AS@% jones %@AE@% structure is stored in memory. Again, since computer memory is linear, the members of the structure are laid out end-to-end. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% You can initialize a structure when you declare it. The following code would perform both operations in EMPLOYEE.C: %@NL@% %@NL@% %@AS@% struct employee jones = %@AS@% { %@AS@% "Jones, J", %@AS@% 77, %@AS@% 13.68 %@AS@% };%@AE@%%@NL@% %@NL@% This code declares the %@AS@% jones %@AE@% structure variable and lists the initializing value for each of its members. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Using Structure Variables%@AE@%%@EH@%%@NL@% %@NL@% A structure member can be treated like any other variable of its type. You can assign a value to it, change its value, and so on. For instance, the statement %@NL@% %@NL@% %@AS@% jones.months = 83;%@AE@%%@NL@% %@NL@% would change the value of the %@AS@% jones.months %@AE@% member in EMPLOYEE.C. %@NL@% %@NL@% %@AU@% Assigning one structure to another copies the entire structure.%@AE@% %@NL@% %@NL@% You can also assign an entire structure to another structure of the same type. This copies the entire contents of the first structure to the second. You might do this to save time when creating a new structure whose contents differ only slightly from those of an existing structure. %@NL@% %@NL@% To illustrate, let's modify the EMPLOYEE.C program. Say you have a second employee named Lavik whose wage rate and months of service are the same as those of Jones and you want to create a second structure. You could begin by declaring a second %@AS@% employee %@AE@% structure variable named %@AS@% lavik %@AE@% in this fashion: %@NL@% %@NL@% %@AS@% struct employee lavik = jones;%@AE@%%@NL@% %@NL@% Now the members of the %@AS@% lavik %@AE@% structure contain the same data as the members of the %@AS@% jones %@AE@% structure. The %@AS@% lavik.name %@AE@% member contains the string %@AS@% Jones, J%@AE@%, the %@AS@% lavik.months %@AE@% member contains the value 77, and the %@AS@% %@AS@%lavik.wage %@AE@% member contains the value 13.68. You could add the statement %@NL@% %@NL@% %@AS@% strcpy( lavik.name, "Lavik, B" );%@AE@%%@NL@% %@NL@% to place a new string in the %@AS@% lavik.name %@AE@% member. %@NL@% %@NL@% %@AU@% Structure variables can be passed as function arguments.%@AE@% %@NL@% %@NL@% When you pass a structure name to a function, the function creates a local structure variable of that type. Like all local variables, the new variable is private to the function that includes it. %@NL@% %@NL@% For example, if you add the statements %@NL@% %@NL@% %@AS@% strcpy( show.name, "King, M" ); %@AS@% printf( "%s\n", show.name );%@AE@%%@NL@% %@NL@% to the end of the %@AS@% display %@AE@% function in EMPLOYEE.C, then a new string is copied into the %@AS@% show.name %@AE@% member of the function's structure variable. The %@AB@%printf%@AE@% statement in the second line prints %@NL@% %@NL@% %@AS@% King, M%@AE@%%@NL@% %@NL@% Since this structure is local to the %@AS@% display %@AE@% function, the change doesn't affect the structure defined in the %@AB@%main%@AE@% function. If you add the statement %@NL@% %@NL@% %@AS@% printf( "%s\n", jones.name );%@AE@%%@NL@% %@NL@% to the end of the %@AB@%main%@AE@% function, the program prints %@NL@% %@NL@% %@AS@% Jones, J%@AE@%%@NL@% %@NL@% The original structure is unchanged. %@NL@% %@NL@% While you can pass a structure name to a function as we did above, it's more common to pass the function a %@AI@%pointer%@AE@% to the structure. This not only permits the function to access a structure defined elsewhere in the program, but it conserves memory (since the function doesn't create a local copy of the structure). Chapter 9, "Advanced Pointers," explains how to access structures using pointers. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Arrays of Structures%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% An array of structures is a group of structures of the same type.%@AE@% %@NL@% %@NL@% Since it's rare for a company to have a single employee, a more practical version of the EMPLOYEE.C program would have an array of structures─one structure per employee. The concept may sound intimidating, but this is a common use of structures. %@NL@% %@NL@% The following statement declares a 50-element array named %@AS@% payroll%@AE@%, with each element a structure of the type %@AS@% employee %@AE@%: %@NL@% %@NL@% %@AS@% struct employee payroll[50];%@AE@%%@NL@% %@NL@% To specify members in such an array, you combine array notation and structure notation, giving the array name, a subscript, and a member name. For instance, the name %@NL@% %@NL@% %@AS@% payroll[0].months%@AE@%%@NL@% %@NL@% specifies the %@AS@% months %@AE@% member of the first structure in the %@AS@% payroll %@AE@% array. The first part of the name (%@AS@% payroll[0] %@AE@%) contains the array name and subscript that identify the structure. The second part (%@AS@% months %@AE@%) identifies the member within that structure. %@NL@% %@NL@% Figure 4.8 depicts the first three elements of the %@AS@% payroll %@AE@% array. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Once you grasp the basic idea, it's easy to imagine practical uses for an array of structures. Many programs, from an address book to a library card catalog, might use a structure to store different types of information about an individual item, then store many such structures in an array. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Structures of Structures%@AE@%%@EH@%%@NL@% %@NL@% As noted earlier, a structure can contain members of any data type─including other structures. So you can create a structure of structures: a structure whose members are structures. %@NL@% %@NL@% To illustrate, suppose you write a group of functions that draw various kinds of graphic windows and message boxes. You could define a small structure something like the following: %@NL@% %@NL@% %@AS@% struct title %@AS@% { %@AS@% char text[70]; /* Title text */ %@AS@% int color; /* Color of title text */ %@AS@% short justify; /* Left, center, or right */ %@AS@% };%@AE@%%@NL@% %@NL@% to aid in drawing titles. The %@AS@% title %@AE@% structure's three members specify the title's text, its color, and how its text is justified. %@NL@% %@NL@% Once the %@AS@% title %@AE@% structure is defined, you can make it part of other, larger structures that use titles. If you define a %@AS@% window %@AE@% structure type to draw windows, for example, that structure could include a %@AS@% title %@AE@% along with other structure members: %@NL@% %@NL@% %@AS@% struct window %@AS@% { %@AS@% struct title wintitle; /* Window title */ %@AS@% /* Other structure members go here... */ %@AS@% };%@AE@%%@NL@% %@NL@% In this structure type, the %@AS@% title %@AE@% member is named %@AS@% wintitle%@AE@%. %@NL@% %@NL@% You specify members of such structures using member-of operators and the appropriate names. If you create a variable of the %@AS@% window %@AE@% type named %@AS@% %@AS@%mywindow%@AE@%, the name %@NL@% %@NL@% %@AS@% mywindow.wintitle.color%@AE@%%@NL@% %@NL@% specifies the %@AS@% color %@AE@% member of the %@AS@% wintitle %@AE@% member of the %@AS@% mywindow %@AE@% structure. %@NL@% %@NL@% If you program using QuickC's Presentation Graphics library, you'll find it useful to understand the notation we just explained. Our fictitious %@AS@% title %@AE@% structure is a simplified version of the Presentation Graphics %@AB@%titletype%@AE@% structure type (see Chapter 14, "Presentation Graphics"). %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Bit Fields%@AE@%%@EH@%%@NL@% %@NL@% A "bit field" is a specialized structure that provides a way to manipulate individual bits or groups of bits. One use for this advanced feature is to access hardware addresses such as the computer's video memory. %@NL@% %@NL@% %@AU@% The members of a bit-field structure are groups of bits.%@AE@% %@NL@% %@NL@% You declare and use a bit-field structure much as you would any other structure. The difference is that every one of its members must be a bit or group of bits. You can't include other data types in a bit field. %@NL@% %@NL@% The following statement declares a bit-field structure type with the tag %@AS@% %@AS@%SCREEN%@AE@%: %@NL@% %@NL@% %@AS@% struct SCREEN %@AS@% { %@AS@% unsigned character : 8; %@AS@% unsigned fgcolor : 3; %@AS@% unsigned intensity : 1; %@AS@% unsigned bgcolor : 3; %@AS@% unsigned blink : 1; %@AS@% } screenbuf[25][80];%@AE@%%@NL@% %@NL@% The colons in the declaration tell QuickC these are bit fields rather than normal structure members. The number following each colon tells how many bits the field contains. In the %@AS@% SCREEN %@AE@% type the %@AS@% character %@AE@% member has 8 bits, %@AS@%intensity %@AE@% has 1 bit, and so on. Figure 4.9 illustrates the %@AS@% SCREEN %@AE@% type. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Figure 4.10 illustrates memory allocation for the %@AS@% SCREEN %@AE@% type. The members of the %@AS@% SCREEN %@AE@% type mirror the arrangement of bits in screen memory. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Take another look at the structure declaration. In addition to declaring a structure type, the statement declares a two-dimensional array variable %@AS@%screenbuf%@AE@%, of the same structure type. You could use this array as an alternate video buffer. Many graphics programs use a similar arrangement to switch between an alternate video buffer and the computer's video memory. %@NL@% %@NL@% The five members of the %@AS@% SCREEN %@AE@% type happen to take up a full %@AB@%int%@AE@% (two bytes, on DOS machines). A bit field need not fill up a byte or %@AB@%int%@AE@%; the bit field can contain as many bits as you need up to the maximum number of bits for the field's %@NL@% %@NL@% base type. The base type for each field in the example is %@AB@%unsigned%@AE@% (%@AB@%unsigned %@AB@%int%@AE@%), so each field can contain a maximum of 16 bits. %@NL@% %@NL@% The members of a bit-field structure are accessed with the structure-member operator─like other structure members. For instance, the name %@NL@% %@NL@% %@AS@% screenbuf[13][53].blink = 1;%@AE@%%@NL@% %@NL@% specifies the %@AS@% blink %@AE@% member of element 13, 53 of the %@AS@% screenbuf %@AE@% array. %@NL@% %@NL@% The range of values you can assign to a bit-field member depends on the member's size. Since the %@AS@% blink %@AE@% member of the %@AS@% SCREEN %@AE@% type contains one bit, %@AS@% blink %@AE@% is limited to the value 0 or 1. The %@AS@% fgcolor %@AE@% member contains three bits and can have any value from 0-7. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00040009 @%%@AB@%Unions%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A union is a group of variables of different types that share storage %@AU@%space.%@AE@% %@NL@% %@NL@% A union is a variable that can hold any one of several data types at different times, using the same storage space. Unions are a rather advanced feature. One use of them is to access DOS registers, which you may sometimes need to access as bytes and at other times as words. %@NL@% %@NL@% As with a structure, you must start by declaring a union type to tell the compiler the number and types of the union's members. You include one of each type that you expect to use. %@NL@% %@NL@% The following code creates a union that can hold a %@AB@%char%@AE@%, %@AB@%int%@AE@%, or %@AB@%long%@AE@% value. It declares a union type with the tag %@AS@% u_sample %@AE@% and declares a variable of that type named %@AS@% example%@AE@%. %@NL@% %@NL@% %@AS@% union u_sample %@AS@% { %@AS@% char c_val; %@AS@% int i_val; %@AS@% long l_val; %@AS@% } example;%@AE@%%@NL@% %@NL@% When you declare a union, QuickC allocates as much storage as the largest data type in the union requires. Since the largest type in %@AS@% u_sample%@AE@% is %@AB@%long%@AE@%, this union contains four bytes. %@NL@% %@NL@% The elements of a union are called members and use the same notation as structure members. Thus, the members of the %@AS@% example %@AE@% union are named %@NL@% %@NL@% %@AS@% example.c_val %@AS@% example.i_val %@AS@% example.l_val%@AE@%%@NL@% %@NL@% The contents of a union depend on how you access it. For instance, the statement %@NL@% %@NL@% %@AS@% example.c_val = '\0';%@AE@%%@NL@% %@NL@% stores a %@AB@%char%@AE@% value in the %@AS@% example %@AE@% union. Since a %@AB@%char%@AE@% value takes one byte, the statement uses only one byte of the space in %@AS@% example%@AE@%. The statement %@NL@% %@NL@% %@AS@% example.i_val = 77;%@AE@%%@NL@% %@NL@% uses two bytes of the union, because an %@AB@%int%@AE@% value requires two bytes of storage. Likewise, the statement %@NL@% %@NL@% %@AS@% example.l_val = 75621;%@AE@%%@NL@% %@NL@% stores %@AB@%long%@AE@% value in %@AS@% example%@AE@%, taking up all four bytes of its storage space. Figure 4.11 shows memory allocation for the three members in the %@AS@% %@AS@%example %@AE@% union. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% It's your job to keep track of what is stored in a union. If you store a %@AB@%long%@AE@% value in %@AS@% example %@AE@% and mistakenly treat that value as a %@AB@%char%@AE@% value later, the result may be nonsense. It's especially important not to confuse integer and floating-point types, which are stored in different internal formats. %@NL@% %@NL@% Now that you're familiar with the data types that C offers, you are ready to tackle more advanced data-handling concepts. The next chapter discusses several of these. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00050001 @%%@1@%%@AB@%Chapter 5 Advanced Data Types%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% In Chapter 4, "Data Types," we described the basic C data types and showed how to declare and use different kinds of variables. This chapter examines more advanced data topics, including the visibility and lifetime of variables and the conversion of values from one data type to another. %@NL@% %@NL@% If you know QuickPascal or QuickBASIC, some of these topics, such as visibility, should be familiar. For example, a variable declared within a function is visible (accessible) only in that function. One area in which C differs notably from QuickPascal is type conversion. The C language gives programmers the freedom to convert a value from one type to another type, whereas QuickPascal does not. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00050002 @%%@AB@%Visibility%@AE@%%@EH@%%@NL@% %@NL@% Every variable in a C program has a definite "visibility" that determines which parts of the program can "see," or access, the variable. Another term for visibility is "scope." %@NL@% %@NL@% As we mentioned in Chapter 1, "Anatomy of a C Program," there are two basic kinds of visibility: local and external. A "local" variable─one declared within a function─is visible only within that function. An "external" variable─one declared outside all functions─is visible to all functions that follow it in the program. %@NL@% %@NL@% This section begins by describing local and external visibility, then goes on to discuss visibility in multiple-file programs and the visibility of functions. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%While the examples in this section use simple %@AB@%int%@AE@%%@AI@% variables, visibility %@AI@%rules apply equally to aggregate types such as arrays and structures.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@AU@% Use external variables only when necessary.%@AE@% %@NL@% %@NL@% C programmers normally limit the visibility of each variable to those parts of the program that need to access the variable. For instance, if a variable is needed only within one function, it should always be local to that function. By restricting a variable's visibility, you can prevent other parts of the program from accidentally changing the variable's value. Such haphazard side effects were common in older interpreted BASIC programs, in which every variable had unlimited visibility. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00050003 @%%@AB@%Local Variables%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Variables declared within a function are local to that function.%@AE@% %@NL@% %@NL@% As we noted in Chapter 1, "Anatomy of a C Program," and Chapter 2, "Functions," the place where you declare a variable controls where the variable is visible. Declaring a variable within a function makes the variable local to that function; the variable can be seen only within the function. %@NL@% %@NL@% The VISIBLE.C program below demonstrates local visibility. It contains a function named %@AS@% be_bop %@AE@% that tries to print the value of the local variable %@AS@% %@AS@%val%@AE@%. %@NL@% %@NL@% %@AS@% /* VISIBLE.C: Demonstrate local visibility. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% void be_bop( void ); %@AS@% %@AS@% main() %@AS@% { %@AS@% int val = 10; %@AS@% be_bop(); %@AS@% } %@AS@% %@AS@% void be_bop( void ) %@AS@% { %@AS@% printf( "val = %d", val ); /* Error! */ %@AS@% }%@AE@%%@NL@% %@NL@% Notice where the %@AS@% val %@AE@% variable is declared. The declaration %@NL@% %@NL@% %@AS@% int val = 10;%@AE@%%@NL@% %@NL@% occurs within the %@AB@%main%@AE@% function, so %@AS@% val %@AE@% is local to %@AB@%main%@AE@%. When you compile VISIBLE.C, QuickC stops, providing this error message: %@NL@% %@NL@% %@AS@% C2065: 'val' : undefined%@AE@%%@NL@% %@NL@% What happened? The %@AB@%printf%@AE@% statement in the %@AS@% be_bop %@AE@% function %@NL@% %@NL@% %@AS@% printf( "val = %d", val ); /* Error! */%@AE@%%@NL@% %@NL@% can't "see" the variable %@AS@% val%@AE@%, which is declared locally within %@AB@%main%@AE@%. Outside the %@AB@%main%@AE@% function, in which %@AS@% val %@AE@% is declared, the variable doesn't exist. %@NL@% %@NL@% You could eliminate the error message by declaring %@AS@% val %@AE@% externally, but most programmers would avoid that solution. If a variable has external visibility, any part of the program might change its value accidentally. A better solution is to pass the value of %@AS@% val %@AE@% to %@AS@% be_bop %@AE@% as a function argument, as shown in the program VISIBLE1.C below. %@NL@% %@NL@% %@AS@% /* VISIBLE1.C: Demonstrate local visibility. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% void be_bop( int param ); %@AS@% %@AS@% main() %@AS@% { %@AS@% int val = 10; %@AS@% be_bop( val ); %@AS@% } %@AS@% %@AS@% void be_bop( int param ) %@AS@% { %@AS@% printf( "%d\n", param ); %@AS@% }%@AE@%%@NL@% %@NL@% The VISIBLE1.C program is identical to VISIBLE.C except for two changes. The %@AS@% be_bop %@AE@% function now can accept an argument, and the statement that calls %@AS@%be_bop %@AE@% passes the value of %@AS@% val %@AE@% as an argument. These changes allow the %@AS@% %@AS@%be_bop %@AE@% function to print the value of %@AS@% val %@AE@% without the drawback of making %@AS@% %@AS@%val %@AE@% external. %@NL@% %@NL@% Most local variables are declared at the beginning of the function and are visible throughout the function. If you declare the variable later in the function, it is visible only to statements that follow the declaration. %@NL@% %@NL@% The reason for this rule is simple: QuickC, like all language compilers, reads your program line by line, from beginning to end. Until the compiler sees the variable's declaration, it must treat the variable as undefined. This rule applies to all variables, including external variables, as we'll see in the next section. %@NL@% %@NL@% Although the practice isn't common, you can restrict a local variable's visibility even further by declaring it in a statement block inside a function. For instance, you might declare a variable within the body of the loop or conditional statement. In fact, any pair of curly braces limits the visibility of a variable declared within that pair. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00050004 @%%@AB@%External Variables%@AE@%%@EH@%%@NL@% %@NL@% If you declare a variable outside all functions, the variable has external visibility; every function that follows the declaration can see the variable. External variables are called "global" in some other languages. %@NL@% %@NL@% Experienced C programmers use external variables only when necessary─for instance, when two or more functions need the ability to change the same variable or communicate with each other by changing a variable. Even in those cases, however, you may be able to avoid the dangers of external visibility by passing a pointer to the variable as a function argument. See the section "Passing Pointers to Functions" in Chapter 8 ("Pointers") for more information. %@NL@% %@NL@% Most external variables are declared near the beginning of the program, before any function definitions. In this way, you can make the variable visible to every function in the program. You could do this in VISIBLE1.C by placing the declaration of %@AS@% val%@AE@%, %@NL@% %@NL@% %@AS@% int val = 10;%@AE@%%@NL@% %@NL@% immediately before the %@AB@%main%@AE@% function. %@NL@% %@NL@% If you declare the variable %@AS@% val %@AE@% later in the program, it is not visible to functions that precede the declaration. The VISIBLE2.C program below demonstrates this principle. %@NL@% %@NL@% %@AS@% /* VISIBLE2.C: Demonstrate external visibility. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% void be_bop( int param ); %@AS@% %@AS@% main() %@AS@% { %@AS@% be_bop( val ); /* Error! */ %@AS@% } %@AS@% %@AS@% int val = 10; %@AS@% %@AS@% void be_bop( int param ) %@AS@% { %@AS@% printf( "val = %d\n", param ); %@AS@% }%@AE@%%@NL@% %@NL@% The VISIBLE2.C program is identical to VISIBLE1.C except that %@AS@% val %@AE@% is declared externally %@NL@% %@NL@% %@AS@% int val = 10;%@AE@%%@NL@% %@NL@% following the %@AB@%main%@AE@% function, rather than locally within %@AB@%main%@AE@%. %@NL@% %@NL@% Because the declaration occurs outside all functions, the variable is external. However, because the declaration follows the %@AB@%main%@AE@% function, the variable is not visible within %@AB@%main%@AE@%. When the %@AB@%printf%@AE@% statement in the %@AB@%main%@AE@% function refers to %@AS@% val%@AE@%, QuickC issues the error message: %@NL@% %@NL@% %@AS@% C2065: 'val' : undefined%@AE@%%@NL@% %@NL@% Remember, QuickC reads the program line by line, from start to finish. Since the compiler knows nothing about %@AS@% val %@AE@% when it reaches the reference in %@AB@%main%@AE@%, it must treat %@AS@% val %@AE@% as undefined. In this program, only the %@AS@% be_bop %@AE@% function can refer to %@AS@% val%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00050005 @%%@AB@%Visibility in Multiple Source Files%@AE@%%@EH@%%@NL@% %@NL@% A "source file" is the file containing your program's text. Source files normally have the .C file extension, to distinguish them from other files such as executable (.EXE) files. %@NL@% %@NL@% Simple programs have only one source file, but large programs are often split into several source files. If you write a word-processing program, for instance, you might place all the program's screen-output functions in one file, all the file-handling functions in a second file, and so forth. %@NL@% %@NL@% %@AU@% Use the extern keyword to make an external variable visible in more than %@AU@%one source file.%@AE@% %@NL@% %@NL@% Normally, an external variable is visible only in the source file in which it is declared. In a multi-file program, however, a function in one file might need to access a variable in a second file. To make the variable visible in more than one source file, you must declare it with the %@AB@%extern%@AE@% keyword. %@NL@% %@NL@% Let's look at a short two-file program that shows how to use %@AB@%extern%@AE@%. The first source file, FILE1.C, declares two external variables, %@AS@% chico %@AE@% and %@AS@% %@AS@%harpo%@AE@%. The file contains one function (%@AB@%main%@AE@%) that calls a second function named %@AS@% yonder%@AE@%. %@NL@% %@NL@% %@AS@% /* FILE1.C: Visibility in multiple source files. */ %@AS@% %@AS@% int chico = 20, harpo = 30; %@AS@% extern void yonder( void ); %@AS@% %@AS@% main() %@AS@% { %@AS@% yonder(); %@AS@% }%@AE@%%@NL@% %@NL@% The second source file, FILE2.C, contains the %@AS@% yonder %@AE@% function that is called in FILE1.C. This file also declares the variables %@AS@% chico %@AE@% and %@AS@% harpo, %@AS@%%@AE@% but it prefaces their declarations with %@AB@%extern%@AE@% to show that the variables are defined externally in some other file. Once this is done, any function in FILE2.C can refer to %@AS@% chico %@AE@% and %@AS@% harpo %@AE@% as if they are defined in the same file. %@NL@% %@NL@% %@AS@% /* FILE2.C: Visibility in multiple source files. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% void yonder( void ) %@AS@% { %@AS@% extern int chico, harpo; %@AS@% printf( "chico = %d, harpo = %d\n", chico, harpo ); %@AS@% }%@AE@%%@NL@% %@NL@% You can compile this program in one of two ways. In the QuickC environment, choose Set Program List from the Make menu and add FILE1.C and FILE2.C to the list. Then choose Build Program from the Make menu. %@NL@% %@NL@% You can also enter this command from the DOS command line: %@NL@% %@NL@% %@AS@% qcl FILE1.C FILE2.C%@AE@%%@NL@% %@NL@% In either case, the executable file is named FILE1.EXE. The program's output, %@NL@% %@NL@% %@AS@% chico = 20, harpo = 30%@AE@%%@NL@% %@NL@% shows that the %@AS@% yonder %@AE@% function in FILE2.C can access the variables defined in FILE1.C. %@NL@% %@NL@% Sometimes you may want an external variable to be visible only in the source file where it's declared. The variable can be shared by functions in one file, but it is hidden to all other files, thus minimizing the risk of naming conflicts. %@NL@% %@NL@% %@AU@% The static keyword can limit a variable's visibility to one source file.%@AE@% %@NL@% %@NL@% To limit a variable's visibility to one file, precede the variable's declaration with the keyword %@AB@%static%@AE@%. For example, if FILE1.C declared the %@AS@% %@AS@%harpo %@AE@% variable as %@AB@%static%@AE@% in this manner, %@NL@% %@NL@% %@AS@% static int harpo;%@AE@%%@NL@% %@NL@% it would prevent FILE2.C from accessing %@AS@% harpo %@AE@% at all, even though FILE2.C declares (with %@AB@%extern%@AE@%) that %@AS@% harpo %@AE@% is defined somewhere else. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00050006 @%%@AB@%Visibility of Functions%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Functions are normally visible in multiple source files.%@AE@% %@NL@% %@NL@% Unlike variables, functions are external by default. That is, they are normally visible to every file in a multi-file program. You'll notice that in FILE1.C we declared the %@AS@% yonder %@AE@% function with the %@AB@%extern%@AE@% keyword. We did this merely to improve readability; the keyword shows clearly that the function is defined in some other file. If we removed the %@AB@%extern%@AE@% from the declaration of %@AS@% yonder %@AE@% in FILE1.C, the program would work just as well as before. %@NL@% %@NL@% At times you may want to restrict the visibility of a function in a multi-file program, making it visible in some files but not in others. By "hiding" a function from other parts of a program, you can reduce the danger of naming conflicts. For instance, if you write a library of functions to sell commercially, you probably would hide all of the library's local function names, to prevent conflicts with function names your customers might create. %@NL@% %@NL@% %@AU@% The static keyword can limit a function's visibility.%@AE@% %@NL@% %@NL@% As with external variables, you limit a function's visibility using the %@AB@%static%@AE@% keyword. A function declared as %@AB@%static%@AE@% is visible only in the source file that declares it. If we add %@AB@%static%@AE@% to the header of the %@AS@% yonder %@AE@% function, for example, %@NL@% %@NL@% %@AS@% static void yonder( void )%@AE@%%@NL@% %@NL@% the function could no longer be called from the FILE1.C file. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00050007 @%%@AB@%Lifetime%@AE@%%@EH@%%@NL@% %@NL@% In addition to visibility, every variable also has a certain "lifetime"─that is, the period during the program's execution when the variable exists. %@NL@% %@NL@% External variables exist for the life of the program. Memory is allocated for them when the program begins and remains until the program ends. %@NL@% %@NL@% %@AU@% An automatic variable disappears when the function ends.%@AE@% %@NL@% %@NL@% Local variables have shorter lifetimes. They come into being when the function begins and disappear when the function ends. For this reason, a local variable is said to be "automatic." The variable comes and goes automatically, each time the function is called. %@NL@% %@NL@% Automatic variables conserve memory in a couple of ways. First, since they evaporate when the function ends, automatic variables don't consume memory when not in use. Second, they are stored in the "stack" memory area, which the program allocates at run time. So, automatic variables don't enlarge the executable program. %@NL@% %@NL@% The C language provides the %@AB@%auto%@AE@% keyword for declaring automatic variables. However, this keyword is seldom used, since all local variables are automatic unless you specify otherwise. In the following function, both %@AS@% val %@AS@%%@AE@% and %@AS@% example %@AE@% are automatic variables: %@NL@% %@NL@% %@AS@% void sample( void ) %@AS@% { %@AS@% int val; %@AS@% auto int example; %@AS@% }%@AE@%%@NL@% %@NL@% The %@AB@%auto%@AE@% preceding the declaration of %@AS@% example %@AE@% has no practical effect. The variable %@AS@% example %@AE@% is automatic even if you remove the %@AB@%auto%@AE@% from its declaration. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00050008 @%%@AB@%Extending the Lives of Local Variables%@AE@%%@EH@%%@NL@% %@NL@% Occasionally, you may want a local variable to retain its value between function calls. The %@AB@%static%@AE@% keyword, introduced earlier as a means of limiting the visibility of external variables, also performs this task. %@NL@% %@NL@% %@AU@% A static local variable retains its value through subsequent function %@AU@%calls.%@AE@% %@NL@% %@NL@% If you precede a local variable declaration with %@AB@%static%@AE@%, the variable exists for the life of the program─the same lifetime as an external variable. The variable still has local visibility, however. %@NL@% %@NL@% The STATIC.C program below shows how to create and use a %@AB@%static%@AE@% local variable. In STATIC.C, the value of the %@AS@% methuselah %@AE@% variable persists through all calls to the %@AS@% add_val %@AE@% function, which adds values to %@AS@% %@AS@%methuselah %@AE@% and prints the variable's value. %@NL@% %@NL@% %@AS@% /* STATIC.C: Demonstrate static variables. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% void add_val( int value ); %@AS@% %@AS@% main() %@AS@% { %@AS@% add_val( 1 ); %@AS@% add_val( 5 ); %@AS@% add_val( 20 ); %@AS@% }%@AE@%%@NL@% %@NL@% %@AS@% void add_val( int value ) %@AS@% { %@AS@% static int methuselah; %@AS@% if( value == 1 ) %@AS@% methuselah = 0; %@AS@% methuselah = methuselah + value; %@AS@% printf( "methuselah = %d\n", methuselah ); %@AS@% }%@AE@%%@NL@% %@NL@% The %@AS@% add_val %@AE@% function in STATIC.C accepts one parameter and also declares a %@AB@%static%@AE@% local variable named %@AS@% methuselah%@AE@%. Each time %@AS@% add_val %@AE@% is called, it adds the passed value to %@AS@% methuselah%@AE@%. %@NL@% %@NL@% The %@AB@%main%@AE@% function calls the %@AS@% add_val %@AE@% function three times, passing the values 1, 5, and 20 to %@AS@% add_val %@AE@% as arguments. The program's output %@NL@% %@NL@% %@AS@% methuselah = 1 %@AS@% methuselah = 6 %@AS@% methuselah = 26%@AE@%%@NL@% %@NL@% shows that the value of %@AS@% methuselah %@AE@% persists through all three function calls. %@NL@% %@NL@% If we remove the %@AB@%static%@AE@% keyword from the declaration of %@AS@% methuselah%@AE@%, the variable's value is not preserved between function calls. The value of %@AS@% %@AS@%methuselah %@AE@% is unpredictable the second and third times that %@AS@% add_val %@AE@% is called. %@NL@% %@NL@% Notice that extending a local variable's lifetime with %@AB@%static%@AE@% doesn't affect its visibility. The %@AS@% methuselah %@AE@% variable keeps its value between function calls, but you can't refer to the variable outside the %@AS@% add_val %@AE@% function. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00050009 @%%@AB@%Converting Data Types%@AE@%%@EH@%%@NL@% %@NL@% It's usually best to avoid mixing data items of different types in the same expression. You wouldn't normally add a character variable to a floating-point variable, for instance. Some languages, such as QuickPascal, generally treat type mixing as an error. However, the C language gives you the freedom to mix data types when necessary. %@NL@% %@NL@% For example, since the %@AB@%char%@AE@% and %@AB@%int%@AE@% types both can store whole numbers, there may be times when you have a good reason to add a %@AB@%char%@AE@% value to an %@AB@%int%@AE@% value. When you mix types, QuickC does not issue an error message. Instead, the compiler converts both data items to the same type and then performs the requested operation. %@NL@% %@NL@% Type conversion can occur in one of two ways. The first way occurs automatically when you combine different types in an expression. You can also use special syntax to intentionally "cast" (convert) one type to another. We'll discuss both methods in the following sections. %@NL@% %@NL@% Knowing how C converts types will help you to find bugs that result from unintended type clashes and to minimize errors when you deliberately mix types. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00050010 @%%@AB@%Ranking of Data Types%@AE@%%@EH@%%@NL@% %@NL@% For purposes of conversion, the C language ranks data types in the order shown in Figure 5.1. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% The ranking illustrated in Figure 5.1 generally reflects the amount of storage that each type requires. As you may remember from Chapter 4, "Data Types," larger data types require more storage than smaller types. Thus, an %@AB@%int%@AE@%, which requires two bytes of storage, outranks a %@AB@%char%@AE@%, which requires one byte. %@NL@% %@NL@% Within this ranking, an %@AB@%unsigned%@AE@% type outranks the corresponding %@AB@%signed%@AE@% type. An %@AB@%unsigned char%@AE@% value is of higher rank than a %@AB@%signed char%@AE@%, and so forth. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00050011 @%%@AB@%Promotions and Demotions%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A promotion is usually harmless.%@AE@% %@NL@% %@NL@% A type conversion always involves two data items of different types. Whenever possible, QuickC converts the lower-ranking (smaller) data item to the higher-ranking (larger) type. This kind of conversion, called a "promotion," is normally harmless. For example, since a two-byte %@AB@%int%@AE@% has more than enough room to store a one-byte %@AB@%char%@AE@%, it's generally safe to promote a %@AB@%char%@AE@% value to an %@AB@%int%@AE@%. %@NL@% %@NL@% %@AU@% A demotion usually causes a loss of data.%@AE@% %@NL@% %@NL@% Sometimes, the compiler is forced to convert a higher-ranking value to a lower-ranking type. This kind of conversion, called a "demotion," usually causes loss of data. For example, the %@AB@%int%@AE@% value 32,000 is much too large to be stored in a %@AB@%char%@AE@% type, which can't hold a number larger than 255. If you assign the value 32,000 to a %@AB@%char%@AE@% variable, some data must be lost. %@NL@% %@NL@% A demotion of an integer type truncates the higher-ranking type, throwing away the data from high-order bytes that can't fit in the smaller-ranking value. Some demotions of floating-point types round off a value rather than truncate it. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00050012 @%%@AB@%Automatic Type Conversions%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% C does an automatic type conversion when you mix different data types.%@AE@% %@NL@% %@NL@% When a program statement mixes two different data types, QuickC performs an automatic type conversion. The following code, for instance, adds the %@AB@%char%@AE@% variable %@AS@% a %@AE@% to the %@AB@%int%@AE@% variable %@AS@% b%@AE@%. %@NL@% %@NL@% %@AS@% char a = 5; %@AS@% int b = 32000; %@AS@% b = a + b;%@AE@%%@NL@% %@NL@% In the statement %@NL@% %@NL@% %@AS@% b = a + b;%@AE@%%@NL@% %@NL@% the addition operation to the right of the equal sign triggers an automatic type conversion. QuickC promotes the %@AB@%char%@AE@% value to an %@AB@%int%@AE@% and then adds the two %@AB@%int%@AE@% values. %@NL@% %@NL@% If you're not sure whether QuickC is doing an automatic type conversion, set Warning Level 2 or higher in the Compiler Flags dialog box. The compiler generates the warning message %@NL@% %@NL@% %@AS@% C4051: data conversion%@AE@%%@NL@% %@NL@% whenever an automatic conversion occurs. This monitoring helps you readily identify unwanted conversions. %@NL@% %@NL@% If you carelessly mix different types, you may create subtle errors. The CONVERT.C program below has a deliberate error that shows what can happen when types are mixed. It adds four variables and assigns their sum to a fifth variable, causing three promotions and one demotion. %@NL@% %@NL@% %@AS@% /* CONVERT.C: Demonstrate type conversions. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% char c_val = 10; %@AS@% int i_val = 20; %@AS@% long l_val = 64000; %@AS@% float f_val = 3.1; %@AS@% int result; %@AS@% %@AS@% result = c_val + i_val + l_val + f_val; /* Error! */ %@AS@% %@AS@% printf( "%d\n", result ); %@AS@% }%@AE@%%@NL@% %@NL@% The CONVERT.C program adds the numbers 10, 20, 64000, and 3.1. Instead of the correct result, 64033.10, the program prints %@NL@% %@NL@% %@AS@% -1503%@AE@%%@NL@% %@NL@% Something definitely went wrong. The problem lies somewhere in the line %@NL@% %@NL@% %@AS@% result = c_val + i_val + l_val + f_val;%@AE@%%@NL@% %@NL@% which triggers four automatic type conversions. We'll examine the conversions in order. %@NL@% %@NL@% The first conversion occurs when the %@AB@%char%@AE@% variable %@AS@% c_val %@AE@% is added to the %@AB@%int%@AE@% variable %@AS@% i_val%@AE@%: %@NL@% %@NL@% %@AS@% c_val + i_val%@AE@%%@NL@% %@NL@% Since the variables are different types, QuickC automatically converts the lower-ranking %@AB@%char%@AE@% value to the higher-ranking %@AB@%int%@AE@% type before adding them. This promotion doesn't create any problems, since there's more than enough room to store the one-byte %@AB@%char%@AE@% value in the two-byte %@AB@%int%@AE@%. The sum of this addition is 30, another %@AB@%int%@AE@% value. %@NL@% %@NL@% The next operation adds that partial sum to the %@AB@%long%@AE@% value of %@AS@% l_val %@AE@% (to make the expression easier to read, we'll show the sum from the previous addition): %@NL@% %@NL@% %@AS@% 30 + l_val%@AE@%%@NL@% %@NL@% This addition triggers another promotion. The compiler promotes the %@AB@%int%@AE@% result of the first addition to a %@AB@%long%@AE@% value before adding it to %@AS@% l_val%@AE@%, which is %@AB@%long%@AE@%. Since the four-byte %@AB@%long%@AE@% type has more than enough room to store a two-byte %@AB@%int%@AE@%, this promotion is also harmless. %@NL@% %@NL@% Now the partial sum equals 64030. The last addition from CONVERT.C %@NL@% %@NL@% %@AS@% 64030 + f_val%@AE@%%@NL@% %@NL@% triggers another harmless conversion: the compiler converts the %@AB@%long%@AE@% result of the previous addition to a %@AB@%float%@AE@% value before adding it to %@AS@% f_val%@AE@%. Even though floating-point and integer values are stored in different internal formats, no data is lost when the %@AB@%long%@AE@% is converted to a %@AB@%float%@AE@%. %@NL@% %@NL@% The result of these additions and conversions is the %@AB@%float%@AE@% value 64033.10, which is correct. So where does the mistake occur? %@NL@% %@NL@% The problem arises when CONVERT.C assigns the final sum to the wrong type of variable. You'll recall that the line containing these operations begins with the assignment%@AS@% result =%@AE@%. %@NL@% %@NL@% Earlier in the program, we declared the variable %@AS@% result %@AE@% as an %@AB@%int%@AE@%. The twobyte %@AB@%int%@AE@% variable created to store the result of these additions is too small to contain the four-byte %@AB@%float%@AE@% sum that was finally produced. %@NL@% %@NL@% The assignment forces QuickC to demote the larger %@AB@%float%@AE@% value to the smaller %@AB@%int%@AE@% type. It's impossible to store such a large floating-point value in the two bytes of an %@AB@%int%@AE@%, so the final result is incorrect. %@NL@% %@NL@% Figure 5.2 shows the progression of automatic type conversions that the CONVERT.C program produces. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% We can fix the conversion error by declaring the variable %@AS@% result %@AE@% as a %@AB@%float%@AE@%, substituting %@NL@% %@NL@% %@AS@% float result;%@AE@%%@NL@% %@NL@% for the earlier declaration. We'll also need to change the format string in the %@AB@%printf%@AE@% function call to print a %@AB@%float%@AE@% value, as shown below: %@NL@% %@NL@% %@AS@% printf( "%6.2f\n", result );%@AE@%%@NL@% %@NL@% Now CONVERT.C prints the expected value of 64033.10. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00050013 @%%@AB@%Manual Type Conversions through Casting%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A cast forces a value to a particular type.%@AE@% %@NL@% %@NL@% The C language also allows you to force a type conversion that would not otherwise happen, a process known as "casting." Using casts, it is possible to convert a data item to any C data type. %@NL@% %@NL@% Sometimes you must use a cast to make the program work properly. When calling the %@AB@%malloc%@AE@% library function, for instance, you should perform a cast on the value that the function returns. (Chapter 12, "Dynamic Memory Allocation," explains %@AB@%malloc%@AE@% and other memory-allocating functions.) %@NL@% %@NL@% Casts can also make a program more readable. QuickC does most automatic type conversions silently. So if you write a tricky bit of code that relies on automatic conversions, you, or some other programmer, may not notice the conversions later. To make such code more readable─and easier to debug─you can add explicit type casts in places where silent conversions might go unnoticed. %@NL@% %@NL@% To cast a value to a different type, place the desired type name in parentheses in front of the value. For instance, the statement %@NL@% %@NL@% %@AS@% f_val = (float)any_val;%@AE@%%@NL@% %@NL@% casts the value of the variable %@AS@% any_val %@AE@% to type %@AB@%float%@AE@% before assigning it to %@AS@% f_val%@AE@%. Here the type name in parentheses, %@NL@% %@NL@% %@AS@% (float)%@AE@%%@NL@% %@NL@% performs the cast. No matter what type %@AS@% any_val %@AE@% has, the cast converts that type to %@AB@%float%@AE@% before assigning it to %@AS@% f_val%@AE@%. %@NL@% %@NL@% When you cast a variable, the cast affects the value the variable yields, but not the variable itself. Suppose that %@AS@% any_val %@AE@% is an %@AB@%int%@AE@% variable with the value 333. The above cast converts the value 333 to %@AB@%float%@AE@% format before assigning it to %@AS@% f_val%@AE@%. But %@AS@% any_val %@AE@% remains an %@AB@%int%@AE@% variable after the cast. %@NL@% %@NL@% Remember, you can detect automatic type conversions by setting Warning Level 2 or higher in QuickC and watching for the following warning: %@NL@% %@NL@% %@AS@% C4051: data conversion%@AE@%%@NL@% %@NL@% You can then add explicit casts to eliminate the warning where the conversions are desirable. (See "Automatic Type Conversions" above.) %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00050014 @%%@AB@%Register Variables%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Register variables are stored in processor registers instead of addressable %@AU@%memory.%@AE@% %@NL@% %@NL@% You can use the %@AB@%register%@AE@% keyword in variable declarations to request that a variable be stored in a processor register. Because processor registers can be accessed more quickly than addressable memory locations, this storage can make a program run faster. Programmers use %@AB@%register%@AE@% to speed access to heavily used variables, such as counter variables in loops. %@NL@% %@NL@% The %@AB@%register%@AE@% specifier is much less important than it used to be, now that most C compilers, including QuickC, can perform optimizations (improvements) during compilation. If you compile with the Optimizations option turned on, QuickC automatically stores variables in registers when needed. So you probably won't need to use %@AB@%register%@AE@% except in special cases. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% IMPORTANT %@AI@%If you compile with Optimizations on, an explicit %@AB@%register%@AE@%%@AI@% declaration can %@AI@%override register storage that QuickC would do automatically. Declaring one %@AI@%variable with %@AE@%%@AI@%%@AB@%register%@AE@%%@AE@%%@AI@% might prevent QuickC from storing some other variable %@AI@%in a register. In the worst case, this can make a program run slower.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% You can use %@AB@%register%@AE@% only with short integer types (%@AB@%char%@AE@%, %@AB@%int%@AE@%, and %@AB@%short %@AB@%int%@AE@%). Other types─including aggregate types such as arrays─are too large to fit in a register. %@NL@% %@NL@% Only two registers are available for variable storage at any given time. (They are DI and SI, for those who have programmed in assembly language.) If you request more registers than are available, QuickC stores the extra variables in addressable memory, as it does non-%@AB@%register%@AE@% variables. %@NL@% %@NL@% The following declaration uses %@AB@%register%@AE@% to ask the compiler to store the %@AB@%int%@AE@% variable %@AS@% val %@AE@% in a processor register: %@NL@% %@NL@% %@AS@% register int val;%@AE@%%@NL@% %@NL@% You can ask the compiler to store more than one variable in a register. For instance, the statement %@NL@% %@NL@% %@AS@% register int val, count;%@AE@%%@NL@% %@NL@% declares %@AS@% val %@AE@% and %@AS@% count %@AE@% as %@AB@%register%@AE@% variables. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%Since registers are not addressable, you can't use the address-of (%@AB@%&%@AE@%%@AI@%) %@AI@%operator to get the address of a variable declared with %@AE@%%@AI@%%@AB@%register%@AE@%%@AE@%%@AI@%. This rule %@AI@%applies whether or not QuickC is actually able to store the variable in a %@AI@%register. Thus, if you need to access a variable through a pointer, don't %@AI@%declare that variable with %@AE@%%@AI@%%@AB@%register%@AE@%%@AE@%%@AI@%. See the section "Initializing a Pointer %@AI@%Variable" in Chapter 8, "Pointers."%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00050015 @%%@AB@%Renaming Existing Types with typedef%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%typedef%@AE@% keyword creates a new name for an existing data type. This is a convenience feature that you can use to make programs more readable. For instance, the declaration %@NL@% %@NL@% %@AS@% typedef int integer;%@AE@%%@NL@% %@NL@% allows you to use %@AS@% integer %@AE@% as a synonym for %@AB@%int%@AE@%. %@NL@% %@NL@% One more practical use of %@AB@%typedef%@AE@% is to substitute a short, descriptive name for an aggregate type. For instance, the QuickC Presentation Graphics library uses %@AB@%typedef%@AE@% to create descriptive names such as %@AB@%windowtype%@AE@% and %@AB@%titletype%@AE@% for structures used in that library. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The %@AB@%typedef%@AE@%%@AI@% keyword doesn't create a new data type. It merely allows you to %@AI@%use a different name for a type that already exists.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% You can also use %@AB@%typedef%@AE@% to minimize portability problems. By using %@AB@%typedef%@AE@% declarations for data types that are machine dependent, you need only change the %@AB@%typedef%@AE@% declaration if you move the program to a different operating system. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00050016 @%%@AB@%The Enumeration Type%@AE@%%@EH@%%@NL@% %@NL@% The "enumeration type" specifies a set of named integer constants, similar to the enumerated type in QuickPascal. In the C language, enumeration types are declared with the %@AB@%enum%@AE@% keyword. %@NL@% %@NL@% %@AU@% Use enum to name a set of integer constants.%@AE@% %@NL@% %@NL@% The %@AB@%enum%@AE@% type is useful mainly for improving a program's readability. With %@AB@%enum%@AE@%, you can use meaningful names for a set of constants whose purpose might not otherwise be apparent. %@NL@% %@NL@% Suppose you're writing a calendar program in which the constant 0 represents Saturday, 1 represents Sunday, and so on. You might begin by declaring the enumeration type %@AS@% day %@AE@% in the following manner: %@NL@% %@NL@% %@AS@% enum day %@AS@% { %@AS@% saturday, sunday, monday, tuesday, %@AS@% wednesday, thursday, friday %@AS@% };%@AE@%%@NL@% %@NL@% Notice this declaration's similarity to a structure declaration. As with structures, the type declaration creates a template that you can use to declare variables of this type. (See the section "Declaring a Structure Type" in Chapter 4, "Data Types.") %@NL@% %@NL@% Unless you specify otherwise, the first value in an enumeration type equals 0 and others are numbered sequentially. In the %@AB@%enum%@AE@% type shown above, %@AS@% %@AS@%saturday %@AE@% equals 0, %@AS@% sunday %@AE@% equals 1, and so forth. %@NL@% %@NL@% The values in an enumeration type need not be sequential, however. If you want some other order, you can declare explicit values for each member of the type. The following declaration, for example, assigns the names %@AS@% zero%@AE@%, %@AS@% %@AS@%freeze%@AE@%, and %@AS@%boil %@AE@% to the constants 0, 32, and 220, respectively. %@NL@% %@NL@% %@AS@% enum temps %@AS@% { %@AS@% zero = 0, %@AS@% freeze = 32, %@AS@% boil = 220 %@AS@% };%@AE@%%@NL@% %@NL@% After declaring an enumeration type, you can create a variable of that type and assign it a value from the type. The statement %@NL@% %@NL@% %@AS@% enum day today = wednesday;%@AE@%%@NL@% %@NL@% declares the variable %@AS@% today%@AE@%, assigning it the value %@AS@% wednesday %@AE@% from the %@AS@% %@AS@%day %@AE@% enumeration type. %@NL@% %@NL@% After you assign its value, you can use the variable %@AS@% today %@AE@% as you would an %@AB@%int%@AE@% variable. Although the variable is considered to have the %@AB@%enum%@AE@% type, it is an ordinary %@AB@%int%@AE@% for all practical purposes. %@NL@% %@NL@% Enumeration types aren't used very often, partly because you can achieve a similar effect using the %@AB@%#define%@AE@% directive. (Chapter 7, "Preprocessor Directives," explains %@AB@%#define%@AE@% in detail.) For example, the code %@NL@% %@NL@% %@AS@% #define SATURDAY 0 %@AS@% #define SUNDAY 1 %@AS@% #define MONDAY 2 %@AS@% #define TUESDAY 3 %@AS@% #define WEDNESDAY 4 %@AS@% . %@AS@% . %@AS@% . %@AS@% int today = WEDNESDAY;%@AE@%%@NL@% %@NL@% uses %@AB@%#define%@AE@% to create symbolic constants named %@AS@% SATURDAY%@AE@%, %@AS@% SUNDAY%@AE@%, %@AS@% MONDAY%@AE@%, %@AS@% TUESDAY%@AE@%, and %@AS@% WEDNESDAY%@AE@%, assigning them the values 0 through 4. The last line in the example creates the %@AB@%int%@AE@% variable %@AS@% today %@AE@% and assigns it the value of %@AS@% WEDNESDAY%@AE@%. The result is identical to the statement shown earlier: %@NL@% %@NL@% %@AS@% enum day today = wednesday;%@AE@%%@NL@% %@NL@% One advantage of using %@AB@%enum%@AE@% over %@AB@%#define%@AE@% directives is that it groups related names in one place and can be more compact than a long series of directives. %@NL@% %@NL@% This concludes our main discussion of data types. The next chapter, "Operators," examines the C language's rich set of operators, which allow you to manipulate data in many different ways. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00060001 @%%@1@%%@AB@%Chapter 6 Operators%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% Compared with other languages, C is very compact, using fewer than 50 keywords. One reason C can get by with so few reserved words is its abundance of powerful operators─well over 30. %@NL@% %@NL@% Most C operators are easy to understand and remember. Even if you have never seen a C program, you probably understand that the statement %@NL@% %@NL@% %@AS@% val = val * 5;%@AE@%%@NL@% %@NL@% multiplies the variable %@AS@% val %@AE@% by 5 and assigns the result to %@AS@% val%@AE@%. %@NL@% %@NL@% Because the printable ASCII character set has only so many unique symbols, C uses some ASCII symbols in more than one operator. For instance, the asterisk (%@AB@%*%@AE@%) performs either a multiplication or pointer operation, depending on context. Similarly, the ampersand (%@AB@%&%@AE@%) is part of three C operators. Depending on context, the ampersand can obtain an address or perform a logical or bitwise AND operation. Be careful not to confuse operators that look similar but do different jobs. %@NL@% %@NL@% This chapter describes the C operators, beginning with those that are common to most languages, and then discussing those unique to C. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00060002 @%%@AB@%Introducing C's Operators%@AE@%%@EH@%%@NL@% %@NL@% We'll start by discussing C operators that look and behave similarly to operators in other languages. These include the following groups: %@NL@% %@NL@% %@NL@% ■ Arithmetic operators, which do operations such as addition and multiplication%@NL@% %@NL@% ■ Relational operators, which compare two values and give a true or false result%@NL@% %@NL@% ■ Assignment operators, which make one value equal to another%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060003 @%%@AB@%Arithmetic Operators%@AE@%%@EH@%%@NL@% %@NL@% The C language's arithmetic operators closely resemble those in other languages. Table 6.1 lists C's arithmetic operators. %@NL@% %@NL@% %@AB@%Table 6.1 %@AB@%Arithmetic Operators%@AE@%%@AE@% %@TH: 8 511 02 26 50 @%Operator Description%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%*%@AE@% Multiplication%@AB@%/%@AE@% Division%@AB@%%%@AE@% Modulus%@AB@%+%@AE@% Addition%@AB@%- %@AE@% Subtraction%@AB@%%@AE@%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 8 511 02 26 50 @% The "modulus operator" (%@AB@%%%@AE@%) may be unfamiliar. It divides a value and gives the remainder. For instance, the statement %@NL@% %@NL@% %@AS@% remainder = 20 % 3;%@AE@%%@NL@% %@NL@% assigns the value 2 to the variable %@AS@% remainder %@AE@% (20 divided by 3 equals 6, with a remainder of 2). If the division doesn't produce a remainder, the modulus operator yields the value 0. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060004 @%%@AB@%Relational Operators%@AE@%%@EH@%%@NL@% %@NL@% "Relational operators" evaluate the relationship between two expressions, giving a true result (the value 1) or a false result (the value 0). C has six relational operators, which are listed in Table 6.2. %@NL@% %@NL@% %@AB@%Table 6.2 %@AB@%Relational Operators%@AE@%%@AE@% %@TH: 9 543 02 23 53 @%Operator Description%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%<%@AE@% Less than%@AB@%<=%@AE@% Less than or equal%@AB@%>%@AE@% Greater than%@AB@%>=%@AE@% Greater than or equal%@AB@%==%@AE@% Equal%@AB@%!=%@AE@% Not equal%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 9 543 02 23 53 @% The "equality operator" (%@AB@%==%@AE@%), shown above, tests whether two expressions are equal. %@NL@% %@NL@% Don't confuse the equality operator with the assignment operator (%@AB@%=%@AE@%) discussed in the next section. The assignment operator sets one value equal to another, as we'll see shortly. (Chapter 10, "Programming Pitfalls," discusses this common programming error.) %@NL@% %@NL@% The C language gives the value 1 for true and 0 for false but recognizes any nonzero value as true. The following code fragment demonstrates this difference: %@NL@% %@NL@% %@AS@% printf( "C generates %d for true\n", 2 == 2 ); %@AS@% printf( "C generates %d for false\n", 2 == 4 ); %@AS@% if( -33 ) %@AS@% printf( "C recognizes any nonzero value as true\n" );%@AE@%%@NL@% %@NL@% The output from this code, %@NL@% %@NL@% %@AS@% C generates 1 for true %@AS@% C generates 0 for false %@AS@% C recognizes any nonzero value as true%@AE@%%@NL@% %@NL@% shows that the true expression (%@AS@% 2 == 2 %@AE@%) gives the value 1 and the false expression (%@AS@% 2 == 4 %@AE@%) gives the value 0. The last output line shows that C recognizes the nonzero value -33 as a true value. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060005 @%%@AB@%Assignment Operators%@AE@%%@EH@%%@NL@% %@NL@% The "assignment operator" (%@AB@%=%@AE@%) sets one value equal to another. The following statement assigns the value of %@AS@% sample %@AE@% to %@AS@% val%@AE@%: %@NL@% %@NL@% %@AS@% val = sample;%@AE@%%@NL@% %@NL@% %@AU@% You can combine an assignment with a bitwise or arithmetic operation.%@AE@% %@NL@% %@NL@% In a convenient shorthand, C allows you to combine the assignment operator with any arithmetic or bitwise operator (see the "Arithmetic Operators" and "Bitwise Operators" sections). For example, the statement %@NL@% %@NL@% %@AS@% val = val + sample;%@AE@%%@NL@% %@NL@% can more conveniently be written %@NL@% %@NL@% %@AS@% val += sample;%@AE@%%@NL@% %@NL@% Both statements add %@AS@% val %@AE@% to %@AS@% sample %@AE@% and then assign the result to %@AS@% val%@AE@%. %@NL@% %@NL@% Table 6.3 lists C's special assignment operators. %@NL@% %@NL@% %@AB@%Table 6.3 %@AB@%Special Assignment Operators%@AE@%%@AE@% %@TH: 13 863 02 12 14 50 @%Expression Equivalent Operation%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AS@%x *= y%@AE@% %@AS@% x = x * y%@AE@% Multiplication%@AS@%x /= y%@AE@% %@AS@% x = x / y%@AE@% Division%@AS@%x %= y%@AE@% %@AS@% x = x % y%@AE@% Modulus%@AS@%x += y%@AE@% %@AS@% x = x + y%@AE@% Addition%@AS@%x -= y%@AE@% %@AS@% x = x - y%@AE@% Subtraction%@AS@%x <<= y%@AE@% %@AS@% x = x << y%@AE@% Left shift%@AS@%x >>= y%@AE@% %@AS@% x = x >> y%@AE@% Right shift%@AS@%x &= y%@AE@% %@AS@% x = x & y%@AE@% AND%@AS@%x ^= y%@AE@% %@AS@% x = x ^ y%@AE@% Exclusive OR%@AS@%x |= y%@AE@% %@AS@% x = x | y%@AE@% Inclusive OR%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 13 863 02 12 14 50 @% Note that the equal sign always follows the other operator. In the following code, %@NL@% %@NL@% %@AS@% val ^= sample; %@AS@% val =^ sample;%@AE@%%@NL@% %@NL@% the first statement is meaningful, but the second is a syntax error. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00060006 @%%@AB@%C's Unique Operators%@AE@%%@EH@%%@NL@% %@NL@% The remaining sections in this chapter describe C operators that fall into two categories: those that are unique to C and those that look or behave differently in C than in other languages. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060007 @%%@AB@%Increment and Decrement Operators%@AE@%%@EH@%%@NL@% %@NL@% The C language's unique "increment" (%@AB@%++%@AE@%) and "decrement" (%@AB@%- -%@AE@%) operators are very useful. They increase or decrease an expression by a value of 1. %@NL@% %@NL@% %@AB@%Table 6.4 %@AB@%Increment and Decrement Operators%@AE@%%@AE@% %@TH: 5 370 02 22 54 @%Operator Operation%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%++%@AE@% Increment expression by 1%@AB@%- -%@AE@% Decrement expression by 1%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 5 370 02 22 54 @% Thus, the two statements %@NL@% %@NL@% %@AS@% val = val + 1; %@AS@% val++;%@AE@%%@NL@% %@NL@% are equivalent and so are these statements: %@NL@% %@NL@% %@AS@% val = val - 1; %@AS@% val--;%@AE@%%@NL@% %@NL@% %@AU@% You can use the ++ and - - operators before or after an expression.%@AE@% %@NL@% %@NL@% The %@AB@%++%@AE@% and %@AB@%- -%@AE@% operators can precede or follow an expression. Placed before an expression, the operator changes the expression before the expression's value is used. In this case, the operator is said to be a "prefix" operator. Placed after an expression, the operator (known as a "postfix" operator) changes the value of the expression after the expression's value is used. %@NL@% %@NL@% In the DECRMENT.C program, shown below, the decrement operator is used both as a prefix operator and a postfix operator. %@NL@% %@NL@% %@AS@% /* DECRMENT.C: Demonstrate prefix and postfix operators. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% main() %@AS@% { %@AS@% int val, sample = 3, proton = 3; %@AS@% val = sample--; %@AS@% printf( "val = %d sample = %d\n", val, sample ); %@AS@% val = --proton; %@AS@% printf( "val = %d proton = %d\n", val, proton ); %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from DECRMENT.C: %@NL@% %@NL@% %@AS@% val = 3 sample = 2 %@AS@% val = 2 proton = 2%@AE@%%@NL@% %@NL@% In the first use of the decrement operator, the statement %@NL@% %@NL@% %@AS@% val = sample--;%@AE@%%@NL@% %@NL@% assigns the value of %@AS@% sample %@AE@% (3) to the variable %@AS@% val %@AE@% and then decrements %@AS@% %@AS@%sample %@AE@% to the value 2. Contrast this with the statement %@NL@% %@NL@% %@AS@% val = --proton;%@AE@%%@NL@% %@NL@% which first decrements %@AS@% proton %@AE@% to the value 2 and then assigns that value to %@AS@% val%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060008 @%%@AB@%Bitwise Operators%@AE@%%@EH@%%@NL@% %@NL@% The "bitwise operators," listed in Table 6.5, manipulate bits in data of the integer type. These operators are often used in programs that must interact with hardware. %@NL@% %@NL@% %@AB@%Table 6.5 %@AB@%Bitwise Operators%@AE@%%@AE@% %@TH: 9 548 02 26 50 @%Operator Description%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%~%@AE@% Complement%@AB@%<<%@AE@% Left shift%@AB@%>>%@AE@% Right shift%@AB@%&%@AE@% AND%@AB@%^%@AE@% Exclusive OR%@AB@%|%@AE@% Inclusive OR%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 9 548 02 26 50 @% The %@AB@%~%@AE@% operator, known as the "one's complement," acts on only one value (rather than on two, as do most operators). This operator changes every 1 bit in its operand to a 0 bit and vice versa. %@NL@% %@NL@% The %@AB@%%@AE@% and%@AB@% >>%@AE@% operators, known as the "shift operators," shift the left operand by the value given in the right operand. These operators offer a fast, convenient way to multiply or divide integers by a power of 2. %@NL@% %@NL@% The %@AB@%&%@AE@% operator, known as the "bitwise AND," sets a bit to 1 if either of the corresponding bits in its operands is 1, or to 0 if both corresponding bits are 0. It is often used to "mask," or turn off, one or more bits in a value. %@NL@% %@NL@% The %@AB@%^%@AE@% operator, known as the "bitwise exclusive OR," sets a bit to 1 if the corresponding bits in its operands are different, or to 0 if they are the same. %@NL@% %@NL@% The %@AB@%|%@AE@% operator, known as the "bitwise inclusive OR," sets a bit to 1 if either of the corresponding bits in its operands is 1, or to 0 if both corresponding bits are 0. It is often used to turn on bits in a value. %@NL@% %@NL@% Each of the bitwise operators is used in the BITWISE.C program, shown below. %@NL@% %@NL@% %@AS@% /* BITWISE.C: Demonstrate bitwise operators. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% printf( "255 & 15 = %d\n", 255 & 15 ); %@AS@% printf( "255 | 15 = %d\n", 255 | 15 ); %@AS@% printf( "255 ^ 15 = %d\n", 255 ^ 15 ); %@AS@% printf( "2 << 2 = %d\n", 2 << 2 ); %@AS@% printf( "16 >> 2 = %d\n", 16 >> 2 ); %@AS@% printf( "~2 = %d\n", ~2 ); %@AS@% }%@AE@%%@NL@% %@NL@% The output from BITWISE.C, %@NL@% %@NL@% %@AS@% 255 & 15 = 15 %@AS@% 255 | 15 = 255 %@AS@% 255 ^ 15 = 240 %@AS@% 2 << 2 = 8 %@AS@% 16 >> 2 = 4 %@AS@% ~2 = -3%@AE@%%@NL@% %@NL@% shows the results of the program's various bitwise operations. %@NL@% %@NL@% The fourth and fifth output lines show you how to use shift operators to multiply and divide by powers of 2. The program multiplies 2 by 4 by shifting the value 2 twice to the left: %@NL@% %@NL@% %@AS@% 2 << 2 = 8%@AE@%%@NL@% %@NL@% Similarly, the program divides 16 by 4 by shifting the value 16 twice to the right: %@NL@% %@NL@% %@AS@% 16 >> 2 = 4%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060009 @%%@AB@%Logical Operators%@AE@%%@EH@%%@NL@% %@NL@% C has three logical operators─AND, OR, and NOT─that allow you to test more than one condition in a single expression. Table 6.6 lists C's logical operators. %@NL@% %@NL@% %@AB@%Table 6.6 %@AB@%Logical Operators%@AE@%%@AE@% %@TH: 6 409 02 27 49 @%Operator Description%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%!%@AE@% Logical NOT%@AB@%&&%@AE@% Logical AND%@AB@%| |%@AE@% Logical OR%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 6 409 02 27 49 @% The logical OR ( %@AB@%| |%@AE@% ) and AND (%@AB@%&&%@AE@%) operators are often used to combine logical tests within a conditional statement. For example, the %@AB@%if%@AE@% statement %@NL@% %@NL@% %@AS@% if( val > 10 && sample < 10 ) %@AS@% printf( "Oh joy!\n" );%@AE@%%@NL@% %@NL@% prints %@AS@% Oh joy! %@AE@% if both conditions in the test expression are true (if %@AS@% val %@AS@%%@AE@% is greater than 10 and %@AS@% sample %@AE@% is less than 10). Here, the relational operators (%@AB@%>%@AE@% and %@AB@%%@AE@%) have higher "precedence" than the logical AND operator (%@AB@%&&%@AE@%), so the compiler evaluates them first. We discuss operator precedence later in this chapter. %@NL@% %@NL@% The logical NOT operator (%@AB@%!%@AE@%) reverses an expression's logical value. For instance, if the variable %@AS@% val %@AE@% has the value 8, the expression %@AS@% (val == 8) %@AE@% is true but the expression %@AS@% !(val == 8) %@AE@% is false. %@NL@% %@NL@% The NOT.C program below shows a common use of this operator. %@NL@% %@NL@% %@AS@% /* NOT.C: Demonstrate logical NOT operator. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int val = 0; %@AS@% if( !val ) %@AS@% printf( "val is zero" ); %@AS@% }%@AE@%%@NL@% %@NL@% The expression %@AS@% if( !val ) %@AE@% is equivalent to the expression %@AS@% if( val == 0 )%@AE@%. When used in this way, the logical NOT operator converts a 0 value to 1 and any nonzero value to 0. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%Don't confuse the logical OR and AND operators with the bitwise OR and AND %@AI@%operators discussed in the previous section. The bitwise operators use the %@AI@%same ASCII symbols, but have only one character. For instance, logical AND %@AI@%is %@AB@%&&%@AE@%%@AI@%, whereas bitwise AND is %@AE@%%@AI@%%@AB@%&%@AE@%%@AE@%%@AI@%.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060010 @%%@AB@%Address Operators%@AE@%%@EH@%%@NL@% %@NL@% The C language has two operators that work with memory addresses. Table 6.7 lists C's address operators. %@NL@% %@NL@% %@AB@%Table 6.7 %@AB@%Address Operators%@AE@%%@AE@% %@TH: 5 373 02 15 61 @%Operator Operation%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%&%@AE@% Yield address of the operand%@AB@%*%@AE@% Yield value contained at the operand's address%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 5 373 02 15 61 @% Both address operators are often used with pointers─variables that contain the addresses of other variables. Chapter 8, "Pointers," and Chapter 9, "Advanced Pointers," are devoted to explaining pointers, including the use of these two operators with them. Since you must understand pointers in order to understand these operators fully, we'll describe them briefly here and elaborate on their use in Chapter 8. %@NL@% %@NL@% The "address-of operator" (%@AB@%&%@AE@%) yields a constant equal to the machine address of its operand. For instance, if the variable %@AS@% val %@AE@% contains the value 10, and its storage is located at address 1508, the expression %@AS@% val %@AE@% yields the value 10, while the expression %@AS@% &val %@AE@% yields the constant 1508. %@NL@% %@NL@% Since the address-of operator yields a constant, you can't assign a value to an expression that uses it. The statement %@NL@% %@NL@% %@AS@% &val = 20;%@AE@%%@NL@% %@NL@% is illegal for the same reason that the statement %@NL@% %@NL@% %@AS@% 1508 = 20;%@AE@%%@NL@% %@NL@% won't pass muster. %@NL@% %@NL@% The "indirection operator" (%@AB@%*%@AE@%) yields the value contained in the address referenced by its operand. If you declare %@AS@% ptr %@AE@% as a pointer variable, the expression %@NL@% %@NL@% %@AS@% *ptr%@AE@%%@NL@% %@NL@% yields the contents of the address to which %@AS@% ptr %@AE@% points. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060011 @%%@AB@%Conditional Operator%@AE@%%@EH@%%@NL@% %@NL@% The "conditional operator" (%@AB@%? :%@AE@%) is made up of two symbols and requires three expressions. It is similar to an %@AB@%if%@AE@%-%@AB@%else%@AE@% construct. If the first expression evaluates as true, the first operand is assigned the value of the second operand. If the first expression is false, the first operand is assigned the value of the third operand. %@NL@% %@NL@% The following statement gives the absolute value of the variable %@AS@% val%@AE@%. The variable is assigned its original value if it is nonnegative or is negated if its original value is negative: %@NL@% %@NL@% %@AS@% val = (val >= 0 ) ? val : -val;%@AE@%%@NL@% %@NL@% The statement is equivalent to the following %@AB@%if%@AE@%-%@AB@%else%@AE@% construct: %@NL@% %@NL@% %@AS@% if( val >= 0 ) %@AS@% val = val; %@AS@% else %@AS@% val = -val;%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060012 @%%@AB@%The sizeof Operator%@AE@%%@EH@%%@NL@% %@NL@% The "%@AB@%sizeof%@AE@% operator" yields the number of bytes contained in its operand, which can be either a general data type or a specific variable. If you apply %@AB@%sizeof%@AE@% to a type name in parentheses, as in the expression %@NL@% %@NL@% %@AS@% sizeof( int )%@AE@%%@NL@% %@NL@% the operator yields the size of that data type in bytes. This example yields the value 2, indicating that an %@AB@%int%@AE@% contains two bytes on DOS machines. You can use this feature to determine the sizes of types that are implementation dependent when transporting a program from one machine to another. %@NL@% %@NL@% If you place %@AB@%sizeof%@AE@% in front of a variable name, the operator returns the number of bytes in the variable. For instance, if you create the string %@NL@% %@NL@% %@AS@% char my_string[] = "Hello";%@AE@%%@NL@% %@NL@% the expression %@NL@% %@NL@% %@AS@% sizeof my_string%@AE@%%@NL@% %@NL@% yields the value 6, showing that the string contains 5 printing characters and a null character. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060013 @%%@AB@%Comma Operator%@AE@%%@EH@%%@NL@% %@NL@% Preceding chapters have shown various ways to use the comma (%@AB@%,%@AE@%) in C programming. For instance, commas can separate multiple function arguments or variable declarations. In such cases the comma is not an operator in the formal sense but merely punctuation, like the semicolon that ends a statement. %@AS@% %@AE@%%@NL@% %@NL@% %@AU@% The comma is used as punctuation and as an operator in C.%@AE@% %@NL@% %@NL@% In C, the comma can also perform as an operator. The commas that separate multiple expressions determine the order in which the expressions are evaluated, and the type and value of the result that is returned. The comma operator causes expressions to be evaluated from left to right. The value and type of the result are the value and type of the rightmost operand. %@NL@% %@NL@% For example, the statement %@NL@% %@NL@% %@AS@% val = sample, sample = temp;%@AE@%%@NL@% %@NL@% first assigns the value of %@AS@% sample %@AE@% to %@AS@% val%@AE@%, then assigns the value of %@AS@% temp %@AS@%%@AE@% to %@AS@% sample%@AE@%. %@NL@% %@NL@% The comma operator often appears in %@AB@%for%@AE@% statements, where it can separate multiple initializing expressions or multiple modifying expressions. The FORLOOP1.C program from Chapter 3, "Flow Control," demonstrates both uses. Here is the %@AB@%for%@AE@% statement from that program: %@NL@% %@NL@% %@AS@% for( a = 256, b = 1; b < 512; a = a / 2, b = b * 2 ) %@AS@% printf( "a = %d \tb = %d\n", a, b );%@AE@%%@NL@% %@NL@% The statement initializes two variables (%@AS@% a %@AE@% and %@AS@% b %@AE@%) and contains two modifying expressions (%@AS@% a = a / 2 %@AE@% and %@AS@% b = b * 2 %@AE@%). Chapter 3 explains the FORLOOP1.C program in detail. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00060014 @%%@AB@%Base Operator%@AE@%%@EH@%%@NL@% %@NL@% The base operator (%@AB@%:>%@AE@%) associates a base expression with a based pointer. Based-object support is a highly advanced feature included in QuickC 2.5 for compatibility with Microsoft C version 6.0; please refer to your C 6.0 documentation for information about based objects. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00060015 @%%@AB@%Operator Precedence%@AE@%%@EH@%%@NL@% %@NL@% Like all languages, C has precedence rules that control the order for evaluating the elements in expressions containing more than one operator. If you're familiar with precedence rules in other languages, you won't find any surprises in C. Table 6.8 shows the "pecking order" established for C's operators. %@NL@% %@NL@% Three general rules control the order of evaluation: %@NL@% %@NL@% %@NL@% 1. When two operators have unequal precedence, the operator with higher precedence is evaluated first.%@NL@% %@NL@% 2. Operators with equal precedence are evaluated from left to right.%@NL@% %@NL@% 3. You can change the normal order of precedence by enclosing an expression in parentheses. The enclosed expression is then evaluated first. (If parentheses are nested, inner parentheses have higher precedence than outer ones.)%@NL@% %@NL@% %@NL@% We'll demonstrate operator precedence with a simple example. Since the multiplication operator (*) has higher precedence than the addition operator (+), the statement %@NL@% %@NL@% %@AS@%%@AE@%val = 2 + 3 * 4 %@NL@% %@NL@% assigns to%@AS@% val %@AE@%the value of 14 (or 2 + 12) rather than 20 (or 5 * 4). Since parentheses have higher precedence than any operator, they can change the normal precedence order. If you enclose the addition operation in parentheses, as follows %@NL@% %@NL@% %@AS@%%@AE@%val = (2 + 3) * 4 %@NL@% %@NL@% the addition is done first. Now the statement assigns to%@AS@% val %@AE@% the value 20 (or 5 * 4). %@NL@% %@NL@% Table 6.8 lists the C operators and their precedence values. The lines in the table separate precedence levels. The highest precedence level is at the top of the table. %@NL@% %@NL@% %@AB@%Table 6.8 %@AB@%C Operators%@AE@%%@AE@% %@TH: 114 4496 02 24 37 15 @%Symbol Name or Meaning Associativity%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%( ) Function call Left to right[ ] Array element %@AB@%.%@AE@% Structure or union member %@AB@%->%@AE@% Pointer to structure member %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%- -%@AE@% Decrement Right to left%@AB@%++%@AE@% Increment %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%:> Base operator Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%!%@AE@% Logical NOT Right to left%@AB@%~ %@AE@% One's complement%@AB@% %@AE@%%@AB@%-%@AE@% Unary minus %@AB@%+%@AE@% Unary plus %@AB@%&%@AE@% Address %@AB@%*%@AE@% Indirection %@AB@%sizeof%@AE@% Size in bytes %@AB@%(%@AE@%type%@AB@%)%@AE@% Type cast [for example, (%@AB@%float%@AE@%) i] %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%*%@AE@% Multiply Left to right%@AB@%/%@AE@% Divide %@AB@%%%@AE@% Modulus (remainder) %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%+%@AE@% Add Left to right%@AB@%-%@AE@% Subtract %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%<<%@AE@% Left shift Left to right%@AB@%>>%@AE@% Right shift %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%<%@AE@% Less than Left to right%@AB@%<=%@AE@% Less than or equal %@AB@%>%@AE@% Greater than %@AB@%>=%@AE@% Greater than or equal %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%==%@AE@% Equal Left to right%@AB@%!=%@AE@% Not equal %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%&%@AE@% Bitwise AND Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%^%@AE@% Bitwise exclusive OR Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%|%@AE@% Bitwise OR Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%&&%@AE@% Logical AND Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%||%@AE@% Logical OR Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%? : %@AE@% Conditional Right to left%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%=%@AE@% Assignment Right to left%@AB@%*=, /=, %=, +=, -=, %@AE@% Compound assignment %@AB@%<<=, >>=, &=, ^=, |=%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%,%@AE@% Comma Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 114 4496 02 24 37 15 @% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00070001 @%%@1@%%@AB@%Chapter 7 Preprocessor Directives%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% This chapter describes preprocessor directives─commands that control the QuickC compiler. It explains how to insert the contents of one source file into another file, how to do text substitutions throughout a file, and how to compile different parts of a file in different situations. %@NL@% %@NL@% A "preprocessor directive" is a command to the QuickC compiler. Although they appear in the same source file as executable statements, preprocessor directives aren't statements in the formal sense. Unlike executable statements, they are not translated into machine code. Instead, they tell the compiler itself to take some action while it translates your source program. For instance, an %@AB@%#include%@AE@% directive tells QuickC to insert another file into the source file. %@NL@% %@NL@% The term "preprocessor" refers to the time when these commands are carried out. Like most language compilers, QuickC translates your source program in several phases, the first of which is called the "preprocessor phase." QuickC first "preprocesses" all the directives in your source program, then processes the program's executable statements. %@NL@% %@NL@% All preprocessor directives begin with a number sign (%@AB@%#%@AE@%), which must be the first nonblank character in the line on which it appears. Since directives aren't statements, they don't end with semicolons. You can't put other statements or directives on the same line with a preprocessor directive, except for a comment, which must appear to the right of the directive. %@NL@% %@NL@% Because the compiler reads your source file sequentially, line by line, the position of directives is important. A preprocessor directive only affects statements that follow it in the source file. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00070002 @%%@AB@%The #include Directive%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The #include directive inserts another file in the source file.%@AE@% %@NL@% %@NL@% The %@AB@%#include%@AE@% directive inserts the contents of another file into your source file. The inserted file is called an include file or header file. %@NL@% %@NL@% When the compiler encounters an %@AB@%#include%@AE@%, it searches for the file named in the directive. This directive makes QuickC look for the standard include file STDIO.H: %@NL@% %@NL@% %@AS@% #include <stdio.h>%@AE@%%@NL@% %@NL@% If the designated file is found, the compiler inserts its contents at the spot where the %@AB@%#include%@AE@% directive appears. Figure 7.1 illustrates a program SAMPLE.C that includes the file STDIO.H. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% When QuickC compiles the SAMPLE.C program shown in Figure 7.1, it inserts the contents of file STDIO.H into SAMPLE.C at the spot marked by the %@AB@%#include%@AE@% directive. %@NL@% %@NL@% Most include files contain commonly used declarations and definitions. Standard include files, supplied with QuickC, contain declarations and definitions for QuickC library routines. You can also write include files of your own. %@NL@% %@NL@% Standard include files end with the .H file extension (STDIO.H is an example). You can use any extension for include files you create, but most programmers stick with the .H extension. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%In some languages, it's common to put executable statements, as well as %@AI@%declarations and definitions, in include files. This practice is legal but %@AI@%not recommended in QuickC. Microsoft debugging tools such as the Microsoft %@AI@%CodeView(R) debugger may not recognize executable statements in include %@AI@%files.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% The %@AB@%#include%@AE@% directive doesn't support wild cards, so you can't insert a group of related files with a single directive. Each %@AB@%#include%@AE@% directive inserts only one file. %@NL@% %@NL@% Include files can be nested. For instance, the source program SAMPLE.C might include a file named INOUT.H. The INOUT.H file, in turn, might contain a second %@AB@%#include%@AE@% directive that includes a file named KEYBOARD.H. Figure 7.2 illustrates this process. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Although it's rarely necessary to nest include files more than two or three levels, nesting may continue up to 10 levels. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00070003 @%%@AB@%Specifying Include Files%@AE@%%@EH@%%@NL@% %@NL@% There are two ways to tell QuickC where to search for an include file. You may have noticed that the %@AB@%#include%@AE@% directive shown earlier encloses the file name STDIO.H in angle brackets (%@AB@%<>%@AE@%). If you enclose the file name in angle brackets, as in the directive %@NL@% %@NL@% %@AS@% #include <stdio.h>%@AE@%%@NL@% %@NL@% the compiler searches the "standard directories" for the file. %@NL@% %@NL@% In QuickC, the standard directories are one or more directories that you define by a DOS environment variable named INCLUDE. An advantage of specifying the standard directories is that QuickC can automatically search more than one directory. %@NL@% %@NL@% Alternatively, you can enclose the file name in double quotes, in the following manner, %@NL@% %@NL@% %@AS@% #include "myfile.h"%@AE@%%@NL@% %@NL@% to cause QuickC to start searching in the directory that contains the current source file. If the target file isn't in that directory, the compiler searches the standard directories. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%You can specify additional directories on the DOS command line when you %@AI@%invoke QuickC with the QCL command. See Chapter 1, "Creating Executable %@AI@%Programs," in the %@AI@%Microsoft QuickC Tool Kit%@AE@%%@AI@%.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00070004 @%%@AB@%The #define and #undef Directives%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%#define%@AE@% directive performs a text substitution in the source file. This directive has two main uses: simple text replacement and creation of function-like macros. It is also used with the %@AB@%#undef%@AE@% directive to control conditional compilation, as we'll discuss later. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00070005 @%%@AB@%Simple Text Replacement%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The #define directive works like the search and replace function of a %@AU@%word processor.%@AE@% %@NL@% %@NL@% At the simplest level, the %@AB@%#define%@AE@% directive works much like the "search and replace" function of a word processor, replacing one piece of text in the source file with another piece of text. The %@AB@%#define%@AE@% directive is commonly used to create a symbolic constant─a meaningful name for a "magic number" whose meaning might not otherwise be apparent. This improves the program's readability. %@NL@% %@NL@% For instance, in the VOLUME.C program in Chapter 1, "Anatomy of a C Program," the directive %@NL@% %@NL@% %@AS@% #define PI 3.14%@AE@%%@NL@% %@NL@% defines a symbolic constant named %@AS@% PI%@AE@%. The directive causes QuickC to replace every occurrence of the text %@AS@% PI %@AE@% in the VOLUME.C source program with the text %@AS@% 3.14%@AE@%. For example, when the compiler encounters the program line %@NL@% %@NL@% %@AS@% result = 4 * PI * result;%@AE@%%@NL@% %@NL@% it expands the line to read %@NL@% %@NL@% %@AS@% result = 4 * 3.14 * result;%@AE@%%@NL@% %@NL@% Besides making your program more readable, symbolic constants can streamline its maintenance. For instance, say you later decide to use 3.14159265 rather than 3.14 in VOLUME.C. All you need to change is one %@AB@%#define%@AE@% directive at the beginning of the program. %@NL@% %@NL@% The replacement text can be longer than the 3.14159265 we used above. A replacement text can't be longer than 512 bytes in QuickC, but you'll rarely, if ever, have to worry about this limit. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00070006 @%%@AB@%Function-Like Macros%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A function-like macro accepts arguments, like a function.%@AE@% %@NL@% %@NL@% Some languages use the term "macro" when referring to replacement text. In C, a macro can do more than simply replace text. It can also accept arguments in much the same way that a function does. In this case the replacement text is called a "function-like macro." %@NL@% %@NL@% A well-designed macro can be every bit as useful as a function. In fact, some C library routines are implemented as macros rather than C functions. %@NL@% %@NL@% The MACRO.C program below has a macro that works like the %@AB@%abs%@AE@% library function, returning the absolute value of any integer. The macro uses the conditional operator (%@AB@%? :%@AE@%), which we explained in Chapter 6. %@NL@% %@NL@% %@AS@% /* MACRO.C: Demonstrate macros. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #define ABS(value) ( (value) >= 0 ? (value) : -(value) ) %@AS@% %@AS@% main() %@AS@% { %@AS@% int val = -20; %@AS@% printf( "result = %d\n", ABS(val) ); %@AS@% }%@AE@%%@NL@% %@NL@% The %@AS@% ABS %@AE@% macro behaves much like a function. You can "call" it by name, passing it an argument you want to process. The macro is defined in the following program line: %@NL@% %@NL@% %@AS@% #define ABS(value) ( (value) >= 0 ? (value) : -(value) )%@AE@%%@NL@% %@NL@% The parameter %@AS@% value %@AE@% appears four times in the macro─once in the macro name %@AS@% ABS %@AE@% and three times in the replacement text that follows the name. %@NL@% %@NL@% %@AU@% Always enclose macro parameters in parentheses.%@AE@% %@NL@% %@NL@% To avoid unwanted side effects, you should always enclose macro parameters in parentheses. If the parameter passed to the %@AS@% ABS %@AE@% macro is an expression containing operators, the lack of parentheses could cause operator-precedence errors. See the section "Omitting Parentheses from Macro Arguments" in Chapter 10, "Programming Pitfalls." %@NL@% %@NL@% Function-like macros, like other %@AB@%#define%@AE@% directives, are expanded during the preprocessor phase of compilation, before QuickC translates any executable statements. When QuickC encounters the line %@NL@% %@NL@% %@AS@% printf( "result= %d\n", ABS(val) );%@AE@%%@NL@% %@NL@% it expands it to read: %@NL@% %@NL@% %@AS@% printf( "result= %d\n", ( (val) >= 0 ? (val) : -(val) ) );%@AE@%%@NL@% %@NL@% %@AU@% Macros can improve readability.%@AE@% %@NL@% %@NL@% A macro can improve a program's readability by describing the nature of an operation while hiding its complex details. Most people find the first of the two statements above easier to understand than the expanded version. %@NL@% %@NL@% %@AU@% Macros are faster than functions but can make a program bigger.%@AE@% %@NL@% %@NL@% Function-like macros are fast, too. Since a macro creates in-line code, it doesn't have the overhead associated with a normal function call. On the other hand, each use of a macro inserts the same code in your program, whereas a function definition occurs only once. So while macros can be faster than functions, they can also bloat the size of the executable file. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00070007 @%%@AB@%The #undef Directive%@AE@%%@EH@%%@NL@% %@NL@% The "%@AB@%#undef%@AE@% directive" is related to %@AB@%#define%@AE@%. As the name suggests, %@AB@%#undef%@AE@% removes ("undefines") a name that was created with %@AB@%#define%@AE@%. For instance, if you create the symbolic constant %@AS@% PI %@AE@% with the %@AB@%#define%@AE@% directive, %@NL@% %@NL@% %@AS@% #define PI 3.14%@AE@%%@NL@% %@NL@% you can then remove the name %@AS@% PI %@AE@% with the following %@AB@%#undef%@AE@% directive: %@NL@% %@NL@% %@AS@% #undef PI%@AE@%%@NL@% %@NL@% You can use %@AB@%#define%@AE@% and %@AB@%#undef%@AE@% to create a name that has meaning in only part of a source program. The next two sections explain why you might want to do this. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00070008 @%%@AB@%Conditional Directives%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Conditional directives are useful for making different versions of a %@AU@%program.%@AE@% %@NL@% %@NL@% Conditional directives can make QuickC skip part of a source file. They are used primarily to create different versions of a program. While developing a program, for instance, you might want to include debugging code at some times but not others. Or, if you plan to move a program to some other machine, you can compile machine-specific sections of code only for a certain machine. %@NL@% %@NL@% The C-language conditional directives are listed below. %@NL@% %@NL@% %@AB@%#if%@AE@%%@AB@%%@AE@% %@AB@%#endif%@AE@%%@AB@%%@AE@% %@AB@%#else%@AE@%%@AB@%%@AE@% %@AB@%#ifdef%@AE@%%@AB@%%@AE@% %@AB@%#elif%@AE@% %@AB@%#ifndef%@AE@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The%@AB@% #ifdef%@AE@%%@AI@% and %@AE@%%@AI@%%@AB@%#ifndef %@AE@%%@AE@%%@AI@%directives are obsolete under the ANSI C standard; %@AI@%see "The defined Operator" below.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@AU@% The #if directive works like the if statement.%@AE@% %@NL@% %@NL@% The %@AB@%#if%@AE@% and %@AB@%#endif%@AE@% directives work like an %@AB@%if%@AE@% statement, allowing you to compile a block of source code if a given condition is true. The %@AB@%#if%@AE@% directive is followed by a constant expression, which the compiler tests at compile time. If the expression is false, the compiler skips every line between the %@AB@%#if%@AE@% and the next %@AB@%#endif%@AE@%. %@NL@% %@NL@% The example below calls the %@AS@% display %@AE@% function only if the name %@AS@% DEBUG %@AE@% was previously defined as 1 (with %@AB@%#define%@AE@%). %@NL@% %@NL@% %@AS@% #if DEBUG == 1 %@AS@% display( debuginfo ); %@AS@% #endif%@AE@%%@NL@% %@NL@% Here, the "conditional block" is a single line (the %@AS@% display %@AE@% function call). A conditional block can contain any number of valid C program lines, including preprocessor directives as well as executable statements. %@NL@% %@NL@% The test expression for a conditional directive can be almost any expression that evaluates to a constant, with a few minor exceptions (the expression can't use the %@AB@%sizeof%@AE@% operator, type casts, or the %@AB@%float%@AE@% and %@AB@%enum%@AE@% types). %@NL@% %@NL@% %@AU@% The #else directive works like the else keyword.%@AE@% %@NL@% %@NL@% The %@AB@%#else%@AE@% and %@AB@%#elif%@AE@% directives work like the %@AB@%else%@AE@% keyword and can perform more complex conditional tests. For example, you could use code like that in the following example to build different versions of a program for various IBM PC computers, including different files for each computer. %@NL@% %@NL@% %@AS@% #if XT == 1 %@AS@% #include "XT.H" %@AS@% #elif AT == 1 %@AS@% #include "AT.H" %@AS@% #else %@AS@% #include "PS2.H" %@AS@% #endif%@AE@%%@NL@% %@NL@% The code includes the file XT.H if the name %@AS@% XT %@AE@% is defined as 1 and it includes the file AT.H if the name %@AS@% AT %@AE@% is defined as 1. If both %@AS@% XT %@AE@% and %@AS@% %@AS@%AT %@AE@% are undefined, the third conditional block executes, causing QuickC to include the file PS2.H. %@NL@% %@NL@% You can nest conditional directives in the same way as you would conditional C language statements. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00070009 @%%@AB@%The defined Operator%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The defined operator tests whether a name has been defined.%@AE@% %@NL@% %@NL@% The test expression of an %@AB@%#if%@AE@% or %@AB@%#elif%@AE@% directive can use the %@AB@%defined%@AE@% operator to test whether a name has been defined. You can use this feature, along with %@AB@%#define%@AE@% and %@AB@%#undef%@AE@%, to turn various parts of a program on and off, compiling different parts under different conditions. %@NL@% %@NL@% The %@AB@%defined%@AE@% operator is true if its argument has been defined and false otherwise. A name is considered defined if it has been created with %@AB@%#define%@AE@% (and not later removed with %@AB@%#undef%@AE@%). %@NL@% %@NL@% The DEFINED.C program below prints %@AS@% Hi %@AE@% because the name %@AS@% DEBUG %@AE@% is defined when the compiler encounters the %@AB@%#if defined%@AE@% directive. %@NL@% %@NL@% %@AS@% /* DEFINED.C: Demonstrate defined operator. */ %@AS@% %@AS@% #define DEBUG 12345 %@AS@% %@AS@% main() %@AS@% { %@AS@% #if defined( DEBUG ) %@AS@% printf( "Hi\n" ); %@AS@% #endif %@AS@% }%@AE@%%@NL@% %@NL@% The %@AB@%defined%@AE@% operator tests only whether a name is defined, not whether it has a certain value. Thus, the DEFINED.C program will print %@AS@% Hi %@AE@% no matter what value is assigned %@AS@% DEBUG%@AE@%. You could substitute the directive %@NL@% %@NL@% %@AS@% #define DEBUG 0%@AE@%%@NL@% %@NL@% to define %@AS@% DEBUG %@AE@% as 0, or the directive %@NL@% %@NL@% %@AS@% #define DEBUG%@AE@%%@NL@% %@NL@% to define %@AS@% DEBUG %@AE@% as having no value at all. Both directives define the name %@AS@% DEBUG%@AE@%, so the program would print %@AS@% Hi %@AE@% in both cases. %@NL@% %@NL@% You can use the logical NOT operator (%@AB@%!%@AE@%) to reverse the logic of an %@AB@%#if %@AB@%defined%@AE@% directive. (Logical operators are explained in Chapter 6.) The code %@NL@% %@NL@% %@AS@% #if !defined( DEBUG ) %@AS@% printf( "Hi\n"); %@AS@% #endif%@AE@%%@NL@% %@NL@% prints %@AS@% Hi %@AE@% if %@AS@% DEBUG %@AE@% is not currently defined. %@NL@% %@NL@% A plain %@AB@%#if%@AE@% directive treats undefined names a little differently than does an %@AB@%#if defined%@AE@% directive. If a name is not currently defined, the %@AB@%#if%@AE@% directive treats the name as having the value 0. %@NL@% %@NL@% In the following code, the %@AB@%#if%@AE@% directive explicitly tests whether %@AS@% DEBUG %@AE@% equals 0. %@NL@% %@NL@% %@AS@% #undef DEBUG %@AS@% #if DEBUG == 0 %@AS@% printf( "Hi\n" ); %@AS@% #endif%@AE@%%@NL@% %@NL@% The result is the same as that of the previous example. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The %@AB@%defined%@AE@%%@AI@% operator is new under the ANSI C standard. You may see older %@AI@%programs that use the older directives %@AE@%%@AI@%%@AB@%#ifdef %@AE@%%@AE@%%@AI@%and %@AE@%%@AI@%%@AB@%#ifndef %@AE@%%@AE@%%@AI@%for the same %@AI@%purpose. These directives are obsolete, but QuickC version 2.5 supports them %@AI@%for the sake of compatibility. The #%@AE@%%@AI@%%@AB@%ifdef %@AE@%%@AE@%%@AI@%directive is followed by a name %@AI@%(not in parentheses) and works the same as %@AE@%%@AI@%%@AB@%#if %@AE@%%@AE@%%@AI@%with %@AE@%%@AI@%%@AB@%defined%@AE@%%@AE@%%@AI@%. If the given %@AI@%name has been defined, %@AE@%%@AI@%%@AB@%#ifdef %@AE@%%@AE@%%@AI@%is true. The %@AE@%%@AI@%%@AB@%#ifndef %@AE@%%@AE@%%@AI@%directive is the opposite %@AI@%of %@AE@%%@AI@%%@AB@%#ifdef%@AE@%%@AE@%%@AI@%. It is true if the given name is not currently defined.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00070010 @%%@AB@%Pragmas%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Pragmas are implementationspecific compiler commands.%@AE@% %@NL@% %@NL@% Although portability is a hallmark of C, the language's creators recognized that every C compiler will need to support some features unique to its host machine. The "%@AB@%#pragma%@AE@% directive" offers a way for each C compiler to offer machine-specific features while retaining overall compatibility with the C language. Since pragmas are machine-specific by definition, they can be─and usually are─different for every C compiler. %@NL@% %@NL@% Pragmas have the same general syntax as preprocessor directives. The pragma must begin with a number sign (%@AB@%#%@AE@%) and it can't share a line with other directives or statements except a comment, which must appear to the right of the pragma. %@NL@% %@NL@% QuickC supports four pragmas: %@AB@%check_stack%@AE@%, %@AB@%check_pointer%@AE@%, %@AB@%message%@AE@%, and %@AB@%pack%@AE@%. Each of these pragmas is described in online help. %@NL@% %@NL@% Some pragmas take arguments, which come after the %@AB@%#pragma%@AE@% keyword. In the following code, the %@AB@%message%@AE@% pragma displays different messages during compilation depending on the outcome of an %@AB@%#if%@AE@% test: %@NL@% %@NL@% %@AS@% #if XT == 1 %@AS@% #pragma message( "Building XT version" ) %@AS@% #elif AT == 1 %@AS@% #pragma message( "Building AT version" ) %@AS@% #endif%@AE@%%@NL@% %@NL@% The message displayed by the %@AB@%message%@AE@% pragma is visible only if you compile from the DOS command line with the QCL command. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00080001 @%%@1@%%@AB@%Chapter 8 Pointers%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% The next two chapters explain pointers─a large and important topic in C. This chapter explains fundamental techniques: how to use pointers with various data types and pass them to functions. In Chapter 9, "Advanced Pointers," we'll explore more advanced pointer techniques, such as multiple indirection. %@NL@% %@NL@% If you have never used pointers before, you may want to read this chapter now and then turn to Chapter 9 after you have had some practice using pointers in your own programs. %@NL@% %@NL@% %@AU@% Don't panic!%@AE@% %@NL@% %@NL@% There's a lot of new information in these two chapters. Don't be discouraged if you don't grasp it all on a first reading. The idea behind a pointer is simple, but some advanced pointer techniques are not so easy to follow at first. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00080002 @%%@AB@%Using Pointers in C%@AE@%%@EH@%%@NL@% %@NL@% Almost every real-world C program uses pointers in some way or another. Much of the usefulness of pointers stems from the fact that in C all function arguments are passed by value. Because a function only receives local copies of such arguments, it can't change the original values that the arguments represent. Pointers make this possible. %@NL@% %@NL@% Here are some common uses of pointers: %@NL@% %@NL@% %@NL@% ■ Manipulating strings%@NL@% %@NL@% ■ Passing command-line arguments to a program at run time%@NL@% %@NL@% ■ Returning more than one value from a function%@NL@% %@NL@% ■ Accessing variables that wouldn't otherwise be visible to a function%@NL@% %@NL@% ■ Manipulating an array by moving pointers to its elements instead of using array subscripting%@NL@% %@NL@% ■ Accessing the address of a memory area that your program allocates at run time%@NL@% %@NL@% ■ Passing the address of one function to another function%@NL@% %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00080003 @%%@AB@%Pointers to Simple Variables%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A pointer variable contains the address of a data object.%@AE@% %@NL@% %@NL@% Although pointers have many different uses, it takes only a few words to say what a pointer is. A "pointer" is a variable that contains the address of some other data object─usually a variable. Because a pointer contains the other variable's address, it is said to "point to" that variable. %@NL@% %@NL@% This section uses the program POINTER.C to demonstrate the basic mechanics of pointers─how to declare and initialize a pointer and use it to access a simple variable: %@NL@% %@NL@% %@AS@% /* POINTER.C: Demonstrate pointer basics. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int val = 25; %@AS@% int *ptr; %@AS@% ptr = &val; %@AS@% printf( " val = %d\n", val ); %@AS@% printf( "*ptr = %d\n\n", *ptr ); %@AS@% printf( "&val = %u\n", &val ); %@AS@% printf( " ptr = %d\n", ptr ); %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from POINTER.C: %@NL@% %@NL@% %@AS@% val = 25 %@AS@% *ptr = 25 %@AS@% %@AS@% &val = 5308 %@AS@% ptr = 5308%@AE@%%@NL@% %@NL@% (The third and fourth output lines show addresses. These may differ when you run POINTER.C depending on factors such as available memory.) %@NL@% %@NL@% POINTER.C creates a pointer variable named %@AS@% ptr %@AE@% and makes %@AS@% ptr %@AE@% point to an %@AB@%int%@AE@% variable named %@AS@% val%@AE@%. Then it prints the two values to show that %@AS@% ptr %@AE@% can access the value stored in %@AS@% val%@AE@%. The program goes on to print the address where %@AS@% val %@AE@% is stored and the address contained in %@AS@% ptr%@AE@%, to show they are the same. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080004 @%%@AB@%Declaring a Pointer Variable%@AE@%%@EH@%%@NL@% %@NL@% Like any variable, a pointer variable must be declared before it is used, and its value can change in the course of a program. A pointer variable can have any legal variable name. Here is the pointer declaration from POINTER.C: %@NL@% %@NL@% %@AS@% int *ptr;%@AE@%%@NL@% %@NL@% This declaration states the program has a pointer variable named %@AS@% ptr %@AE@% that can point to a data object of the %@AB@%int%@AE@% type. %@NL@% %@NL@% Notice the similarity to a simple variable declaration. As in other cases, the declaration gives a type (%@AB@%int%@AE@%) and name (%@AS@% ptr %@AE@%) for the variable. %@NL@% %@NL@% %@AU@% Use the indirection operator (%@AE@% *) to declare a pointer variable. %@NL@% %@NL@% The indirection operator (%@AB@%*%@AE@%) in front of the name %@AS@% ptr %@AE@% shows this variable is a pointer. This operator has two different uses in C. In declarations, such as the one above, it simply means "this is a pointer." In other contexts, as we'll elaborate throughout this chapter, it means indirection─using the data object that a pointer points to. %@NL@% %@NL@% %@AU@% A pointer declaration shows %@AE@%%@AB@%what%@AE@% type of data object a pointer references. %@NL@% %@NL@% A pointer doesn't have a type in the same sense as other variables. When you declare a simple variable, the type specifier shows what type of value the variable stores. When you declare a pointer variable, the type specifier shows what type of data object the pointer %@AI@%points to%@AE@%. %@NL@% %@NL@% Thus, in POINTER.C the declaration of the variable %@AS@% val %@AE@% indicates %@AS@% val %@AE@% stores a value of the type %@AB@%int%@AE@%, %@NL@% %@NL@% %@AS@% int val = 25;%@AE@%%@NL@% %@NL@% while the declaration of the variable %@AS@% ptr %@AE@% indicates it %@AI@%points to%@AE@% a data object of the type %@AB@%int%@AE@%: %@NL@% %@NL@% %@AS@% int *ptr;%@AE@%%@NL@% %@NL@% To declare pointers to other types of variables, you can use whatever type specifier is appropriate. These statements, for instance, declare pointers to %@AB@%char%@AE@% and %@AB@%float%@AE@% variables: %@NL@% %@NL@% %@AS@% char *c_ptr, *ch; %@AS@% float *f_pointer;%@AE@%%@NL@% %@NL@% Note that if you declare more than one pointer variable in the same line, each name must be preceded by the indirection operator. The first line in the previous example declares two pointer variables: %@AS@% c_ptr %@AE@% and %@AS@% ch%@AE@%. Each pointer can point to an object of the %@AB@%char%@AE@% type. If you omit the second indirection operator from the first line, %@NL@% %@NL@% %@AS@% char *c_ptr, ch;%@AE@%%@NL@% %@NL@% the line declares a pointer variable named %@AS@% c_ptr %@AE@% and an ordinary %@AB@%char%@AE@% variable named %@AS@% ch%@AE@%. %@NL@% %@NL@% %@AU@% A pointer declared with type %@AE@%%@AB@%void%@AE@% can point to any type of data object. %@NL@% %@NL@% In most cases a pointer points to a particular type of object, such as an %@AB@%int%@AE@%. You can also declare a pointer with type %@AB@%void%@AE@%, which allows it to point to any type of object. %@NL@% %@NL@% One use of %@AB@%void%@AE@% pointers is to write a general-purpose function, such as a sort, that can operate on data of more than one type. Each time you use a %@AB@%void%@AE@% pointer, you must perform an explicit type cast to show what type of object it points to on that occasion. %@NL@% %@NL@% Figure 8.1 shows the relationship between %@AS@% val %@AE@% and %@AS@% ptr %@AE@% in POINTER.C, immediately after %@AS@% ptr %@AE@% has been declared. The figure shows that the variable %@AS@% val %@AE@% is stored at memory location 5308, as in the output shown above. Again, the actual address may differ when you run POINTER.C. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Figure 8.1 uses question marks to show that the contents of %@AS@% ptr %@AE@% are undefined at this stage in the program. Like any other variable that has been declared but not initialized, the contents of %@AS@% ptr %@AE@% are unknown. You must take special care not to use pointers that have not been initialized, since an uninitialized pointer might point anywhere in memory─including sensitive operating-system addresses. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% Because a pointer can potentially access any memory address, using an uninitialized pointer can have drastic consequences.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080005 @%%@AB@%How Pointers Are Stored%@AE@%%@EH@%%@NL@% %@NL@% Figure 8.1 also shows that while a pointer is a special kind of variable, it is not a mysterious entity floating in limbo. A pointer is a true variable whose contents are stored at a specific memory address. %@NL@% %@NL@% In POINTER.C we don't care precisely where the pointer's contents are stored─the compiler handles that detail for us, as it does so many others. So Figure 8.1 does not include the address of the storage for %@AS@% ptr%@AE@%. It does show, however, that the pointer is stored in two bytes, the same amount of memory needed to store an %@AB@%int%@AE@% value. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The actual amount of memory needed to store a pointer variable depends on %@AI@%the current "memory model." In the %@AI@%small%@AE@%%@AI@% memory model─the default for QuickC %@AI@%version 2.5─a pointer is stored in two bytes. In some larger memory models, %@AI@%a pointer is stored in four bytes. For purposes of discussion, this chapter %@AI@%and the following chapter assume the small memory model. Appendix B, %@AI@%"Working with QuickC Memory Models," in the Microsoft QuickC Tool Kit%@AE@%%@AI@% %@AI@%discusses memory models.%@AE@%%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080006 @%%@AB@%Initializing a Pointer Variable%@AE@%%@EH@%%@NL@% %@NL@% The next step in the POINTER.C program is to initialize the pointer variable %@AS@% ptr%@AE@%, making it point to some meaningful address in memory: %@NL@% %@NL@% %@AS@% ptr = &val;%@AE@%%@NL@% %@NL@% The "address-of operator" (%@AB@%&%@AE@%) gives the address of the name it precedes. So in plain English the above statement says, "assign the address of %@AS@% val %@AE@% to %@AS@% %@AS@%ptr%@AE@%." %@NL@% %@NL@% After its initialization, the variable %@AS@% ptr %@AE@% points to %@AS@% val %@AE@% in the sense that it contains the address where %@AS@% val %@AE@% is stored. %@NL@% %@NL@% The output from POINTER.C shows that %@AS@% ptr %@AE@% contains the address of %@AS@% val%@AE@%. First it prints the address of %@AS@% val %@AE@% using the address-of operator to directly obtain the variable's address, %@NL@% %@NL@% %@AS@% &val = 5308%@AE@%%@NL@% %@NL@% then it prints the contents of %@AS@% ptr%@AE@%: %@AS@% %@AE@%%@NL@% %@NL@% %@AS@% ptr = 5308%@AE@%%@NL@% %@NL@% The two values are identical. Figure 8.2 shows the relationship of %@AS@% val %@AE@% and %@AS@% ptr %@AE@% at this stage in the POINTER.C program. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Initialization is especially important for pointers because, as noted earlier, they have the potential to point anywhere in memory. If you forget to initialize it, or make it point to the wrong place, a pointer can wreak havoc with your program or even the operating system itself. %@NL@% %@NL@% %@AU@% The target of a pointer must be present in memory at run time.%@AE@% %@NL@% %@NL@% The pointer in POINTER.C points to a simple %@AB@%int%@AE@% variable. As a general rule, pointers can point to any data object that is present in memory at run time. This category mainly includes objects for which the program allocates (sets aside) memory. Memory can be allocated implicitly, by defining a variable or function, or explicitly, by calling a memory-allocating library function such as %@AB@%malloc%@AE@%. %@NL@% %@NL@% A pointer can't point to program elements such as expressions or %@AB@%register%@AE@% variables, which aren't present in addressable memory. %@NL@% %@NL@% POINTER.C initializes the pointer %@AS@% ptr %@AE@% by assigning it an address constant (the address of %@AS@% val%@AE@%, obtained with the address-of operator). You can also assign the value of one pointer to another, as shown here: %@NL@% %@NL@% %@AS@% ptr = ptr1;%@AE@%%@NL@% %@NL@% If %@AS@% ptr %@AE@% and %@AS@% ptr1 %@AE@% are both pointers, this statement assigns the address contained in %@AS@% ptr1 %@AE@% to %@AS@% ptr%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080007 @%%@AB@%Using a Pointer Variable%@AE@%%@EH@%%@NL@% %@NL@% Once %@AS@% ptr %@AE@% points to %@AS@% val%@AE@%, we have two ways to access the %@AB@%int%@AE@% value stored in %@AS@% val%@AE@%. The usual way is direct, using the name of %@AS@% val%@AE@%: %@NL@% %@NL@% %@AS@% printf( " val = %d\n", val );%@AE@%%@NL@% %@NL@% The second way to access %@AS@% val %@AE@% is indirect, using the pointer variable %@AS@% ptr %@AE@% and the indirection operator: %@NL@% %@NL@% %@AS@% printf( "*ptr = %d\n\n", *ptr );%@AE@%%@NL@% %@NL@% Both of the preceding statements print the value of %@AS@% val%@AE@%, confirming that you can access the contents of %@AS@% val %@AE@% indirectly as well as directly. Once %@AS@% %@AS@%ptr %@AE@% points to %@AS@% val %@AE@% you can use %@AS@% *ptr %@AE@% anywhere that you would use %@AS@% val%@AE@%. %@AS@% %@AE@%%@NL@% %@NL@% %@AU@% The indirection operator can obtain the value to which a pointer points.%@AE@% %@NL@% %@NL@% Using the indirection operator to access the contents of %@AS@% val %@AE@% is the second use of this operator (the first is in declaring pointer variables, as explained earlier). When the asterisk appears in front of the name %@AS@% ptr%@AE@%, the expression states that you want to use the %@AI@%value the pointer points to%@AE@%, not the value of %@AS@% ptr %@AE@% itself. %@NL@% %@NL@% The second %@AB@%printf%@AE@% statement in POINTER.C uses the expression %@AS@% *ptr %@AE@% to access the value stored in %@AS@% val%@AE@%. %@NL@% %@NL@% This use of a pointer is analogous to the %@AB@%PEEK%@AE@% function in QuickBASIC. You can just as easily use %@AS@% ptr %@AE@% to change the data in %@AS@% val%@AE@%, an operation that somewhat resembles a QuickBASIC %@AB@%POKE%@AE@% statement. %@NL@% %@NL@% For instance, if you add the following statements to the end of POINTER.C, %@NL@% %@NL@% %@AS@% *ptr = 3301; %@AS@% printf( "%d\n", val );%@AE@%%@NL@% %@NL@% the program prints %@AS@% 3301%@AE@%. %@NL@% %@NL@% Figure 8.3 shows the relationship between %@AS@% ptr %@AE@% and %@AS@% val %@AE@% after executing the previous two statements. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% As Figure 8.3 shows, the value stored in %@AS@% val %@AE@% has changed from 25 to 3301. The contents of %@AS@% val %@AE@% were changed indirectly, through the pointer %@AS@% ptr%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080008 @%%@AB@%Summary of Pointer Basics%@AE@%%@EH@%%@NL@% %@NL@% In the preceding sections, you have seen how to do these operations: %@NL@% %@NL@% %@NL@% ■ Declare a pointer to a simple variable%@NL@% %@NL@% ■ Initialize a pointer, making it point to a variable%@NL@% %@NL@% ■ Use a pointer to get the value of a variable%@NL@% %@NL@% ■ Use a pointer to change the contents of a variable%@NL@% %@NL@% %@NL@% It's important for you to be comfortable with these basic ideas before reading about the more advanced uses of pointers. If you're not sure you understand these concepts, you may want to experiment with the POINTER.C program to reinforce what you know. For instance, you might add some new variables of different types and create new pointers to access them. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00080009 @%%@AB@%Pointers to Arrays%@AE@%%@EH@%%@NL@% %@NL@% Pointers and arrays are closely related in C─a major theme we'll elaborate throughout the rest of this chapter and Chapter 9, "Advanced Pointers." This section explains one of the simpler ways to use pointers with arrays. %@NL@% %@NL@% A pointer to an array, or "array pointer," combines two powerful language features─the pointer's ability to provide indirect access and the convenience of accessing array elements through numerical subscripts. %@NL@% %@NL@% %@AU@% An array pointer can point to any element in a given array.%@AE@% %@NL@% %@NL@% A pointer to an array is not much different than a pointer to a simple variable. In both cases, the pointer can point only to a single object at any given time. An array pointer, however, can reference any individual element within an array (but just one at a time). %@NL@% %@NL@% The program PARRAY.C shows how to access the elements of an %@AB@%int%@AE@% array through a pointer: %@NL@% %@NL@% %@AS@% /* PARRAY.C: Demonstrate pointer to array. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% int i_array[] = { 25, 300, 2, 12 }; %@AS@% %@AS@% main() %@AS@% { %@AS@% int *ptr; %@AS@% int count; %@AS@% ptr = &i_array[0];%@AE@%%@NL@% %@NL@% %@AS@% for( count = 0; count < 4 ; count++ ) { %@AS@% printf( "i_array[%d] = %d\n", count, *ptr ); %@AS@% ptr++; %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from PARRAY.C: %@NL@% %@NL@% %@AS@% i_array[0] = 25 %@AS@% i_array[1] = 300 %@AS@% i_array[2] = 2 %@AS@% i_array[3] = 12%@AE@%%@NL@% %@NL@% The PARRAY.C program creates a four-element %@AB@%int%@AE@% array named %@AS@% i_array%@AE@%. Then it declares a pointer named %@AS@% ptr %@AE@% and uses %@AS@% ptr %@AE@% in a %@AB@%for%@AE@% loop to access each of the elements in %@AS@% i_array%@AE@%. %@NL@% %@NL@% Notice the similarity between PARRAY.C and the previous example (POINTER.C). The pointer is declared in the same way: %@NL@% %@NL@% %@AS@% int *ptr;%@AE@%%@NL@% %@NL@% As noted before, this declaration states that %@AS@% ptr %@AE@% can point to any object of the %@AB@%int%@AE@% type, which includes an element in an %@AB@%int%@AE@% array as well as a simple %@AB@%int%@AE@%. The initialization of %@AS@% ptr %@AE@% looks similar, too: %@NL@% %@NL@% %@AS@% ptr = &i_array[0];%@AE@%%@NL@% %@NL@% This statement assigns %@AS@% ptr %@AE@% the address of the first element of %@AS@% i_array%@AE@%, which is %@AS@% i_array[0]%@AE@%. (There's a more compact way to initialize this pointer, but we'll defer that discussion for a moment.) Figure 8.4 shows the relationship between %@AS@% ptr %@AE@% and %@AS@% i_array %@AE@% immediately after %@AS@% ptr %@AE@% is initialized. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080010 @%%@AB@%Arrays and Pointer Arithmetic%@AE@%%@EH@%%@NL@% %@NL@% Once a pointer points to an array, it can access any of the array's elements. By adding or subtracting from the pointer's value (using "pointer arithmetic") you can access any element in the array, just as you can access it with array subscripts. %@NL@% %@NL@% So in PARRAY.C, just as in POINTER.C, we can use %@AS@% *ptr %@AE@% to access the %@AB@%int%@AE@% value that %@AS@% ptr %@AE@% references. The only difference is now %@AS@% ptr %@AE@% points to an array element instead of a simple variable. %@NL@% %@NL@% When the %@AB@%for%@AE@% loop in PARRAY.C executes the first time, %@AS@% ptr %@AE@% points to the first element of %@AS@% i_array%@AE@%, which is %@AS@% i_array[0]%@AE@%. The second statement in the loop body, %@NL@% %@NL@% %@AS@% ptr++;%@AE@%%@NL@% %@NL@% increments the pointer. Now %@AS@% ptr %@AE@% points to the next element in %@AS@% i_array%@AE@%, which is %@AS@% i_array[1]%@AE@%. Figure 8.5 shows the relationship of %@AS@% ptr %@AE@% and %@AS@% %@AS@%i_array %@AE@% after the first iteration of the %@AB@%for%@AE@% loop in PARRAY.C. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Figures 8.4 and 8.5 illustrate another important fact about pointers. Pointer arithmetic is automatically scaled to the size of the object that a pointer references. As explained above, incrementing %@AS@% ptr %@AE@% with the statement %@AS@% %@AE@%%@NL@% %@NL@% %@AS@% ptr++;%@AE@%%@NL@% %@NL@% %@AU@% Pointer arithmetic is scaled to the size of elements in an array.%@AE@% %@NL@% %@NL@% moves the pointer forward to the next %@AI@%element%@AE@% in %@AS@% i_array%@AE@%. Since each element of an %@AB@%int%@AE@% array contains two bytes, this operation actually adds 2 to the address stored in %@AS@% ptr%@AE@%, but you don't have to worry about that detail. The compiler knows the size of the elements in the array and adjusts the pointer accordingly. %@NL@% %@NL@% Incrementing a pointer adds 1 if it points to a %@AB@%char%@AE@% array, 4 if it points to a %@AB@%float%@AE@% array, and so on. %@NL@% %@NL@% You can also decrement an array pointer. If %@AS@% ptr %@AE@% points to %@AS@% i_array[2]%@AE@%, this statement moves the pointer back one element, to %@AS@% i_array[1]%@AE@%: %@NL@% %@NL@% %@AS@% ptr--;%@AE@%%@NL@% %@NL@% Although the previous expressions increment and decrement %@AS@% ptr %@AE@% by 1, you can add or subtract any integer value from a pointer. For instance, the following statement moves %@AS@% ptr %@AE@% forward three elements in %@AS@% i_array%@AE@%: %@NL@% %@NL@% %@AS@% ptr += 3;%@AE@%%@NL@% %@NL@% Be careful not to overrun the bounds of an array when accessing its elements with a pointer. As noted in Chapter 4, "Data Types," the C language doesn't check array subscripts. This rule applies equally when you access an array with a pointer, which can potentially reference any address in memory. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% The C language does not check array pointer references. If you increment or decrement a pointer past the limits of an array, you can corrupt other parts of your program or cause other unexpected results.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% It's your job to make sure an increment or decrement doesn't move a pointer outside the memory where an array is stored. For instance, if you decrement %@AS@% %@AS@%ptr %@AE@% when it points to %@AS@% i_array[0]%@AE@%, it will point to whatever happens to be stored in the %@AB@%int%@AE@%-size memory area %@AI@%below%@AE@% the element %@AS@% i_array[0]%@AE@%. %@NL@% %@NL@% Most pointer arithmetic occurs in connection with arrays, where a numerical index has obvious utility. It's not illegal to do pointer arithmetic on nonarray pointers, but such operations normally serve no purpose. For instance, if you increment a pointer to a simple variable, the pointer no longer points to the variable and becomes useless. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080011 @%%@AB@%Comparing Pointers%@AE@%%@EH@%%@NL@% %@NL@% The special nature of a pointer variable─the fact that it contains an address─ precludes most operations that are legal for other variables. There's no such thing as a fractional memory address, for example. So it wouldn't make sense to divide a pointer, or add a floating-point number to it. The most common pointer operations are assignment, incrementing, and decrementing, as described earlier. You can also compare one pointer to another. %@NL@% %@NL@% If a program allocates memory for a stack, for instance, you might create two pointers that point to different parts of the stack. One pointer can show where the stack begins and the other where it ends. To see how much of the stack is in use, you can subtract the pointers. (A "stack" is a memory area used for temporary storage.) %@NL@% %@NL@% %@AU@% You can compare pointer variables with relational operators or by %@AU@%subtraction.%@AE@% %@NL@% %@NL@% Pointer comparisons can be done with relational operators (such as %@AB@%%@AE@% ) or by subtracting one pointer from another. Of course, pointer comparisons are meaningful only for pointers that point to the same data object or related objects of the same type. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080012 @%%@AB@%PARRAY.C Revisited%@AE@%%@EH@%%@NL@% %@NL@% Before leaving the PARRAY.C program, we should note that most C programmers would write it more compactly (PARRAY1.C): %@NL@% %@NL@% %@AS@% /* PARRAY1.C: Compact version of PARRAY.C. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% int i_array[] = { 25, 300, 2, 12 }; %@AS@% %@AS@% main() %@AS@% { %@AS@% int count; %@AS@% int *ptr = i_array; %@AS@% for( count = 0; count < 4 ; count++ ) %@AS@% printf( "i_array[%d] = %d\n", count, *ptr++ ); %@AS@% }%@AE@%%@NL@% %@NL@% %@AU@% You can declare and initialize a pointer variable in one statement.%@AE@% %@NL@% %@NL@% The PARRAY1.C program uses several shorthand techniques you can expect to see in C programs. Like other variables, pointers can be initialized at the same time they are declared. The following statement in PARRAY1.C performs both operations: %@NL@% %@NL@% %@AS@% int *ptr = i_array;%@AE@%%@NL@% %@NL@% The statement above is equivalent to these statements: %@NL@% %@NL@% %@AS@% int *ptr; %@AS@% ptr = i_array;%@AE@%%@NL@% %@NL@% You may have noticed another difference in the way %@AS@% ptr %@AE@% is initialized. The PARRAY1.C program omits the address-of operator and array subscript that PARRAY.C used to signify the address of the first element of %@AS@% i_array%@AE@%. Instead of %@NL@% %@NL@% %@AS@% &i_array[0]%@AE@%%@NL@% %@NL@% the program uses %@NL@% %@NL@% %@AS@% i_array%@AE@%%@NL@% %@NL@% %@AU@% An array name is a pointer.%@AE@% %@NL@% %@NL@% In fact, the two expressions are equivalent. In the C language, the name of an array is actually a pointer. Any array name that doesn't have a subscript is interpreted as a pointer to the base address of the array. (The "base address" is the address of the array's first element.) We'll explore this equivalence further in the following sections and in Chapter 9, "Advanced Pointers." %@NL@% %@NL@% Finally, PARRAY1.C uses the expression %@AS@% *ptr++ %@AE@% to perform two jobs: accessing the value %@AS@% ptr %@AE@% points to and incrementing %@AS@% ptr%@AE@%. Note the order in which the two operators in this expression take effect. The indirection operator takes effect first, accessing the value of the array element that %@AS@% %@AS@%ptr %@AE@% currently points to. Then the increment operator (%@AB@%++%@AE@%) adds 1 to %@AS@% ptr%@AE@%, making it point to the next element in %@AS@% i_array%@AE@%. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00080013 @%%@AB@%Pointers and Strings%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% String pointers are handled like other array pointers.%@AE@% %@NL@% %@NL@% Because a string is an array of characters, pointers to strings are handled much like other array pointers. The program PSTRING.C is similar to the examples that demonstrated array pointers (PARRAY.C and PARRAY1.C). It uses a pointer to access a %@AB@%char%@AE@% array: %@NL@% %@NL@% %@AS@% /* PSTRING.C: Demonstrate pointer to a string. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int count; %@AS@% char name[] = "john"; %@AS@% char *ptr = name; %@AS@% for( count = 0; count < 4; count++ ) %@AS@% { %@AS@% printf( "name[%d]: %c\n", count, *ptr++ ); %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% The PSTRING.C program steps through the %@AS@% name %@AE@% array, printing each character in turn: %@NL@% %@NL@% %@AS@% name[0]: j %@AS@% name[1]: o %@AS@% name[2]: h %@AS@% name[3]: n%@AE@%%@NL@% %@NL@% The notable difference between PARRAY.C and PSTRING.C is that PSTRING.C has a %@AB@%char%@AE@% array instead of an %@AB@%int%@AE@% array. Again, incrementing an array pointer moves the pointer to the next array element. So in PSTRING.C each iteration of the %@AB@%for%@AE@% loop moves the pointer to the next %@AB@%char%@AE@% in the string. %@NL@% %@NL@% The first time through the loop, %@AS@% ptr %@AE@% points to %@AS@% name[0]%@AE@%. The second time it points to %@AS@% name[1]%@AE@%, and so on. %@NL@% %@NL@% As mentioned in Chapter 4, "Data Types," one difference between strings and noncharacter arrays is that strings end with a null character. The string in PSTRING.C actually contains five characters: four letters and a null character. We can exploit this fact to simplify the program, as we do below in PSTRING.C. %@NL@% %@NL@% %@AS@% /* PSTRING1.C: Look for null at string's end. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% char name[] = "john"; %@AS@% char *ptr = name; %@AS@% while( *ptr ) %@AS@% printf( "*ptr = %c\n", *ptr++ ); %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from PSTRING1.C: %@NL@% %@NL@% %@AS@% *ptr = j %@AS@% *ptr = o %@AS@% *ptr = h %@AS@% *ptr = n%@AE@%%@NL@% %@NL@% Like PSTRING.C, the PSTRING1.C program steps through the array one character at a time. However, it replaces the %@AB@%for%@AE@% loop with a simpler %@AB@%while%@AE@% loop. The test expression in the %@AB@%while%@AE@% loop, %@NL@% %@NL@% %@AS@% while( *ptr )%@AE@%%@NL@% %@NL@% is evaluated as true until %@AS@% ptr %@AE@% points to the null character that terminates the string. It's a more compact way of writing this expression: %@NL@% %@NL@% %@AS@% while( *ptr != 0 )%@AE@%%@NL@% %@NL@% %@AU@% Any operation done with array subscripts can also be done with pointer %@AU@%notation.%@AE@% %@NL@% %@NL@% This is an ideal time to elaborate on the relationship between arrays and pointers. Any operation you can do with conventional array notation (subscripts) can also be done with pointers. This is possible because an array name, as we noted earlier, is itself a pointer. %@NL@% %@NL@% To illustrate, the PSTRING2.C program uses only array notation: %@NL@% %@NL@% %@AS@% /* PSTRING2.C: Demonstrate strings and array notation. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <string.h>%@AE@%%@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% int count; %@AS@% char name[] = "john"; %@AS@% for( count = 0; count < strlen( name ); count++ ) %@AS@% printf( "name[%d]: %c\n", count, name[count] ); %@AS@% }%@AE@%%@NL@% %@NL@% PSTRING2.C gives the same output as PSTRING.C. In this program, the expression %@NL@% %@NL@% %@AS@% name[count]%@AE@%%@NL@% %@NL@% uses %@AS@% count %@AE@% as in an index to the %@AS@% name %@AE@% array. %@NL@% %@NL@% PSTRING3.C is the same program written with pointer notation: %@NL@% %@NL@% %@AS@% /* PSTRING3.C: Strings and pointer notation. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <string.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int count; %@AS@% char name[] = "john"; %@AS@% for( count = 0; count < strlen( name ); count++ ) %@AS@% printf( "*(name+%d) = %c\n", count,*(name+count) ); %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from PSTRING3.C: %@NL@% %@NL@% %@AS@% *(name+0) = j %@AS@% *(name+1) = o %@AS@% *(name+2) = h %@AS@% *(name+3) = n%@AE@%%@NL@% %@NL@% Notice how PSTRING3.C replaces the expression %@NL@% %@NL@% %@AS@% name[count]%@AE@%%@NL@% %@NL@% with the expression: %@NL@% %@NL@% %@AS@% *(name+count)%@AE@%%@NL@% %@NL@% Both expressions use the variable %@AS@% count %@AE@% as an offset from the base address of the array. The parentheses in the second expression are important. They are necessary because the indirection operator takes effect before the addition operator. If you omit the parentheses, as in %@NL@% %@NL@% %@AS@% *name+count%@AE@%%@NL@% %@NL@% the expression has the same effect as %@NL@% %@NL@% %@AS@% (*name)+count%@AE@%%@NL@% %@NL@% which adds the value of %@AS@% count %@AE@% to the object %@AS@% name %@AE@% references. %@NL@% %@NL@% In summary, the examples in this section show three alternative ways to access a character inside a string. In the %@AB@%printf%@AE@% statements in the examples, these expressions are equivalent: %@NL@% %@NL@% %@AS@% *ptr %@AE@%%@NL@% %@NL@% %@AS@% name[count]%@AE@%%@NL@% %@NL@% %@AS@% *(name+count)%@AE@%%@NL@% %@NL@% Many C programmers prefer pointer notation to array notation because pointers are faster for some operations. In other cases─including the one above─the choice is entirely one of taste. There's more to say about the relationship between pointers and arrays. We'll return to this topic later in this chapter and in Chapter 9, "Advanced Pointers." %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00080014 @%%@AB@%Passing Pointers to Functions%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A function that receives pointers can access variables that are local to %@AU@%other functions.%@AE@% %@NL@% %@NL@% One of the most common uses of pointers is to pass them as arguments to functions. Functions that receive variables as parameters get local copies of those variables, not the originals. In contrast, functions that receive pointers to variables gain access to the original variables associated with the pointers. This allows the functions to %@NL@% %@NL@% %@NL@% ■ Return more than one value%@NL@% %@NL@% ■ Read and change values in variables─including arrays and structures─that otherwise aren't visible to the function%@NL@% %@NL@% %@NL@% The first item listed above relates to the %@AB@%return%@AE@% statement. As we noted in Chapter 2, "Functions," a function can return only one value through %@AB@%return%@AE@%. How-ever, it's not difficult to imagine a useful function─a sort, for instance─that would return more than one value. Pointers offer an elegant solution. %@NL@% %@NL@% The second item involves visibility. Most variables in C programs are local to the functions where they are defined, and a function normally can't access local variables in other functions. There are times, however, when you want a function to have access to a local variable defined elsewhere in the program. By passing the function a pointer to the local variable, you can give it access to the variable itself. %@NL@% %@NL@% The PFUNC.C program illustrates both ideas. It has a function that returns more than one value and uses pointers to alter variables that aren't visible within the function: %@NL@% %@NL@% %@AS@% /* PFUNC.C: Pass pointers to a function. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% void swap( int *ptr1, int *ptr2 ); %@AS@% %@AS@% main() %@AS@% { %@AS@% int first = 1, second = 3; %@AS@% int *ptr = &second; %@AS@% printf( "first: %d second: %d\n", first, *ptr ); %@AS@% swap( &first, ptr ); %@AS@% printf( "first: %d second: %d\n", first, *ptr ); %@AS@% } %@AS@% %@AS@% void swap( int *ptr1, int *ptr2 ) %@AS@% { %@AS@% int temp; %@AS@% temp = *ptr1; %@AS@% *ptr1 = *ptr2; %@AS@% *ptr2 = temp; %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from PFUNC.C: %@NL@% %@NL@% %@AS@% first: 1 second: 3 %@AS@% first: 3 second: 1%@AE@%%@NL@% %@NL@% %@AU@% Pointers can eliminate the need for external variables.%@AE@% %@NL@% %@NL@% The PFUNC.C program swaps the values of two %@AB@%int%@AE@% variables named %@AS@% first %@AE@% and %@AS@% %@AS@%second%@AE@%, using a function named %@AS@% swap%@AE@%. Since the exchange involves two values, the %@AS@% swap %@AE@% function can't use %@AB@%return%@AE@% to communicate its results. More-over, the variables %@AS@% first %@AE@% and %@AS@% second %@AE@% are defined only in the %@AB@%main%@AE@% function, and as good C programmers, we want to exchange their values without making them externally visible. %@NL@% %@NL@% The prototype for the %@AS@% swap %@AE@% function shows that %@AS@% swap %@AE@% expects to receive two pointers to %@AB@%int%@AE@% variables: %@NL@% %@NL@% %@AS@% void swap( int *ptr1, int *ptr2 );%@AE@%%@NL@% %@NL@% Notice the use of %@AB@%void%@AE@% in the prototype and function definition. The %@AB@%void%@AE@% specifier shows that the %@AS@% swap %@AE@% function doesn't return any value through a %@AB@%return%@AE@% statement. Instead, %@AS@%swap %@AE@% returns its results indirectly, through the action of pointers. %@NL@% %@NL@% The variables we want to exchange are defined only in %@AB@%main%@AE@%: %@NL@% %@NL@% %@AS@% int first = 1, second = 3;%@AE@%%@NL@% %@NL@% No other function in the program can access these variables directly by using the variable names %@AS@% first %@AE@% and %@AS@% second%@AE@%. We must pass these variables as arguments; but since the C language passes arguments by value, we need to pass pointers to the variables. %@NL@% %@NL@% The %@AB@%main%@AE@% function calls %@AS@% swap %@AE@% with the following statement: %@NL@% %@NL@% %@AS@% swap( &first, ptr );%@AE@%%@NL@% %@NL@% This statement shows two different ways to pass a pointer to a function. The first argument in the function call, %@AS@% %@AE@%%@NL@% %@NL@% %@AS@% &first %@AE@%%@NL@% %@NL@% passes the address of first as a constant, using the address-of operator. The second argument,%@AS@% %@AE@%%@NL@% %@NL@% %@AS@% ptr%@AE@%%@NL@% %@NL@% passes the address of %@AS@% second %@AE@% with a pointer variable. Earlier in PFUNC.C we declared %@AS@% ptr %@AE@% as a pointer to an %@AB@%int%@AE@% and assigned it the address of %@AS@% %@AS@%second%@AE@%: %@NL@% %@NL@% %@AS@% int *ptr = &second;%@AE@%%@NL@% %@NL@% Both arguments pass the same kind of data─the address of a local variable─to the function. We'll return to this idea after we see how the rest of PFUNC.C works. %@NL@% %@NL@% When the %@AS@% swap %@AE@% function executes, it creates two %@AB@%int%@AE@% pointers named %@AS@% ptr1 %@AE@% and %@AS@% ptr2 %@AE@% and assigns the passed addresses to them: %@NL@% %@NL@% %@AS@% void swap( int *ptr1, int *ptr2 )%@AE@%%@NL@% %@NL@% Since there's a one-to-one correspondence between arguments and parameters, the pointer %@AS@% ptr1 %@AE@% receives the address of %@AS@% first %@AE@% and %@AS@% ptr2 %@AE@% receives the address of %@AS@% second%@AE@%. The %@AS@% swap %@AE@% function exchanges the values of %@AS@% first %@AE@% and %@AS@% %@AS@%second%@AE@%, using the two pointers and a temporary %@AB@%int%@AE@% variable named %@AS@% temp%@AE@%: %@NL@% %@NL@% %@AS@% int temp; %@AS@% temp = *ptr1; %@AS@% *ptr1 = *ptr2; %@AS@% *ptr2 = temp;%@AE@%%@NL@% %@NL@% Within the %@AS@% swap %@AE@% function, PFUNC.C uses the indirection operator to access the values that %@AS@% ptr1 %@AE@% and %@AS@% ptr2 %@AE@% reference. The expression %@AS@% *ptr1 %@AE@% accesses the value stored in %@AS@% first%@AE@%. Likewise, the expression %@AS@% *ptr2 %@AE@% accesses the value stored in %@AS@% second%@AE@%. %@NL@% %@NL@% Through the addresses contained in the pointers, the %@AS@% swap %@AE@% function can indirectly access variables that are local to the %@AB@%main%@AE@% function. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00080015 @%%@AB@%Passing Address Constants Versus Passing Pointer Variables%@AE@%%@EH@%%@NL@% %@NL@% Now that you know how the %@AS@% swap %@AE@% function works, we can elaborate on the two methods that PFUNC.C uses to pass the address of %@AS@% first %@AE@% and %@AS@% second %@AE@% to %@AS@% %@AS@%swap%@AE@%. %@NL@% %@NL@% %@AU@% When you pass a pointer to a function, the function actually receives an %@AU@%address.%@AE@% %@NL@% %@NL@% Earlier, we said the %@AS@% swap %@AE@% function expects to receive two pointers as parameters. While it's common to say pointers in this context, it would be more accurate to say the function expects addresses, since that's what it actually receives. %@NL@% %@NL@% To work correctly, %@AS@% swap %@AE@% only needs the addresses of two variables. Once it has the addresses, it assigns them to its own local pointers and proceeds to do its work─modifying the original variables at long distance, as it were. The %@AS@% swap %@AE@% function doesn't care whether you pass the addresses as constants or pointer variables, since it receives the same kind of value in either case. The address is all the function needs to change the value of a variable defined elsewhere. %@NL@% %@NL@% The first argument in the function call to %@AS@% swap %@AE@% shows a straightforward way to pass an address. Inside the %@AB@%main%@AE@% function of PFUNC.C, the expression %@AS@% %@AS@%&first %@AE@% equals the address of %@AS@% first%@AE@%. When you pass this argument to %@AS@% swap%@AE@%, the function clearly receives an address. %@NL@% %@NL@% The second argument is an address, too. Since %@AB@%main%@AE@% assigns the address of %@AS@% %@AS@%second %@AE@% to the pointer variable %@AS@% ptr%@AE@%, the expression %@AS@% ptr %@AE@% equals the address of %@AS@%second%@AE@%. When you pass this argument to %@AS@% swap%@AE@%, the function also receives an address. (Remember, the value contained in a pointer variable is an address.) %@NL@% %@NL@% Some beginning programmers get confused by functions that expect to receive pointers, thinking they must always pass pointer %@AI@%variables%@AE@% to such functions. As PFUNC.C shows, if the function expects an address you can simply pass the address as a constant, using the address-of operator. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%When a function expects to receive an address as a parameter, you can pass %@AI@%either an address constant or a pointer variable, whichever is more %@AI@%suitable.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% Why, then, would you ever go to the trouble of passing a pointer variable to this kind of function? In a real program, the function that calls %@AS@% swap %@AE@% might well use pointers to process %@AS@% first %@AE@% and %@AS@% second %@AE@% for some other purpose. In such a case you might prefer to use pointers in the function call, too. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00080016 @%%@AB@%Arrays of Pointers%@AE@%%@EH@%%@NL@% %@NL@% Pointers, like other variables, can be stored in arrays. This feature allows you to create a variety of useful data structures. %@NL@% %@NL@% %@AU@% In an array of pointers, each array element is a pointer variable.%@AE@% %@NL@% %@NL@% If you find an array of pointers hard to picture, begin with the idea that an array is a group of variables of the same type. An "array of pointers" is also a group of variables, but instead of simple variables, it contains a group of pointer variables. %@NL@% %@NL@% Each element in an array of pointers, then, is a pointer that contains an address. Like other array elements, each element can be accessed with a numerical subscript. %@NL@% %@NL@% Pointer arrays are often used to speed up sorts. The QCSORT.C program shows the basic idea behind such a sort: %@NL@% %@NL@% %@AS@% /* QCSORT.C: Demonstrate sorting array of pointers. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #define SIZE 4 %@AS@% %@AS@% void sort( int size, double *p[] ); %@AS@% void show( int size, double *p[], double dd[] ); %@AS@% %@AS@% main() %@AS@% { %@AS@% int x; %@AS@% double d[] = { 3.333, 1.111, 2.222, 4.444 }; %@AS@% double *d_ptr[SIZE]; %@AS@% for( x = 0; x < SIZE; x++ ) %@AS@% d_ptr[x] = &d[x]; %@AS@% show( SIZE, d_ptr, d ); %@AS@% sort( SIZE, d_ptr ); %@AS@% show( SIZE, d_ptr, d ); %@AS@% } %@AS@% %@AS@% void sort( int size, double *p[] ) %@AS@% { %@AS@% int x, x1; %@AS@% double *temp; %@AS@% for( x = 0; x < size - 1; x++ ) %@AS@% for( x1 = x + 1; x1 < size; x1++ ) %@AS@% { %@AS@% if( *p[x] > *p[x1] ) %@AS@% { %@AS@% temp = p[x1]; %@AS@% p[x1] = p[x]; %@AS@% p[x] = temp; %@AS@% } %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% %@AS@% void show( int size, double *p[], double dd[] ) %@AS@% { %@AS@% int x; %@AS@% printf( "------------------------" ); %@AS@% printf( "------------------------\n" ); %@AS@% for( x = 0; x < size; x++ ) %@AS@% { %@AS@% printf( "*d_ptr[%d] = %1.3f ", x, *p[x]); %@AS@% printf( "d_ptr[%d] = %u ", x, p[x]); %@AS@% printf( " d[%d] = %1.3f\n", x, dd[x] ); %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from QCSORT.C: %@NL@% %@NL@% %@AS@% ------------------------------------------------ %@AS@% *d_ptr[0] = 3.333 d_ptr[0] = 66 d[0] = 3.333 %@AS@% *d_ptr[1] = 1.111 d_ptr[1] = 74 d[1] = 1.111 %@AS@% *d_ptr[2] = 2.222 d_ptr[2] = 82 d[2] = 2.222 %@AS@% *d_ptr[3] = 4.444 d_ptr[3] = 90 d[3] = 4.444 %@AS@% ------------------------------------------------ %@AS@% *d_ptr[0] = 1.111 d_ptr[0] = 74 d[0] = 3.333 %@AS@% *d_ptr[1] = 2.222 d_ptr[1] = 82 d[1] = 1.111 %@AS@% *d_ptr[2] = 3.333 d_ptr[2] = 66 d[2] = 2.222 %@AS@% *d_ptr[3] = 4.444 d_ptr[3] = 90 d[3] = 4.444%@AE@%%@NL@% %@NL@% Since the purpose of QCSORT.C is to demonstrate pointers, not sorting methods, it uses a simple bubble sort. This method isn't efficient but has the advantage of being short and easy to follow. %@NL@% %@NL@% The QCSORT.C program creates a %@AB@%double%@AE@% array named %@AS@% d %@AE@% and an array of pointers named %@AS@% d_ptr%@AE@%. Each array has four elements. To illustrate the sort, the elements of %@AS@% d %@AE@% are initialized out of order. %@NL@% %@NL@% The goal of QCSORT.C is to display a sorted list of the values in %@AS@% d%@AE@%. You could do this by sorting the elements of %@AS@% d %@AE@% itself, but that solution is not efficient. Every %@AB@%double%@AE@% value contains eight bytes, and sorting a large number of %@AB@%double%@AE@% values requires that you move a lot of memory. %@NL@% %@NL@% Instead of moving the %@AB@%double%@AE@% values themselves, QCSORT.C creates an array of pointers that point to the elements of the %@AS@% d %@AE@% array, then sorts the pointers. This saves time because a pointer is stored in only two bytes. Figure 8.6 shows the relationship between the %@AS@% d %@AE@% and %@AS@% d_ptr %@AE@% arrays immediately after both are initialized. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% At the stage shown in Figure 8.6, the pointers in the %@AS@% d_ptr %@AE@% array have been initialized to point to the %@AB@%double%@AE@% elements in the %@AS@% d %@AE@% array. (The array element %@AS@% d_ptr[0] %@AE@% points to %@AS@% d[0]%@AE@%, %@AS@% d_ptr[1] %@AE@% points to %@AS@% d[1]%@AE@%, and so on.) The function %@AS@% show %@AE@% displays three sets of data: %@NL@% %@NL@% %@NL@% ■ The value each pointer references%@NL@% %@NL@% ■ The address assigned to each pointer%@NL@% %@NL@% ■ The value of each element in the %@AS@% d %@AE@% array%@NL@% %@NL@% %@NL@% After calling the %@AS@% show %@AE@% function, QCSORT.C calls the %@AS@% sort %@AE@% function, which sorts the pointers in %@AS@% d_ptr%@AE@%. %@NL@% %@NL@% The declaration of %@AS@% sort %@AE@% contains something new. In the declaration %@NL@% %@NL@% %@AS@% void sort( int size, double *p[] );%@AE@%%@NL@% %@NL@% the expression %@AS@% *p[] %@AE@% shows that the %@AS@% sort %@AE@% function expects to receive a %@AI@%pointer to an array of pointers%@AE@%. When the program calls %@AS@% sort%@AE@%, it passes the size of the array to be sorted (first argument) and a pointer to the array of pointers (second argument): %@NL@% %@NL@% %@AS@% sort( SIZE, d_ptr );%@AE@%%@NL@% %@NL@% Now the %@AS@% sort %@AE@% function has all the information it needs to sort the pointers in the %@AS@% d_ptr %@AE@% array, making each pointer point to the correct element in the %@AS@% d %@AE@% array. %@NL@% %@NL@% After the sort is complete, QCSORT.C calls %@AS@% show %@AE@% again to display the results of the sort. Now that the pointers have been sorted, they can be used to display a sorted list of %@AB@%double%@AE@% values. Figure 8.7 shows the relationship between the %@AS@% d %@AE@% and %@AS@% d_ptr %@AE@% arrays after the sort is complete. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Of course, the array in QCSORT.C is so small that the time savings from using pointers is negligible. In a real program, however, which might sort thousands of values instead of four, the difference between moving eight bytes and two bytes can be dramatic. The advantage of sorting pointers is even greater when sorting large data objects such as strings or structures. %@NL@% %@NL@% %@AU@% The elements in a pointer array can point to any type of data.%@AE@% %@NL@% %@NL@% The QCSORT.C example section uses a fairly simple array of pointers. But you can use such arrays to create quite complex data structures. The basic form of the array is always the same─it is a group of pointer variables, each pointer accessible through a subscript─but the pointers in an array can point to any kind of data object. You can have an array of pointers to structures, an array of pointers to strings, and so on. The only difference is in what the pointers reference. %@NL@% %@NL@% Don't confuse an array of pointers with a pointer to an array. A pointer to an array (or "array pointer") is a single pointer variable that points to an array element. The single pointer can access any element of the array, but only one pointer is involved. %@NL@% %@NL@% In contrast, an array of pointers is a group of related pointer variables stored in an array. Each element in the array is a pointer, and you can access individual pointers with the array name and subscript. Each pointer in the array points, in turn, to some other object. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00080017 @%%@AB@%A Pause for Reflection%@AE@%%@EH@%%@NL@% %@NL@% If this is your first exposure to pointers, you may want to reflect on what you have learned before reading the next chapter. This chapter has explained the basic uses of pointers, and you can write a great many useful programs using only these techniques. If you're not comfortable with all these ideas, you may want to experiment with them before reading more about pointers. %@NL@% %@NL@% The next chapter, "Advanced Pointers," examines further uses of pointers, including multiple indirection and pointers to structures. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00090001 @%%@1@%%@AB@%Chapter 9 Advanced Pointers%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% The preceding chapter, "Pointers," explained the basics of using pointers─ how to declare and initialize pointer variables and use them to access basic data types. This chapter explores more advanced pointer techniques, including multiple indirection, pointers to structures, and pointers to functions. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00090002 @%%@AB@%Pointers to Pointers%@AE@%%@EH@%%@NL@% %@NL@% In Chapter 8, "Pointers," we stated a pointer can point to any kind of variable. Since a pointer is a variable, you can make it the target of another pointer, creating a pointer to a pointer. This concept is useful in itself and is also important for understanding the equivalence of array notation and pointer notation, which is explained in the next section. %@NL@% %@NL@% The program PTRPTR.C demonstrates a pointer to a pointer insimple terms: %@NL@% %@NL@% %@AS@% /* PTRPTR.C: Demonstrate a pointer to a pointer. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int val = 501; %@AS@% int *ptr = &val; %@AS@% int **ptr_ptr = &ptr; %@AS@% printf( "val = %d\n", **ptr_ptr ); %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from PTRPTR.C: %@NL@% %@NL@% %@AS@% val = 501%@AE@%%@NL@% %@NL@% The first two statements in PTRPTR.C should look familiar by now. They create an %@AB@%int%@AE@% variable named %@AS@% val %@AE@% and an %@AB@%int%@AE@% pointer named %@AS@% ptr%@AE@%. The third line, however, requires some explanation: %@NL@% %@NL@% %@AS@% int **ptr_ptr = &ptr;%@AE@%%@NL@% %@NL@% This statement uses double indirection to create a variable named %@AS@% ptr_ptr%@AE@%, which is a pointer to a pointer. This pointer is assigned the address of the first pointer, %@AS@% ptr%@AE@%. The pointer %@AS@% ptr %@AE@% references %@AS@% val%@AE@%, and the pointer %@AS@% %@AS@%ptr_ptr %@AE@% references %@AS@% ptr%@AE@%. Figure 9.1 illustrates the relationship between %@AS@% %@AS@%ptr %@AE@% and %@AS@% ptr_ptr%@AE@%. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Once we have initialized both pointers, we can use %@AS@% ptr_ptr %@AE@% to access %@AS@% val%@AE@%: %@NL@% %@NL@% %@AS@% **ptr_ptr%@AE@%%@NL@% %@NL@% %@AU@% The double indirection operator (%@AE@%%@AB@% %@AE@%%@AB@%** %@AE@%) is used with a pointer to a pointer. %@NL@% %@NL@% The double indirection operator (%@AB@%**%@AE@%) in front of %@AS@% ptr_ptr %@AE@% tells two things about %@AS@%ptr_ptr%@AE@%: that %@AS@% ptr_ptr %@AE@% is itself a pointer and it points to a second pointer. Both asterisks are needed to access the contents of %@AS@% val%@AE@%. If you use only one, as in %@NL@% %@NL@% %@AS@% *ptr_ptr%@AE@%%@NL@% %@NL@% then %@AS@% ptr_ptr %@AE@% accesses the contents of %@AS@% ptr%@AE@%, which is the address of %@AS@% val%@AE@%. This statement, for instance, prints the address stored in %@AS@% ptr%@AE@%: %@NL@% %@NL@% %@AS@% printf( "ptr = %u", *ptr_ptr );%@AE@%%@NL@% %@NL@% Using pointers to pointers is known as "multiple indirection." One pointer points to a second pointer, which in turn accesses a third data object. In theory, there's no limit to how far you can take multiple indirection. You can create pointers to pointers, pointers to pointers to pointers, and so on. However, there's rarely any practical reason to carry indirection beyond two levels (a pointer to a pointer). %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090003 @%%@AB@%Equivalence of Array and Pointer Notation%@AE@%%@EH@%%@NL@% %@NL@% In previous sections we noted, more or less in passing, two important facts about arrays and pointers: %@NL@% %@NL@% %@NL@% 1. An array name is actually a pointer.%@NL@% %@NL@% 2. Array notation (subscripts) and pointer notation are interchangeable.%@NL@% %@NL@% %@NL@% These ideas are significant enough to warrant an explicit demonstration. Let's rewrite the QCSORT.C program using pointer notation: %@NL@% %@NL@% %@AS@% /* QCSORT1.C: Demonstrate sort with pointer notation. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #define SIZE 4 %@AS@% %@AS@% void sort( int size, double **p ); %@AS@% void show( int size, double **p, double dd[] ); %@AS@% %@AS@% main() %@AS@% { %@AS@% int x; %@AS@% double d[] = { 3.333, 1.111, 2.222, 4.444 }; %@AS@% double *d_ptr[SIZE]; %@AS@% for( x = 0; x < SIZE; x++ ) %@AS@% d_ptr[x] = &d[x]; %@AS@% show( SIZE, d_ptr, d ); %@AS@% sort( SIZE, d_ptr ); %@AS@% show( SIZE, d_ptr, d ); %@AS@% }%@AE@%%@NL@% %@NL@% %@AS@% void sort( int size, double **p ) %@AS@% { %@AS@% int x, x1; %@AS@% double *temp; %@AS@% for( x = 0; x < size - 1; x++ ) %@AS@% for( x1 = x + 1; x1 < size; x1++ ) %@AS@% { %@AS@% if( **(p+x) > **(p+x1) ) %@AS@% { %@AS@% temp = *(p+x1); %@AS@% *(p+x1) = *(p+x); %@AS@% *(p+x) = temp; %@AS@% } %@AS@% } %@AS@% } %@AS@% %@AS@% void show( int size, double **p, double dd[] ) %@AS@% { %@AS@% int x; %@AS@% printf( "------------------------" ); %@AS@% printf( "------------------------\n" ); %@AS@% for( x = 0; x < size; x++ ) %@AS@% { %@AS@% printf( "*d_ptr[%d] = %1.3f ", x, **(p+x) ); %@AS@% printf( "d_ptr[%d] = %u ", x, *(p+x) ); %@AS@% printf( " d[%d] = %1.3f\n", x, dd[x] ); %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% The QCSORT1.C program works like its predecessor, QCSORT.C. (It sorts an array of pointers that point to elements in an %@AB@%int%@AE@% array.) The only difference is QCSORT1.C uses pointer notation instead of array notation. %@NL@% %@NL@% Let's look at how the change affects the %@AS@% sort %@AE@% function, beginning with its prototype. In the previous program, QCSORT.C, the prototype %@NL@% %@NL@% %@AS@% void sort( int size, double *p[] );%@AE@%%@NL@% %@NL@% uses array notation to show we'll pass the name of an array of pointers to %@AS@% %@AS@%sort%@AE@%. Since an array name is a pointer, we can rewrite the prototype using pointer notation, as in QCSORT1.C: %@NL@% %@NL@% %@AS@% void sort( int size, double **p );%@AE@%%@NL@% %@NL@% The %@AS@% sort %@AE@% function definition is rewritten in the same way. Here is the definition of %@AS@% sort %@AE@% in the original program (QCSORT.C): %@NL@% %@NL@% %@AS@% void sort( int size, double *p[] ) %@AS@% { %@AS@% int x, x1; %@AS@% double *temp; %@AS@% for( x = 0; x < size - 1; x++ ) %@AS@% for( x1 = x + 1; x1 < size; x1++ ) %@AS@% { %@AS@% if( *p[x] > *p[x1] ) %@AS@% { %@AS@% temp = p[x1]; %@AS@% p[x1] = p[x]; %@AS@% p[x] = temp; %@AS@% } %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% The same function using pointers looks like this in QCSORT1.C: %@NL@% %@NL@% %@AS@% void sort( int size, double **p ) %@AS@% { %@AS@% int x, x1; %@AS@% double *temp; %@AS@% for( x = 0; x < size - 1; x++ ) %@AS@% for( x1 = x + 1; x1 < size; x1++ ) %@AS@% { %@AS@% if( **(p+x) > **(p+x1) ) %@AS@% { %@AS@% temp = *(p+x1); %@AS@% *(p+x1) = *(p+x); %@AS@% *(p+x) = temp; %@AS@% } %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% Within the %@AS@% sort %@AE@% function, the variable %@AS@% p %@AE@% is a pointer to a pointer. When we use a single asterisk, as in, %@NL@% %@NL@% %@AS@% *(p+x1)%@AE@%%@NL@% %@NL@% we access the contents of the %@AS@% x1 %@AE@% pointer, which is an address. When we place a double asterisk in front of an address value, as in, %@NL@% %@NL@% %@AS@% **(p+x)%@AE@%%@NL@% %@NL@% we access the contents of this address. %@NL@% %@NL@% Using pointer notation in place of array notation, QCSORT1.C achieves the same result as QCSORT.C. In many cases─including this one─it doesn't really matter which notation you use. If you're still more comfortable with array notation, you may prefer to use it sometimes. Since many C programs use pointers to manipulate arrays, however, it's worth taking the time to learn pointer notation, too. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090004 @%%@AB@%Getting Command-Line Arguments%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Command-line arguments are passed to programs through argv, an array of %@AU@%pointers.%@AE@% %@NL@% %@NL@% Arrays of pointers have one very common use─accessing command-line arguments. When a C program begins execution, DOS passes two arguments to it. The first argument, normally called %@AS@% argc%@AE@%, is an %@AB@%int%@AE@% variable that indicates the number of command-line arguments. The second, normally called %@AS@% %@AS@%argv%@AE@%, is a pointer to an array of strings. Each string in the array contains one of the command-line arguments. %@NL@% %@NL@% Even if you don't plan to use %@AS@% argc %@AE@% and %@AS@% argv %@AE@% in your programs, you can expect to see them often in other C programs, so it's useful to know how they're used. The ARGV.C program uses %@AS@% argc %@AE@% and %@AS@% argv%@AE@%. %@NL@% %@NL@% %@AS@% /* ARGV.C: Demonstrate accessing command-line arguments. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% void show_args( char *argument ); %@AS@% %@AS@% int main( int argc, char *argv[] ) %@AS@% { %@AS@% int count; %@AS@% for( count=0; count < argc; count++ ) %@AS@% show_args( argv[count] ); %@AS@% return 0; %@AS@% } %@AS@% %@AS@% void show_args( char *argument ) %@AS@% { %@AS@% printf( "%s\n", argument ); %@AS@% }%@AE@%%@NL@% %@NL@% To make ARGV.C produce output, you must give it some command-line arguments. (If you run ARGV.C in the QuickC environment, select Run/Debug from the Options menu and type the command-line arguments at the Command Line prompt.) The program prints each argument on the screen. %@NL@% %@NL@% If you use this command line, for instance, %@NL@% %@NL@% %@AS@% argv harpo chico groucho zeppo%@AE@%%@NL@% %@NL@% then ARGV.C gives this output: %@NL@% %@NL@% %@AS@% C:\SOURCES\ARGV.EXE %@AS@% harpo %@AS@% chico %@AS@% groucho %@AS@% zeppo%@AE@%%@NL@% %@NL@% The first argument may have surprised you. In DOS versions 3.0 and higher, the first string in the %@AS@% argv %@AE@% array ( %@AS@%argv[0]%@AE@% ) contains the drive specification and full pathname to the program that is executing. The drive and path you see will depend on how your system is configured. In the example the ARGV.EXE program is located in the SOURCES directory of drive C. %@NL@% %@NL@% Thus, the value of %@AS@% argc %@AE@% actually is one greater than the number of command-line arguments, and the first argument typed on the command line is the second string in the array (%@AS@% argv[1] %@AE@%). If you type the arguments shown above, the value of %@AS@% argc %@AE@% is 5 and %@AS@% argv[1] %@AE@% contains the argument %@AS@% harpo%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090005 @%%@AB@%Null Pointers%@AE@%%@EH@%%@NL@% %@NL@% We can use the ARGV.C program to illustrate another handy property of pointers: null pointers. Consider this modification (ARGV1.C): %@NL@% %@NL@% %@AS@% /* ARGV1.C: Demonstrate null pointers. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% void show_args( char *argument ); %@AS@% %@AS@% int main( int argc, char **argv ) %@AS@% { %@AS@% while( *argv ) %@AS@% show_args( *(argv++) ); %@AS@% return 0; %@AS@% } %@AS@% %@AS@% void show_args( char *argument ) %@AS@% { %@AS@% printf( "%s\n", argument ); %@AS@% }%@AE@%%@NL@% %@NL@% The ARGV1.C program gives the same output as the previous program but it uses a %@AB@%while%@AE@% loop instead of a %@AB@%for%@AE@% loop. The test expression in this loop, %@NL@% %@NL@% %@AS@% while( *argv )%@AE@%%@NL@% %@NL@% is equivalent to this test expression: %@NL@% %@NL@% %@AS@% while( *argv != 0 )%@AE@%%@NL@% %@NL@% The loop in ARGV1.C continues until it finds a "null pointer," a pointer that contains 0. In this case, the null pointer means we have reached the end of the array: no more strings are available. %@NL@% %@NL@% %@AU@% Null pointers can be used to show success or failure and as markers in a %@AU@%series.%@AE@% %@NL@% %@NL@% Many C library functions use null pointers to signal the success or failure of an operation that returns a pointer. For instance, the library function %@AB@%malloc%@AE@% normally returns a pointer to the beginning address of the memory area it allocates. If no memory is available, %@AB@%malloc%@AE@% returns a null pointer to show the operation failed. Similarly, the %@AB@%fopen%@AE@% function usually returns a pointer to a %@AB@%FILE%@AE@% structure, but returns a null pointer when it fails. %@NL@% %@NL@% Null pointers can also be used to mark the end of a list of pointers, such as the %@AS@% argv %@AE@% array or a linked list. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00090006 @%%@AB@%Pointers to Structures%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% A structure pointer can access any member of a structure.%@AE@% %@NL@% %@NL@% A pointer to a structure, or "structure pointer," is conceptually similar to an array pointer. Just as an array pointer can point to any element in an array, a structure pointer can reference any member in a structure. The major difference is one of notation. %@NL@% %@NL@% In case you're not yet an expert on structure notation, let's review it very briefly. First recall that each element in an array has the same type, so you refer to individual array elements with subscripts: %@NL@% %@NL@% %@AS@% i_array[3]%@AE@%%@NL@% %@NL@% Because members of a structure can have different types, you can't use numerical subscripts to refer to them based on their order. Instead, each structure member has a symbolic name. You refer to a member with a structure name and member name, separating the two names with the member-of operator (%@AB@%.%@AE@%): %@NL@% %@NL@% %@AS@% jones.name%@AE@%%@NL@% %@NL@% The notation for structure pointers follows the same pattern, with only two differences. You must %@NL@% %@NL@% %@NL@% 1. Replace the structure name with the name of the pointer%@NL@% %@NL@% 2. Replace the member-of operator with a two-character operator called the "pointer-member" operator (%@AB@%->%@AE@%)%@NL@% %@NL@% %@NL@% The pointer-member operator is formed by a dash and a right-angle bracket. The following name uses the pointer-member operator: %@NL@% %@NL@% %@AS@% jones_ptr->name%@AE@%%@NL@% %@NL@% Here %@AS@% jones_ptr %@AE@% is the name of a pointer to a structure, and %@AS@% name %@AE@% is a member of the structure that %@AS@% jones_ptr %@AE@% points to. %@NL@% %@NL@% The EMPLOY1.C program is a revision of the EMPLOYEE.C program that demonstrates structures in Chapter 4, "Data Types." This program illustrates how to manipulate a structure through a pointer: %@NL@% %@NL@% %@AS@% /* EMPLOY1.C: Demonstrate structure pointers. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% struct employee %@AS@% { %@AS@% char name[10]; %@AS@% int months; %@AS@% float wage; %@AS@% }; %@AS@% %@AS@% void display( struct employee *e_ptr ); %@AS@% %@AS@% main() %@AS@% { %@AS@% struct employee jones = %@AS@% { %@AS@% "Jones, J", %@AS@% 77, %@AS@% 13.68 %@AS@% }; %@AS@% %@AS@% display( &jones ); %@AS@% } %@AS@% %@AS@% void display( struct employee *e_ptr ) %@AS@% { %@AS@% printf( "Name: %s\n", e_ptr->name ); %@AS@% printf( "Months of service: %d\n", e_ptr->months ); %@AS@% printf( "Hourly wage: %6.2f\n", e_ptr->wage ); %@AS@% }%@AE@%%@NL@% %@NL@% %@AU@% Structure pointers allow functions to access structures that are local %@AU@%to other functions.%@AE@% %@NL@% %@NL@% The EMPLOY1.C program gives the same output as the earlier version. But instead of passing the entire structure to the %@AS@% display %@AE@% function, this program passes a structure pointer. This method conserves memory, since the %@AS@% %@AS@%display %@AE@% function doesn't create a local copy of the structure. It also allows %@AS@% display %@AE@% to change members in the original structure, which is local to the %@AB@%main%@AE@% function. %@NL@% %@NL@% The header of the %@AS@% display %@AE@% function shows that the function expects to receive a structure pointer: %@NL@% %@NL@% %@AS@% void display( struct employee *e_ptr )%@AE@%%@NL@% %@NL@% The expression in parentheses specifies what type of value the function expects. This expression is a bit complex, so let's look at each part individually. The expression %@AS@% *e_ptr %@AE@% indicates the function expects to receive a pointer, which it names %@AS@% e_ptr%@AE@%. It is preceded by %@NL@% %@NL@% %@AS@% struct employee%@AE@%%@NL@% %@NL@% which states what type of pointer %@AS@% e_ptr %@AE@% is. The %@AB@%struct%@AE@% keyword indicates %@AS@% %@AS@%e_ptr %@AE@% is a pointer to a structure, and the tag %@AS@% employee %@AE@% specifies the structure type. %@NL@% %@NL@% The next item of interest in EMPLOY1.C is the function call that passes the structure pointer: %@NL@% %@NL@% %@AS@% display( &jones );%@AE@%%@NL@% %@NL@% This statement uses the address-of operator to pass the address of the %@AS@% %@AS@%jones %@AE@% structure to the %@AS@% display %@AE@% function. The address-of operator is not optional. Since we want the function to access the original structure─not a local copy─we must pass the structure's address. %@NL@% %@NL@% When the %@AS@% display %@AE@% function executes, it creates a pointer variable named %@AS@% %@AS@%e_ptr %@AE@% and assigns to it the address passed in the function call. Now the %@AS@% %@AS@%display %@AE@% function can refer to any member of the structure indirectly through the pointer %@AS@% e_ptr%@AE@%. Within the %@AS@% display %@AE@% function, the statement %@NL@% %@NL@% %@AS@% printf( "%s\n", e_ptr->name );%@AE@%%@NL@% %@NL@% has the same effect that the statement %@NL@% %@NL@% %@AS@% printf( "%s\n", jones.name );%@AE@%%@NL@% %@NL@% has in the %@AB@%main%@AE@% function. Figure 9.2 illustrates the relationship between the structure pointer and structure members in EMPLOY1.C. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Just to confirm that the %@AS@% display %@AE@% function can access the original structure in EMPLOY1.C, try adding this statement to the end of the %@AS@% display %@AS@%%@AE@% function: %@NL@% %@NL@% %@AS@% strcpy( e_ptr->name, "King, M" );%@AE@%%@NL@% %@NL@% and this statement to the end of the %@AB@%main%@AE@% function: %@NL@% %@NL@% %@AS@% printf( "%s\n", jones.name );%@AE@%%@NL@% %@NL@% These changes cause EMPLOY1.C to print: %@NL@% %@NL@% %@AS@% King, M%@AE@%%@NL@% %@NL@% Acting indirectly through a structure pointer, the %@AS@% display %@AE@% function was able to change a structure defined elsewhere in the program. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00090007 @%%@AB@%Pointers to Functions%@AE@%%@EH@%%@NL@% %@NL@% At the beginning of the previous chapter we stated that a pointer can point to any object present in memory at run time. Since functions themselves are located in memory, you can assign the address of a function to a pointer, creating a "function pointer." %@NL@% %@NL@% %@AU@% A function pointer makes it possible to pass a function as a function %@AU@%argument.%@AE@% %@NL@% %@NL@% Function pointers provide a way─in fact, the only practical way─to pass a function as an argument to another function. This permits the second function to call the first function indirectly through the pointer. %@NL@% %@NL@% While function pointers may sound rather obscure, they have some common practical uses: %@NL@% %@NL@% %@NL@% ■ Some QuickC run-time library functions, such as %@AB@%qsort%@AE@%, expect to receive a pointer to a user-defined function in your program. (Online help includes an example program that uses %@AB@%qsort%@AE@%.)%@NL@% %@NL@% ■ Function pointers are used extensively in Windows and OS/2 Presentation Manager programs. %@NL@% %@NL@% ■ Using an array of function pointers, you can create a "dispatch table." A dispatch table is a list of related functions that can be called based on some choice made at run time. It is similar to an %@AB@%ON %@AB@% GOSUB%@AE@% statement in BASIC or a call table in assembly language.%@NL@% %@NL@% %@NL@% The syntax for function pointers is a bit complex, so let's start with a simple example. The FUNCPTR.C program creates a pointer to our old friend, %@AB@%printf%@AE@%, and calls %@AB@%printf%@AE@% through the pointer: %@NL@% %@NL@% %@AS@% /* FUNCPTR.C: Demonstrate function pointers. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int (*func_ptr) (); %@AS@% func_ptr = printf; %@AS@% (*func_ptr) ( "Curiouser and curiouser...\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from FUNCPTR.C: %@NL@% %@NL@% %@AS@% Curiouser and curiouser...%@AE@%%@NL@% %@NL@% This line from FUNCPTR.C declares %@AS@% func_ptr %@AE@% as a pointer to a function: %@NL@% %@NL@% %@AS@% int (*func_ptr) ();%@AE@%%@NL@% %@NL@% The declaration of a function pointer must use the same type specifier as the function it references. If the function returns a %@AB@%float%@AE@% value, the pointer uses type %@AB@%float%@AE@%, and so on. Since the %@AB@%printf%@AE@% function returns an %@AB@%int%@AE@% value showing how many characters it displays, the declaration of %@AS@% func_ptr %@AE@% uses the type %@AB@%int%@AE@%. %@NL@% %@NL@% %@AU@% A function-pointer declaration must have two pairs of parentheses.%@AE@% %@NL@% %@NL@% Function-pointer declarations may look complex, but all the parentheses are essential. The empty parentheses at the end of the declaration are needed to show the pointer points to a function. %@NL@% %@NL@% The parentheses enclosing the function name itself are mandatory, too. Notice what happens if you omit them: %@NL@% %@NL@% %@AS@% void *func_ptr(); /* Error! Not a function pointer. */%@AE@%%@NL@% %@NL@% Instead of declaring a pointer to a function, this statement declares a function that returns a pointer─not at all what we want in FUNCPTR.C. %@NL@% %@NL@% The next program line initializes the function pointer, assigning it the address of the %@AB@%printf%@AE@% function: %@NL@% %@NL@% %@AS@% func_ptr = printf;%@AE@%%@NL@% %@NL@% This line has two important features. First, notice the name %@AB@%printf%@AE@% isn't followed by parentheses, as it would be when you call %@AB@%printf%@AE@% directly. We want to obtain the address of %@AB@%printf%@AE@%, not call it. %@NL@% %@NL@% Second, note that it's not necessary to place the address-of operator before the name %@AB@%printf%@AE@%. Because %@AS@% func_ptr %@AE@% was declared as a function pointer, the compiler knows it should use the address of %@AB@%printf%@AE@% here. If you like, however, you can add the address-of operator to make the statement a little more readable: %@NL@% %@NL@% %@AS@% func_ptr = &printf;%@AE@%%@NL@% %@NL@% The next line calls the %@AB@%printf%@AE@% function indirectly through the pointer %@AS@% %@AS@%func_ptr%@AE@%: %@NL@% %@NL@% %@AS@% (*func_ptr) ( "Curiouser and curiouser...\n" );%@AE@%%@NL@% %@NL@% Note the similarity between this statement and a normal call to %@AB@%printf%@AE@%. It's equivalent to this line: %@NL@% %@NL@% %@AS@% printf( "Curiouser and curiouser...\n" );%@AE@%%@NL@% %@NL@% To call %@AB@%printf%@AE@% indirectly through %@AS@% func_ptr%@AE@%, you supply the same arguments as when you call %@AB@%printf%@AE@% directly. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00090008 @%%@AB@%Passing Function Pointers as Arguments%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Function pointers are usually passed as function arguments.%@AE@% %@NL@% %@NL@% Like other pointers, function pointers can be passed as arguments to functions. Normally, in fact, this is the only reason to use a function pointer. %@NL@% %@NL@% The FUNCPTR.C program in the previous section is easy to follow but not very practical. In a real program, you wouldn't go to the trouble of creating a function pointer just to call %@AB@%printf%@AE@% from the %@AB@%main%@AE@% function. %@NL@% %@NL@% The FUNCPTR1.C program demonstrates how to pass a function pointer as an argument. It has a function named %@AS@% gimme_func %@AE@% that expects to be passed a function pointer: %@NL@% %@NL@% %@AS@% /* FUNCPTR1.C: Passing function pointers as arguments. */%@AE@%%@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% %@AS@% void gimme_func( void (*func_ptr) () ); %@AS@% %@AS@% main() %@AS@% { %@AS@% gimme_func( puts ); %@AS@% gimme_func( printf ); %@AS@% } %@AS@% %@AS@% void gimme_func( void (*func_ptr) () ) %@AS@% { %@AS@% (*func_ptr) ( "Ausgezeichnet!" ); %@AS@% }%@AE@%%@NL@% %@NL@% Here is the output from FUNCPTR1.C: %@NL@% %@NL@% %@AS@% Ausgezeichnet! %@AS@% Ausgezeichnet!%@AE@%%@NL@% %@NL@% In the interests of brevity, the function %@AS@% gimme_func %@AE@% does a very simple job. It expects to receive a pointer to a function that can display a string and uses that pointer to print the string. The first call to %@AS@% gimme_func %@AE@% passes a pointer to the library function %@AB@%puts%@AE@%, and the second passes a pointer to %@AB@%printf%@AE@%. %@NL@% %@NL@% Since the declaration of %@AS@% gimme_func %@AE@% states it takes a pointer to a function, the address-of operator is optional in a call to %@AS@% gimme_func%@AE@%. The following statements are equivalent: %@NL@% %@NL@% %@AS@% gimme_func( puts ); %@AS@% gimme_func( &puts );%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00090009 @%%@AB@%A Parting Word on Pointers%@AE@%%@EH@%%@NL@% %@NL@% If you have read the previous two chapters from beginning to end, you may be suffering from a mild─or perhaps not so mild─case of information overload. Pointers have so many different uses that it's difficult to learn everything about them at once. %@NL@% %@NL@% Don't be discouraged if some uses of pointers still aren't clear to you. The latter parts of this chapter cover some rather esoteric techniques, which you probably won't use often. When needed, however, these techniques offer some very powerful capabilities. %@NL@% %@NL@% Like other programming concepts, pointers are best learned through practice, so use them at every sensible opportunity. Remember, you don't need to know everything about pointers in order to do %@AI@%something%@AE@% with them. The more you use pointers in everyday programming, the sooner all the pieces of the puzzle will fall into place. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00100001 @%%@1@%%@AB@%Chapter 10 Programming Pitfalls%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% In C, as in every language, it's rare for any program to work perfectly the first time. An important part of knowing a language is recognizing what %@AI@%not%@AE@% to do and why certain problems occur. %@NL@% %@NL@% This chapter describes common C programming pitfalls and how to avoid them. It is organized under broad topics, such as "Pointer Problems," with a category for miscellaneous problems at the end. The description of each error gives a code example, explains why the error occurs, and offers a solution. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00100002 @%%@AB@%Operator Problems%@AE@%%@EH@%%@NL@% %@NL@% The most common operator problems involve operators unique to C. Others involve questions of precedence, which can cause problems in any language. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100003 @%%@AB@%Confusing Assignment and Equality Operators%@AE@%%@EH@%%@NL@% %@NL@% A common error is to confuse the assignment operator (%@AB@%=%@AE@%) with the equality operator (%@AB@%==%@AE@%). The mistake often occurs in decision-making statements: %@NL@% %@NL@% %@AS@% int val = 555; %@AS@% if( val = 20 ) /* Error! */ %@AS@% printf( "val equals 20\n" );%@AE@%%@NL@% %@NL@% The above code prints %@AS@% val equals 20 %@AE@% even though it's clear %@AS@% val %@AE@% doesn't equal 20 when the %@AB@%if%@AE@% statement begins. Instead of testing whether %@AS@% x %@AE@% equals 20, the expression %@AS@% val = 20 %@AE@% %@AI@%assigns%@AE@% the value 20 to %@AS@% val%@AE@%. %@NL@% %@NL@% Remember, the single equal sign (=) performs an assignment in C. This particular assignment results in a nonzero value, so the %@AB@%if%@AE@% test is evaluated as true, causing the %@AB@%printf%@AE@% statement to execute. %@NL@% %@NL@% To correct the problem, use the double equal sign (%@AB@%==%@AE@%) to test equality: %@NL@% %@NL@% %@AS@% if( x == 20 ) %@AS@% printf( "x equals 20\n" );%@AE@%%@NL@% %@NL@% Once you're in the habit of using the equality operator, you might make the opposite mistake of using two equal signs where you should use only one: %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% int val; %@AS@% for( val == 0; val < 5; val++ ) /* Error! */ %@AS@% printf( "val = %d\n", val ); %@AS@% }%@AE@%%@NL@% %@NL@% Here the error appears in the initializing expression of the %@AB@%for%@AE@% statement. It's the reverse of what happened in the first example. Instead of assigning the value 0 to %@AS@% val%@AE@%, the expression %@AS@% val == 0 %@AE@% evaluates whether or not %@AS@% val %@AS@%%@AE@% equals 0. The expression doesn't change the value of %@AS@% val %@AE@% at all. Since %@AS@% %@AS@%val %@AE@% is an uninitialized variable, the %@AB@%for%@AE@% loop is unpredictable. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100004 @%%@AB@%Confusing Operator Precedence%@AE@%%@EH@%%@NL@% %@NL@% Peculiar things can happen if you ignore operator precedence: %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% int ch; %@AS@% while( ch = getch() != '\r' ) %@AS@% printf( "%d\n", ch ); %@AS@% }%@AE@%%@NL@% %@NL@% Instead of assigning the result of the %@AB@%getch%@AE@% library-function call to %@AS@% ch%@AE@%, the above code assigns the value 0 to %@AS@% ch %@AE@% when you press the ENTER key and the value 1 when you press any other key. (The values 1 and 0 represent true and false.) %@NL@% %@NL@% The error occurs because the inequality operator (%@AB@%!=%@AE@%) has higher precedence than the assignment operator (%@AB@%=%@AE@%). The expression %@NL@% %@NL@% %@AS@% ch = getch() != '\r'%@AE@%%@NL@% %@NL@% is the same as %@NL@% %@NL@% %@AS@% ch = (getch() != '\r')%@AE@%%@NL@% %@NL@% Both expressions compare the result of the %@AB@%getch%@AE@% call to the character constant %@AB@%\r%@AE@%. The result of that comparison is then assigned to %@AS@% ch%@AE@%. %@NL@% %@NL@% For the program to work correctly, these operations must happen in the reverse order. The result of the function call must be assigned to the variable %@AI@%before%@AE@% the variable is compared to the constant. We can solve the problem by adding parentheses: %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% int ch; %@AS@% while( (ch = getch()) != '\r') %@AS@% printf( "%d\n", ch ); %@AS@% }%@AE@%%@NL@% %@NL@% Parentheses have the highest precedence of any operator, so the expression %@NL@% %@NL@% %@AS@% (ch = getch()) != '\r'%@AE@%%@NL@% %@NL@% works correctly. It assigns the result of the %@AB@%getch%@AE@% call to %@AS@% ch %@AE@% before comparing %@AS@% ch %@AE@% to the constant. %@NL@% %@NL@% The list of precedence-related errors is almost endless. Fortunately, QuickC makes it unnecessary to memorize precedence rules. To view a complete table of operator precedences, see Appendix A, "C Language Guide," and online help in the QuickC environment. %@NL@% %@NL@% %@AU@% Use parentheses to avoid operator precedence problems.%@AE@% %@NL@% %@NL@% When in doubt, use extra parentheses to make the order of operations absolutely clear. Extra parentheses don't degrade performance, and they can improve readability as well as minimize precedence problems. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100005 @%%@AB@%Confusing Structure-Member Operators%@AE@%%@EH@%%@NL@% %@NL@% Two different operators are used to access the members of a structure. Use the structure-member operator (%@AB@%.%@AE@%) to access a structure member directly, and the pointer-member operator (%@AB@%->%@AE@%) to access a structure member indirectly through a pointer. %@NL@% %@NL@% For instance, you may create a pointer to a structure of the %@AS@% employee %@AE@% type, %@NL@% %@NL@% %@AS@% struct employee *p_ptr;%@AE@%%@NL@% %@NL@% and initialize the pointer to point to the %@AS@% jones %@AE@% structure: %@NL@% %@NL@% %@AS@% p_ptr = &jones;%@AE@%%@NL@% %@NL@% If you use the structure-member operator to access a structure member through the pointer, %@NL@% %@NL@% %@AS@% p_ptr.months = 78; /* Error! */%@AE@%%@NL@% %@NL@% QuickC issues this error message: %@NL@% %@NL@% %@AS@% C2040: '.' requires struct/union name%@AE@%%@NL@% %@NL@% Use the pointer-member operator to access a structure member through a pointer: %@NL@% %@NL@% %@AS@% p_ptr->months = 78;%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00100006 @%%@AB@%Array Problems%@AE@%%@EH@%%@NL@% %@NL@% The most common errors associated with arrays involve indexing errors. The problems described in this section all concern indexing errors of one form or another. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100007 @%%@AB@%Array Indexing Errors%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The first C array subscript is 0.%@AE@% %@NL@% %@NL@% If you're used to a language that has different subscripting rules, it's easy to forget that the first subscript of a C array is 0 and the last subscript is 1 less than the number used to declare the array. Here's an example: %@NL@% %@NL@% %@AS@% int i_array[4] = { 3, 55, 600, 12 }; %@AS@% main() %@AS@% { %@AS@% int count; %@AS@% for( count = 1; count < 5; count++ ) /* Error! */ %@AS@% printf( "i_array[%d] = %d\n", i_array[count] ); %@AS@% }%@AE@%%@NL@% %@NL@% The %@AB@%for%@AE@% loop in the above program starts at %@AS@% i_array[1] %@AE@% and ends at %@AS@% %@AS@%i_array[4]%@AE@%. It should begin with the first element, %@AS@% i_array[0] %@AE@% and end at the last,%@AS@% i_array[3]%@AE@%. The following corrects the error. %@NL@% %@NL@% %@AS@% for( count = 0; count < 4; count++ ) %@AS@% printf( "i_array[%d] = %d\n", i_array[count] );%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100008 @%%@AB@%Omitting an Array Subscript in Multidimensional Arrays%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Enclose each subscript in its own set of brackets.%@AE@% %@NL@% %@NL@% Programmers who know QuickBASIC, QuickPascal, or FORTRAN may be tempted to place more than one array subscript in the same pair of brackets. In C, each subscript of a multidimensional array is enclosed in its own pair of brackets: %@NL@% %@NL@% %@AS@% int i_array[2][2] = { { 12, 2 }, { 6, 55 } }; %@AS@% main() %@AS@% { %@AS@% printf( "%d\n", i_array[ 0, 1 ] ); /* Error! */ %@AS@% }%@AE@%%@NL@% %@NL@% In the preceding example, the expression %@NL@% %@NL@% %@AS@% i_array[ 0, 1 ]%@AE@%%@NL@% %@NL@% does not access element 0,1 of %@AS@% i_array %@AE@%. Here is the correct way to refer to that array element: %@NL@% %@NL@% %@AS@% i_array[0][1]%@AE@%%@NL@% %@NL@% Interestingly, the deviant array reference doesn't cause a syntax error. As mentioned in Chapter 6, "Operators," it's legal to separate multiple expressions with a comma operator, and the final value of such a series is the value of the rightmost expression in the group. Thus, the expression %@NL@% %@NL@% %@AS@% i_array[ 0, 1 ]%@AE@%%@NL@% %@NL@% is equivalent to this one: %@NL@% %@NL@% %@AS@% i_array[ 1 ];%@AE@%%@NL@% %@NL@% Both expressions give an address, not the value of an array element. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100009 @%%@AB@%Overrunning Array Boundaries%@AE@%%@EH@%%@NL@% %@NL@% Since C doesn't check array subscripts for validity, you must keep track of array boundaries on your own. For instance, if you initialize a five-character array, %@NL@% %@NL@% %@AS@% char sample[] = "ABCD";%@AE@%%@NL@% %@NL@% and refer to a nonexistent array element, %@NL@% %@NL@% %@AS@% sample[9] = 'X';%@AE@%%@NL@% %@NL@% QuickC doesn't signal an error, although the second statement overwrites memory outside the array. It stores a character in element 9 of an array that contains only 5 elements. %@NL@% %@NL@% The same problem can occur when accessing an array through a pointer: %@NL@% %@NL@% %@AS@% char sample[] = "ABCD"; %@AS@% char *ptr = sample; %@AS@% *--ptr = 'X'; /* Error! */%@AE@%%@NL@% %@NL@% The code overwrites the byte in memory below the array. To avoid such problems, confine all array operations within the range used to declare the array. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00100010 @%%@AB@%String Problems%@AE@%%@EH@%%@NL@% %@NL@% Strings are handled a little differently in C than most languages─a fact that can cause problems. The following errors are common to programs that use strings. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100011 @%%@AB@%Confusing Character Constants and Character Strings%@AE@%%@EH@%%@NL@% %@NL@% Remember the difference between a character constant, which has one byte, and a character string, which is a series of characters ending with a null character: %@NL@% %@NL@% %@AS@% char ch = 'Y'; %@AS@% if( ch == "Y" ) /* Error! */ %@AS@% printf( "The ayes have it..." );%@AE@%%@NL@% %@NL@% The example above mistakenly compares the %@AB@%char%@AE@% variable %@AS@% ch %@AE@% to a twocharacter string (%@AS@% "Y" %@AE@%) instead of a single character constant (%@AS@% 'Y' %@AE@%). Since the comparison is false, the %@AB@%printf%@AE@% statement never executes─no matter what %@AS@% ch %@AE@% equals. %@NL@% %@NL@% The %@AB@%if%@AE@% statement needs to use single quotes. This code correctly tests whether %@AS@% ch %@AE@% equals the character %@AS@% 'Y'%@AE@%: %@NL@% %@NL@% %@AS@% char ch = 'Y'; %@AS@% if( ch == 'Y' ) %@AS@% printf( "The ayes have it..." );%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100012 @%%@AB@%Forgetting the Null Character That Terminates Strings%@AE@%%@EH@%%@NL@% %@NL@% Remember that strings end with a null character in C. If you declare this five-character array, %@NL@% %@NL@% %@AS@% char sample[5];%@AE@%%@NL@% %@NL@% the compiler allocates five bytes of memory for the array. If you try to store the string %@AS@%"Hello" %@AE@% in the array like this, %@NL@% %@NL@% %@AS@% strcpy( sample, "Hello" );%@AE@%%@NL@% %@NL@% you'll overrun the array's bounds. The string %@AS@%"Hello" %@AE@% contains six characters (five letters and a null character), so it's one byte too big to fit in the %@AS@% sample %@AE@% array. The %@AB@%strcpy%@AE@% overwrites one byte of memory outside the array's storage. %@NL@% %@NL@% It's easy to make this error when allocating memory for a string, too: %@NL@% %@NL@% %@AS@% char str[] = "Hello"; %@AS@% char *ptr; %@AS@% ptr = malloc( strlen( str ) ); /* Error! */ %@AS@% if( ptr == NULL ) %@AS@% exit( 1 ); %@AS@% else %@AS@% strcpy( ptr, str );%@AE@%%@NL@% %@NL@% This time the error occurs in the call to the %@AB@%malloc%@AE@% function, which allocates memory to a pointer prior to a string copy. The %@AB@%strlen%@AE@% function returns the length of a string not including the null character that ends the string. Since the amount of memory allocated is one byte too small, the %@AB@%strcpy%@AE@% operation overwrites memory, just as in the previous example. %@NL@% %@NL@% To avoid the problem, add 1 to the value returned by %@AB@%strlen%@AE@%: %@NL@% %@NL@% %@AS@% ptr = malloc( strlen( str ) + 1 );%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100013 @%%@AB@%Forgetting to Allocate Memory for a String%@AE@%%@EH@%%@NL@% %@NL@% If you declare a string as a pointer, don't forget to allocate memory for it. This example tries to create a %@AB@%char%@AE@% pointer named %@AS@% ptr %@AE@% and initialize it with a string: %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% char *ptr; %@AS@% strcpy( ptr, "Ashby" ); /* Error! */ %@AS@% }%@AE@%%@NL@% %@NL@% The pointer declaration %@AS@% char *ptr; %@AE@% creates a pointer variable but nothing else. It allocates enough memory for the pointer to store an address but doesn't allocate any memory to store the object to which %@AS@% ptr %@AE@% will point. The %@AB@%strcpy%@AE@% operation in the next line overwrites memory by copying the string into an area not used by the program. %@NL@% %@NL@% One way to allocate memory is by declaring a %@AB@%char%@AE@% array large enough to hold the string: %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% char c_array[10]; %@AS@% strcpy( c_array, "Randleman" ); %@AS@% }%@AE@%%@NL@% %@NL@% You can also call the %@AB@%malloc%@AE@% library function to allocate memory at run time: %@NL@% %@NL@% %@AS@% #define BUFFER_SIZE 30 %@AS@% #include <malloc.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% char *ptr; %@AS@% if( ptr = (char *) malloc( BUFFER_SIZE ) ) %@AS@% { %@AS@% strcpy( ptr, "Duvall" ); %@AS@% printf( ptr ); %@AS@% free( ptr ); %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00100014 @%%@AB@%Pointer Problems%@AE@%%@EH@%%@NL@% %@NL@% Every experienced C programmer has a collection of favorite pointer-induced bugs. Pointer errors can wreak havoc because pointers can change the contents of any addressable memory location. If a pointer writes to an unexpected address, the results can be disastrous. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100015 @%%@AB@%Using the Wrong Address Operator to Initialize a Pointer%@AE@%%@EH@%%@NL@% %@NL@% If you're still learning about pointers, it's easy to forget which address operator to use when initializing a pointer variable. For example, you might want to create a pointer to a simple %@AB@%int%@AE@% variable: %@NL@% %@NL@% %@AS@% int val = 25; %@AS@% int *ptr; %@AS@% ptr = val; /* Error! */%@AE@%%@NL@% %@NL@% The code above doesn't initialize %@AS@% ptr %@AE@% correctly. Instead of assigning to %@AS@% %@AS@%ptr %@AE@% the address of %@AS@% val%@AE@%, the statement %@NL@% %@NL@% %@AS@% ptr = val;%@AE@%%@NL@% %@NL@% tries to assign %@AS@% ptr %@AE@% the contents of %@AS@% val%@AE@%, causing an error message: %@NL@% %@NL@% %@AS@% warning C4047: '=' : different levels of indirection%@AE@%%@NL@% %@NL@% Because %@AS@% val %@AE@% is an %@AB@%int%@AE@% variable, its contents can't form a meaningful address for %@AS@%ptr%@AE@%. You must use the address-of operator to initialize %@AS@% ptr%@AE@%: %@NL@% %@NL@% %@AS@% ptr = &val;%@AE@%%@NL@% %@NL@% Here's another pointer initialization error: %@NL@% %@NL@% %@AS@% int val = 25; %@AS@% int *ptr; %@AS@% *ptr = &val; /* Error! */%@AE@%%@NL@% %@NL@% The last line doesn't initialize %@AS@% ptr %@AE@% to point to the variable %@AS@% val%@AE@%. The expression to the left of the equal sign, %@AS@% *ptr%@AE@%, stands for the object %@AS@% ptr %@AE@% points to. Instead of assigning %@AS@% ptr %@AE@% the address of %@AS@% val%@AE@%, the line tries to assign the address of %@AS@% val %@AE@% to the place where %@AS@% ptr %@AE@% points. Because %@AS@% ptr %@AE@% has never been initialized, the assignment triggers a run-time error: %@NL@% %@NL@% %@AS@% run-time error R6001 %@AS@% -null pointer assignment%@AE@%%@NL@% %@NL@% Here is the correct way to initialize this pointer: %@NL@% %@NL@% %@AS@% ptr = &val;%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100016 @%%@AB@%Declaring a Pointer with the Wrong Type%@AE@%%@EH@%%@NL@% %@NL@% You should make sure the type used to declare a pointer matches the type of data object it points to: %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% int *ptr; %@AS@% . %@AS@% . %@AS@% . %@AS@% float val = 3.333333; %@AS@% ptr = val; /* Error! */ %@AS@% printf( "val = %f\n", *ptr ); %@AS@% }%@AE@%%@NL@% %@NL@% The program declares %@AS@% ptr %@AE@% as a pointer to an %@AB@%int%@AE@%. Later on, forgetting what type we used when declaring %@AS@% ptr%@AE@%, we assign it the address of the floating-point variable %@AS@% val%@AE@%. %@NL@% %@NL@% %@AU@% Declaring a pointer with the wrong type can cause unwanted type %@AU@%conversions.%@AE@% %@NL@% %@NL@% Since C allows you to assign any address to a pointer, the assignment doesn't cause an error. But accessing %@AS@% val %@AE@% through %@AS@% ptr %@AE@% creates problems. Because %@AS@% ptr %@AE@% is declared as a pointer to an %@AB@%int%@AE@%, the compiler does a type conversion on the %@AB@%float%@AE@% it points to, converting the %@AB@%float%@AE@% value to an %@AB@%int%@AE@%. The output is garbage: %@NL@% %@NL@% %@AS@% val = 11242989923343410000000000000000000000000000000000000 %@AS@% 000000000000000000000000000000000000000000000000000.000000%@AE@%%@NL@% %@NL@% The following program cures the error by declaring %@AS@% ptr %@AE@% as a pointer to a %@AB@%float%@AE@% data type: %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% float *ptr; %@AS@% float val = 3.333333; %@AS@% ptr = &val; %@AS@% printf( "%f\n", *ptr ); %@AS@% }%@AE@%%@NL@% %@NL@% Now it gives the correct output: %@NL@% %@NL@% %@AS@% val = 3.333333%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100017 @%%@AB@%Using Dangling Pointers%@AE@%%@EH@%%@NL@% %@NL@% A "dangling pointer" is one that points to a memory area no longer in use by your program. Dangling pointers, like uninitialized pointers, can be very dangerous to use. %@NL@% %@NL@% For instance, say you allocate a block of memory with the %@AB@%malloc%@AE@% library function: %@NL@% %@NL@% %@AS@% #define BUFSIZE 1000 %@AS@% char *ptr; %@AS@% if( ptr = (char *) malloc( BUFSIZE ) ) %@AS@% /* do something */ ;%@AE@%%@NL@% %@NL@% After the memory block has been allocated with %@AB@%malloc%@AE@%, the pointer %@AS@% ptr %@AE@% points to a valid data object. Once you're done using allocated memory, you normally return it to the heap: %@NL@% %@NL@% %@AS@% free( ptr );%@AE@%%@NL@% %@NL@% After you free the memory it points to, %@AS@% ptr %@AE@% is a dangling pointer. It still points to a valid machine address, but that address is no longer in use by the program. You shouldn't use the pointer at this stage, just as you shouldn't use it before it has been initialized. %@NL@% %@NL@% Dangling pointers can also be created by a function that returns a pointer to a local variable: %@NL@% %@NL@% %@AS@% int *boo_boo( void ) %@AS@% { %@AS@% int object; %@AS@% . %@AS@% . %@AS@% . %@AS@% return &object; /* Error! */ %@AS@% }%@AE@%%@NL@% %@NL@% The %@AS@% boo_boo %@AE@% function returns the address of the local variable %@AS@% object%@AE@%, forgetting the storage for %@AS@% object %@AE@% is no longer part of the program after the function ends. %@NL@% %@NL@% Here's a variant of the previous example involving a string pointer: %@NL@% %@NL@% %@AS@% char *boo_boo( void ) %@AS@% { %@AS@% char *c_ptr; %@AS@% c_ptr = "Hello"; %@AS@% . %@AS@% . %@AS@% . %@AS@% return c_ptr; /* Error! */ %@AS@% }%@AE@%%@NL@% %@NL@% Since the string constant %@AS@% "Hello" %@AE@% is local to the function, it evaporates when the function ends, leaving the pointer %@AS@% c_ptr %@AE@% dangling. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00100018 @%%@AB@%Library-Function Problems%@AE@%%@EH@%%@NL@% %@NL@% Once you've learned enough about C to write practical programs, you can begin to explore the rich function library supplied with QuickC. This section outlines a few common problems related to using library functions. Again, you can use online help to get information about specific library functions. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100019 @%%@AB@%Failing to Check Return Values from Library Functions%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Always check library function return values.%@AE@% %@NL@% %@NL@% Almost all library functions return some value─either the result of processing or an error code showing success or failure. You should always check libraryfunction return values, even if you're confident of the result. %@NL@% %@NL@% This rule is critical when calling a library function such as %@AB@%malloc%@AE@%, which allocates memory at run time: %@NL@% %@NL@% %@AS@% char *ptr; %@AS@% ptr = (char *) malloc( BUFSIZE ); /* Error! */%@AE@%%@NL@% %@NL@% If the call to %@AB@%malloc%@AE@% fails, the pointer %@AS@% ptr %@AE@% is assigned a null (0) value. Using %@AS@% ptr %@AE@% under these circumstances can overwrite unexpected memory addresses or cause a run-time error. The following code checks the return value from %@AB@%malloc%@AE@%: %@NL@% %@NL@% %@AS@% #define NULL 0 %@AS@% #define BUFSIZE 32768 %@AS@% . %@AS@% . %@AS@% . %@AS@% char *ptr; %@AS@% if( (ptr = (char *) malloc( BUFSIZE ) ) != NULL ) %@AS@% { %@AS@% printf( "Copacetic.\n" ); %@AS@% /* Do something useful... */ %@AS@% } %@AS@% else %@AS@% printf( "Not enough memory!\n" );%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100020 @%%@AB@%Duplicating Library-Function Names%@AE@%%@EH@%%@NL@% %@NL@% There are so many functions in the QuickC run-time library that it's sometimes difficult to avoid duplicating function names. For instance, if you write a function that reads data from a buffer, the name %@AS@% read %@AE@% may strike you as short and descriptive. %@NL@% %@NL@% The only problem is that %@AB@%read%@AE@% is the name of a QuickC library function. A program that defines its own %@AS@% read %@AE@% function may work correctly at first, but if you later include the header file that declares the %@AB@%read%@AE@% library function, %@NL@% %@NL@% %@AS@% #include <io.h>%@AE@%%@NL@% %@NL@% then redefinition errors occur. You can't use the same name for two different functions. The solution here is to rename the user-defined function. %@NL@% %@NL@% %@AU@% Use online help to check for function-name conflicts.%@AE@% %@NL@% %@NL@% QuickC's online help lets you check for such name conflicts on the spot. Put the cursor on the function name you wish to use, then press F1. If the name is already used for a library function, online help displays information about the function. If the name isn't in online help, it's not used in the QuickC function library and is a safe choice. %@NL@% %@NL@% Unless you're writing your own library functions, it's a good rule to avoid declaring names that begin with an underscore ( _ ), since many of the system-defined names in QuickC start with that character. (Non-ANSI library functions begin with a single underscore. Predefined identifiers such as %@AB@%TIME%@AE@% start with two underscores, and routines internal to the C run-time library can begin with either one or two underscores.) %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100021 @%%@AB@%Forgetting to Include Header Files for Library Functions%@AE@%%@EH@%%@NL@% %@NL@% Because they contain needed function prototypes, it's important to include the correct header files when using QuickC library functions: %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% double val = sqrt( (double) 10 ); %@AS@% printf( "square root of 10 = %le\n", val ); %@AS@% }%@AE@%%@NL@% %@NL@% The program above calls the library function %@AB@%sqrt%@AE@%, which calculates a square root. Most of the program is correct. When passing the value 10 to %@AB@%sqrt%@AE@%, it casts the argument as a %@AB@%double%@AE@%, the type %@AB@%sqrt%@AE@% expects. The return value from %@AB@%sqrt%@AE@% is assigned to a %@AB@%double%@AE@% variable, too. %@NL@% %@NL@% Unfortunately, the program still gives the wrong output. The square root of 10 is not 171 (1.710000e+002 in exponential notation): %@NL@% %@NL@% %@AS@% square root of 10 = 1.710000e+002%@AE@%%@NL@% %@NL@% %@AU@% Function prototypes can prevent unexpected type conversions.%@AE@% %@NL@% %@NL@% Because the program has no prototype for the %@AB@%sqrt%@AE@% function, %@AB@%sqrt%@AE@% has the %@AB@%int%@AE@% return type by default. The value returned by %@AB@%sqrt%@AE@% undergoes an unexpected type conversion─from type %@AB@%double%@AE@% to %@AB@%int%@AE@%─and becomes garbage. %@NL@% %@NL@% This problem is easily solved. Simply include the standard header file that contains the prototype for %@AB@%sqrt%@AE@%: %@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% #include <math.h> %@AS@% main() %@AS@% { %@AS@% double val = sqrt( (double) 10 ); %@AS@% printf( "square root of 10 = %le\n", val ); %@AS@% }%@AE@%%@NL@% %@NL@% Now the program works correctly: %@NL@% %@NL@% %@AS@% square root of 10 = 3.162278e+000%@AE@%%@NL@% %@NL@% If you're not sure which header file a library function needs, take advantage of QuickC's online help. (Put the cursor on the function name and press F1.) If the function needs a header file, the file name appears in an %@AB@%#include%@AE@% directive above the function prototype. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100022 @%%@AB@%Omitting the Address-Of Operator When Calling scanf%@AE@%%@EH@%%@NL@% %@NL@% Don't forget to put the address-of operator in front of arguments when using the %@AB@%scanf%@AE@% library function (the %@AB@%scanf%@AE@% function accesses keyboard input; see Chapter 11, "Input and Output")%@AB@%:%@AE@% %@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% int val; %@AS@% printf( "Type a number: " ); %@AS@% scanf( "%d", val ); /* Error! */ %@AS@% printf( "%d", val ); %@AS@% }%@AE@%%@NL@% %@NL@% When the program calls %@AB@%scanf%@AE@%, it omits the address-of operator that should precede the second argument: %@NL@% %@NL@% %@AS@% scanf( "%d", val ); /* Error! */%@AE@%%@NL@% %@NL@% The %@AB@%scanf%@AE@% function expects to be passed a pointer to a variable (in this case, a pointer to %@AS@% val %@AE@%) so it can assign an input value to the variable. But because the address-of operator is missing, the program passes the value of %@AS@% val%@AE@%, not its address. %@NL@% %@NL@% Instead of storing an input value in %@AS@% val %@AE@% as intended, %@AB@%scanf%@AE@% uses the uninitialized value of %@AS@% val %@AE@% as a pointer and assigns the input value to an unpredictable address. As a result, %@AS@% val %@AE@% remains uninitialized and the program overwrites memory elsewhere─two very undesirable events. %@NL@% %@NL@% Here is the correct way to call %@AB@%scanf%@AE@% in this program: %@NL@% %@NL@% %@AS@% scanf( "%d", &val );%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00100023 @%%@AB@%Macro Problems%@AE@%%@EH@%%@NL@% %@NL@% Function-like macros─macro definitions that take arguments─share many of the advantages of functions. They can cause unwanted side effects, however, if you fail to put parentheses around their arguments or carelessly supply an argument that uses an increment or decrement operator. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100024 @%%@AB@%Omitting Parentheses from Macro Arguments%@AE@%%@EH@%%@NL@% %@NL@% A macro definition that doesn't enclose its arguments in parentheses can create precedence problems: %@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% %@AS@% #define FOURX(arg) ( arg * 4 ) %@AS@% %@AS@% main() %@AS@% { %@AS@% int val; %@AS@% val = FOURX( 2 + 3 ); %@AS@% printf( "val = %d\n", val ); %@AS@% }%@AE@%%@NL@% %@NL@% The %@AS@% FOURX %@AE@% macro in the program multiplies its argument by 4. The macro works fine if you pass it a single value, as in %@NL@% %@NL@% %@AS@% val = FOURX( 2 );%@AE@%%@NL@% %@NL@% but returns the wrong result if you pass it this expression: %@NL@% %@NL@% %@AS@% val = FOURX( 2 + 3 );%@AE@%%@NL@% %@NL@% QuickC expands the above line to this line: %@NL@% %@NL@% %@AS@% val = 2 + 3 * 4;%@AE@%%@NL@% %@NL@% %@AU@% Use parentheses to avoid precedence problems in macros.%@AE@% %@NL@% %@NL@% Because the multiplication operator has higher precedence than the addition operator, this line assigns %@AS@% val %@AE@% the value 14 (or 2 + 12) rather than the correct value 20 (or 5 * 4). %@NL@% %@NL@% You can avoid the problem by enclosing the macro argument in parentheses each time it appears in the macro definition: %@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% %@AS@% #define FOURX(arg) ( (arg) * 4 ) %@AS@% %@AS@% main() %@AS@% { %@AS@% int val; %@AS@% val = FOURX(2 + 3); %@AS@% printf( "val = %d\n", val ); %@AS@% }%@AE@%%@NL@% %@NL@% Now the program expands this line %@NL@% %@NL@% %@AS@% val = FOURX(2 + 3);%@AE@%%@NL@% %@NL@% into this one: %@NL@% %@NL@% %@AS@% val = (2 + 3) * 4;%@AE@%%@NL@% %@NL@% The extra parentheses assure that the addition is performed before the multiplication, giving the desired result. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100025 @%%@AB@%Using Increment and Decrement Operators in Macro Arguments%@AE@%%@EH@%%@NL@% %@NL@% If a function-like macro evaluates an argument more than once, you should avoid passing it an expression that contains an increment or decrement operator: %@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% #define ABS(value) ( (value) >= 0 ? (value) : -(value) ) %@AS@% %@AS@% main() %@AS@% { %@AS@% int array[4] = {3, -20, -555, 6}; %@AS@% int *ptr = array; %@AS@% int val, count; %@AS@% for( count = 0; count < 4; count++ ) %@AS@% { %@AS@% val = ABS(*ptr++); /* Error! */ %@AS@% printf( "abs of array[%d] = %d\n", count, val ); %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% The program uses the %@AS@% ABS %@AE@% macro that was used to explain macros in Chapter 7, "Preprocessor Directives." The macro returns the absolute value of the argument you pass to it. %@NL@% %@NL@% The goal in this program is to display the absolute value of every element in %@AS@% array%@AE@%. It uses a %@AB@%for%@AE@% loop to step through the array and a pointer named %@AS@% %@AS@%ptr %@AE@% to access each array element in turn. Instead of the output you would expect, %@NL@% %@NL@% %@AS@% abs of array[0] = 3 %@AS@% abs of array[1] = 20 %@AS@% abs of array[2] = 555 %@AS@% abs of array[3] = 6%@AE@%%@NL@% %@NL@% the program gives this output: %@NL@% %@NL@% %@AS@% abs of array[0] = -20 %@AS@% abs of array[1] = -6 %@AS@% abs of array[2] = 8307 %@AS@% abs of array[3] = 24864%@AE@%%@NL@% %@NL@% (The last two array values may differ if you run the program. They are the contents of memory not used by the program.) %@NL@% %@NL@% The error occurs in this line, %@NL@% %@NL@% %@AS@% val = ABS(*ptr++); /* Error! */%@AE@%%@NL@% %@NL@% which QuickC expands as shown here: %@NL@% %@NL@% %@AS@% val = ( (*ptr++) >= 0 ? (*ptr++) : -(*ptr++) ); /* Error! */%@AE@%%@NL@% %@NL@% Because it uses the conditional operator, the %@AS@% ABS %@AE@% macro always evaluates its argument at least twice. This isn't a problem when the argument is a constant or simple variable. In the example, however, the argument is the expression %@AS@% *ptr++%@AE@%. Each time the macro evaluates this expression, the increment operator takes effect, causing %@AS@% ptr %@AE@% to point to the next element of %@AS@% array%@AE@%. %@NL@% %@NL@% The first time the program invokes the macro, %@AS@% ptr %@AE@% points to the first array element, %@AS@% array[0]%@AE@%. Since this element contains a nonnegative value (3) the macro evaluates the argument twice. The first evaluation takes the value that %@AS@% ptr %@AE@% points to and then increments %@AS@% ptr%@AE@%. Now %@AS@% ptr %@AE@% points to the second element, %@AS@% array[1]%@AE@%. The second evaluation takes the value of %@AS@% %@AS@%array[1] %@AE@% and increments %@AS@% ptr %@AE@% again. %@NL@% %@NL@% The first macro invocation not only returns an incorrect value (-20, the value of %@AS@% array[1]%@AE@% ). It also leaves %@AS@% ptr %@AE@% pointing to the third array element, making the results of later invocations unpredictable. (The pointer eventually moves past the last element of %@AS@% array %@AE@% and points to unknown data.) %@NL@% %@NL@% To avoid the problem, don't use the increment or decrement operators in arguments you pass to a macro. This revision removes the error by incrementing %@AS@%ptr %@AE@% in the %@AB@%for%@AE@% statement instead of the macro invocation: %@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% #define ABS(value) ( (value) >= 0 ? (value) : -(value) ) %@AS@% %@AS@% main() %@AS@% { %@AS@% int array[4] = {3, -20, -555, 6}; %@AS@% int *ptr = array; %@AS@% int val, count; %@AS@% for( count = 0; count < 4; count++, ptr++ ) %@AS@% { %@AS@% val = ABS(*ptr); %@AS@% printf( "abs of array[%d] = %d\n", count, val ); %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% This advice applies generally to QuickC library routines as well as macros you write. Remember, some run-time library routines are implemented as macros rather than C functions. If you're not sure whether a library routine is actually a macro, look it up in online help. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00100026 @%%@AB@%Miscellaneous Problems%@AE@%%@EH@%%@NL@% %@NL@% This section describes C programming problems that don't fit into any convenient category. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100027 @%%@AB@%Mismatching if and else Statements%@AE@%%@EH@%%@NL@% %@NL@% In nested %@AB@%if%@AE@% statements, each %@AB@%else%@AE@% is associated with the closest preceding %@AB@%if%@AE@% statement that does not have an %@AB@%else%@AE@%. Although indentation can make nested constructs more readable, it has no syntactical effect: %@NL@% %@NL@% %@AS@% if( val > 5 ) %@AS@% if( count == 10 ) %@AS@% val = sample; %@AS@% else %@AS@% val = 0;%@AE@%%@NL@% %@NL@% The indentation suggests that the %@AB@%else%@AE@% associates with the first %@AB@%if%@AE@%. In fact, the %@AB@%else%@AE@% is part of the second %@AB@%if%@AE@%, as shown more clearly here: %@NL@% %@NL@% %@AS@% if( val > 5 ) %@AS@% if( count == 10 ) %@AS@% val = sample; %@AS@% else %@AS@% val = 0;%@AE@%%@NL@% %@NL@% The %@AB@%else%@AE@% is part of the second %@AB@%if%@AE@% statement─the closest preceding %@AB@%if%@AE@% that doesn't have a matching %@AB@%else%@AE@%. To tie the %@AB@%else%@AE@% to the first %@AB@%if%@AE@%, you must use braces: %@NL@% %@NL@% %@AS@% if( val > 5 ) %@AS@% { %@AS@% if( count == 10 ) %@AS@% val = sample; %@AS@% } %@AS@% else %@AS@% val = 0;%@AE@%%@NL@% %@NL@% %@AU@% Indentation makes programs easier to read, but is ignored by the %@AU@%compiler.%@AE@% %@NL@% %@NL@% Now the %@AB@%else%@AE@% belongs with the outermost %@AB@%if%@AE@%. Remember, indentation is meaningful only to humans. The compiler relies strictly on punctuation when it translates the source file. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100028 @%%@AB@%Misplacing Semicolons%@AE@%%@EH@%%@NL@% %@NL@% Misplaced semicolons can cause subtle bugs: %@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int count; %@AS@% for( count = 0; count < 500; count++ ); /* Error! */ %@AS@% { %@AS@% printf( "count = %d\n", count ); %@AS@% printf( "And the beat goes on...\n" ); %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% You might expect the program to print the value of %@AS@% count %@AE@% 500 times, but this is all it prints: %@NL@% %@NL@% %@AS@% count = 500 %@AS@% And the beat goes on...%@AE@%%@NL@% %@NL@% The culprit is the extra semicolon immediately after the parentheses of the %@AB@%for%@AE@% statement. Its effect is more evident if we reformat the statement: %@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int count; %@AS@% for( count = 0; count < 500; count++ ) %@AS@% ; /* Null statement */ %@AS@% { %@AS@% printf( "count = %d\n", count ); %@AS@% printf( "And the beat goes on...\n" ); %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% Instead of printing the value of %@AS@% count %@AE@% 500 times, the program executes the null statement (%@AS@%;%@AE@%) 500 times. Null statements are perfectly legal in C, so the compiler has no way to tell this is a mistake. %@NL@% %@NL@% Since the null statement is interpreted as the loop body, the %@AB@%printf%@AE@% statements inside curly braces are interpreted as a statement block and executed once. Statement blocks usually appear as part of a loop, function definition, or decision- making statement, but it's legal to enclose any series of statements in braces. %@NL@% %@NL@% The program works as intended if you remove the extra semicolon: %@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int count; %@AS@% for( count = 0; count < 500; count++ ) %@AS@% { %@AS@% printf( "count = %d\n", count ); %@AS@% printf( "And the beat goes on...\n" ); %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% Here's another one. If you know QuickPascal, you might be tempted to put a semicolon after the parentheses of a function definition: %@NL@% %@NL@% %@AS@% void func( void ); %@AS@% %@AS@% void func( void ); /* Error! No semicolon here. */ %@AS@% { %@AS@% printf( "C is not Pascal\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% The function header causes a syntax error. While a function declaration requires a semicolon after its parentheses, a function definition does not. This code corrects the error: %@NL@% %@NL@% %@AS@% void func( void ); %@AS@% %@AS@% void func( void ) %@AS@% { %@AS@% printf( "C is not Pascal\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100029 @%%@AB@%Omitting Double Backslashes in DOS Path Specifications%@AE@%%@EH@%%@NL@% %@NL@% Because C uses the backslash (%@AB@%\%@AE@%) as an escape character, it's easy to create garbled path specifications: %@NL@% %@NL@% %@AS@% fp = fopen( "c:\temp\bodkin.txt", "w" );%@AE@%%@NL@% %@NL@% At first glance, the path specification in the string %@NL@% %@NL@% %@AS@% "c:\temp\bodkin.txt"%@AE@%%@NL@% %@NL@% looks good because that's how you would type it on the DOS command line. In a quoted string, however, the backslash is interpreted as an escape character. In this string the sequences %@AB@%\t%@AE@% and %@AB@%\b%@AE@% are interpreted as the tab and backspace character, respectively, garbling the path and file name. Even if the indicated file exists, this call to %@AB@%fopen%@AE@% is sure to fail. %@NL@% %@NL@% In a quoted string the escape sequence for a backslash character is a double backslash (%@AB@%\\%@AE@%). This statement solves the problem: %@NL@% %@NL@% %@AS@% fp = fopen( "c:\\temp\\bodkin.txt", "w" );%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100030 @%%@AB@%Omitting break Statements from a switch Statement%@AE@%%@EH@%%@NL@% %@NL@% Don't forget to include %@AB@%break%@AE@% statements when using the %@AB@%switch%@AE@% statement: %@NL@% %@NL@% %@AS@% switch( ch ) %@AS@% { %@AS@% case 'e': %@AS@% printf( "Bye bye\n" ); %@AS@% break; %@AS@% case 'l': %@AS@% printf( "Loading the file\n" ); %@AS@% load_file( fp ); %@AS@% break;%@AE@%%@NL@% %@NL@% %@AS@% case 's': %@AS@% printf( "Saving the file\n" ); %@AS@% write_file( fp ); /* Error! Missing break. */ %@AS@% case 'd': %@AS@% printf( "Deleting the file\n" ); %@AS@% kill_file( fp ); %@AS@% break; %@AS@% default: %@AS@% break; %@AS@% }%@AE@%%@NL@% %@NL@% In this code a %@AB@%break%@AE@% statement is missing from the statements following the third case label (the statements that print %@AS@% Saving the file %@AE@%). After those statements execute, execution falls through to the next case label, deleting the newly saved file. %@NL@% %@NL@% To avoid this problem, place a %@AB@%break%@AE@% at the end of every case item: %@NL@% %@NL@% %@AS@% case 's': %@AS@% printf( "Saving the file.\n" ); %@AS@% write_file( fp ); %@AS@% break;%@AE@%%@NL@% %@NL@% It's legal, of course, to write a program in which execution deliberately falls through from one case label to the next. In such cases you may want to add a comment to prevent confusion. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00100031 @%%@AB@%Mixing Signed and Unsigned Values%@AE@%%@EH@%%@NL@% %@NL@% If you explicitly compare two values of different types, the compiler normally catches the error. Some type mismatches aren't easy to spot, however, even for humans: %@NL@% %@NL@% %@AS@% #define CHARVAL '\xff' %@AS@% %@AS@% main() %@AS@% { %@AS@% unsigned char uc; %@AS@% uc = CHARVAL; %@AS@% if( uc == CHARVAL ) %@AS@% printf( "Eureka!" ); %@AS@% else %@AS@% printf( "Oops..." ); %@AS@% }%@AE@%%@NL@% %@NL@% The program prints %@AS@% Oops... %@AE@% which probably wasn't expected. The comparison between %@AS@% CHARVAL %@AE@% and %@AS@% uc %@AE@% is false even though both are clearly %@AB@%char%@AE@% values. %@NL@% %@NL@% The answer lies in the way the compiler converts %@AB@%signed%@AE@% and %@AB@%unsigned char%@AE@% values into %@AB@%int%@AE@% values for internal use. The %@AB@%#define%@AE@% directive, %@NL@% %@NL@% %@AS@% #define CHARVAL '\xff'%@AE@%%@NL@% %@NL@% defines %@AS@% CHARVAL %@AE@% as the constant 0xff. Since no sign is specified, the compiler treats the constant as a %@AB@%signed char%@AE@% value by default. When it converts the %@AB@%char%@AE@% to an %@AB@%int%@AE@% for internal use, as it does all character values, the compiler extends the value's sign. The result is an %@AB@%int%@AE@% with the value 0xffff. %@NL@% %@NL@% The variable %@AS@% uc %@AE@% undergoes the same internal conversion, with an important difference. Since %@AS@% uc %@AE@% is explicitly declared as %@AB@%unsigned%@AE@%, its value is converted to an %@AB@%int%@AE@% value of 0x00ff. %@NL@% %@NL@% When the two %@AB@%int%@AE@% values are compared, the result is false (0xffff does not equal 0x00ff). One solution is to explicitly cast %@AS@% CHARVAL %@AE@% to the desired type: %@NL@% %@NL@% %@AS@% #define CHARVAL (unsigned char)'\xff'%@AE@%%@NL@% %@NL@% Now the compiler compares two %@AB@%unsigned char%@AE@% values, giving the desired result. Another solution is to make %@AS@% CHARVAL %@AE@% an %@AB@%int%@AE@% instead of a %@AB@%char%@AE@% constant: %@NL@% %@NL@% %@AS@% #define CHARVAL 0xff%@AE@%%@NL@% %@NL@% Both solutions give the desired result, although the second is slightly less efficient. It creates word-size, rather than byte-size, machine-code instructions. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A-Part 02 @%%@1@%%@AB@%PART II Using C%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% Part 2 of %@AI@%C for Yourself%@AE@% is called "Using C" and should be read after you are familiar with basic C concepts. It covers practical topics that make it possible for you to write real programs. The features discussed in these chapters are provided in the QuickC run-time library, which, as you may recall from Part 1, is not part of the C language itself. %@NL@% %@NL@% While Part 1 was designed to be read sequentially, Part 2 is topical. So you don't need to read its chapters in any particular order. If you are new to C, however, it is recommended that you begin with Chapter 11, "Input and Output," which describes how to read and write data, and process files. Similarly, if you're not familiar with QuickC graphics, you should read Chapters 13-15 in order. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00110001 @%%@1@%%@AB@%Chapter 11 Input and Output%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% The first part of this book explored the fundamentals of the C language. In the second part (starting with this chapter), the topics include more complex and powerful functions: accessing disk files, creating high-resolution graphics, creating graphs, manipulating fonts, and adding assembly-language routines to your C programs. %@NL@% %@NL@% Program examples in previous chapters used %@AB@%printf%@AE@% to print to the screen. In this chapter, we'll cover %@AB@%printf%@AE@% in more detail, moving on to other I/O functions such as %@AB@%fprintf%@AE@%, which prints to a file, instead of to the screen. %@NL@% %@NL@% This chapter covers three broad topics: keyboard and screen input/output (I/O), reading and writing standard disk files, and low-level disk access. It also introduces several common string-handling functions. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00110002 @%%@AB@%Input and Output Streams%@AE@%%@EH@%%@NL@% %@NL@% Books about C often refer to "input streams" and "output streams." A stream is a sequence of bytes flowing into the program (input) or flowing out (output). The data might have originally come from the keyboard, a modem, a disk file, or some other peripheral device. The outgoing data might be sent out to the screen, a modem, or a disk file. %@NL@% %@NL@% Thus, when you see a phrase such as "opening a stream," it means opening a line of communication to the disk drive or to some other peripheral. %@NL@% %@NL@% %@AU@% Peripherals and files are called "streams" in C.%@AE@% %@NL@% %@NL@% The five streams always open and available for input or output are shown in Table 11.1. %@NL@% %@NL@% %@AB@%Table 11.1 %@AB@%Standard I/O Streams%@AE@%%@AE@% %@TH: 8 537 02 16 60 @%Name Stream%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%stdin%@AE@% Standard input (keyboard)%@AB@%stdout%@AE@% Standard output (screen)%@AB@%stderr%@AE@% Standard error channel (screen)%@AB@%stdprn%@AE@% Standard printer (parallel port)%@AB@%stdaux%@AE@% Standard auxiliary device (serial port)%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 8 537 02 16 60 @% %@NL@% %@2@%%@CR:C6A00110003 @%%@AB@%Screen and Keyboard I/O%@AE@%%@EH@%%@NL@% %@NL@% Imagine an application program that doesn't ever send output to the screen or accept input from the keyboard. It's possible to write such a program, but it's unlikely you'd ever want to. %@NL@% %@NL@% In most situations, you need to display various kinds of data on the screen and to accept input from the keyboard. "Manipulating and Printing Strings" introduces the functions commonly used to communicate back and forth. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110004 @%%@AB@%Manipulating and Printing Strings%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Always pass at least one string to the printf function.%@AE@% %@NL@% %@NL@% Previous chapters have used the %@AB@%printf%@AE@% function to display results on the screen. By now you should be accustomed to how it works. There's one rule you must always follow when using %@AB@%printf%@AE@%: pass it at least one format string, which may be a literal string or a pointer to a string. The string may or may not include format specifiers, which are defined below. %@NL@% %@NL@% The %@AB@%printf%@AE@% function always prints to the %@AB@%stdout%@AE@% device. Unless the output has been redirected, the standard output device is the screen. %@NL@% %@NL@% The following program illustrates some typical ways to manipulate strings and to print them: %@NL@% %@NL@% %@AS@% /* PRTSTR.C: Print strings. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <string.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% char aline[80], more[80]; %@AS@% char *strptr; %@AS@% %@AS@% /* aline = "Another line."; */ %@AS@% /* Note: This causes a compiler error */ %@AS@% %@AS@% strcpy( aline, "Another line." ); %@AS@% strcpy( more, aline ); %@AS@% strptr = aline; %@AS@% strcat( aline, "dog" ); %@AS@% printf( "A line of text." ); %@AS@% printf( aline ); %@AS@% printf( more ); %@AS@% printf( strptr ); %@AS@% }%@AE@%%@NL@% %@NL@% The declarations come first: %@NL@% %@NL@% %@AS@% char aline[80], more[80]; %@AS@% char *strptr;%@AE@%%@NL@% %@NL@% The variables %@AS@% aline %@AE@% and %@AS@% more %@AE@% are arrays of characters. In this program, they act as strings. Although these arrays have 80 characters each (numbered 0-79), the maximum string length is 79 characters, because strings must end with a null character. The variable %@AS@% strptr %@AE@% is a pointer to a string. %@NL@% %@NL@% If you've previously programmed in BASIC, you might expect to use the equal sign to assign a value to a string variable. The program won't compile if you remove the comment symbols from the following line: %@NL@% %@NL@% %@AS@% /* aline = "Another line."; */%@AE@%%@NL@% %@NL@% Faced with this line, QuickC prints the error message: %@NL@% %@NL@% %@AS@% 2106: '=' : Left operand must be lvalue%@AE@%%@NL@% %@NL@% (an "lvalue" is a value allowed on the left side of an equal sign). %@NL@% %@NL@% %@AU@% Use the strcpy function─ not the equal sign─ to copy a string.%@AE@% %@NL@% %@NL@% You can use the equal sign to assign a value to a numeric variable. When you're using strings, however, you almost always use the library function %@AB@%strcpy%@AE@%, which copies a string to a character array from either a string constant or another array: %@NL@% %@NL@% %@AS@% strcpy( aline, "Another line." ); %@AS@% strcpy( more, aline );%@AE@%%@NL@% %@NL@% The %@AB@%strcpy%@AE@% function makes an exact copy of a string. The first argument is the address of the destination string. The second is the address of the source string. The first %@AB@%strcpy%@AE@% above copies %@AS@%" Another line." %@AE@% to the %@AS@% aline %@AS@%%@AE@% string. The second copies %@AS@% aline %@AE@% to %@AS@% more%@AE@%. %@NL@% %@NL@% Note that the first argument must be the address of an array, but the second is either a string constant (enclosed in quotation marks) or the address of a character array. %@NL@% %@NL@% The 80-character arrays have more than enough room for the 13 characters of %@AS@%"Another line." %@AE@% and a null character. In your own programs, you should be aware of the declared size of an array and avoid overrunning the bounds of the array. See Chapter 10, "Programming Pitfalls," for more information about this programming mistake. %@NL@% %@NL@% It is possible to assign the address of a string to a pointer: %@NL@% %@NL@% %@AS@% strptr = aline;%@AE@%%@NL@% %@NL@% Notice that both %@AS@% strptr %@AE@% and %@AS@% aline %@AE@% point to the same string. There's one object in memory, but it has two different names. If %@AS@% aline %@AE@% changes, the same change occurs in the string referenced by %@AS@% strptr%@AE@%, because they're the same string. Below, the word %@AS@%"dog" %@AE@% is added to the end of the string %@AS@% %@AS@%aline%@AE@%: %@NL@% %@NL@% %@AS@% strcat( aline, "dog" );%@AE@%%@NL@% %@NL@% The %@AB@%strcat%@AE@% function concatenates one string to the end of a second string. In the line above, both %@AS@% aline %@AE@% and the string referenced by %@AS@% strptr %@AE@% have been changed from %@AS@% "Another line." %@AE@% to %@AS@% "Another line.dog".%@AE@% %@NL@% %@NL@% Now four %@AB@%printf%@AE@% statements execute: %@NL@% %@NL@% %@AS@% printf( "A line of text." ); %@AS@% printf( aline ); %@AS@% printf( more ); %@AS@% printf( strptr );%@AE@%%@NL@% %@NL@% The screen should look like this: %@NL@% %@NL@% %@AS@% A line of text.Another line.dogAnother line.Another line.dog%@AE@%%@NL@% %@NL@% To the first %@AB@%printf%@AE@% we passed a string constant. To the other three we passed names of strings. Concatenating %@AS@% aline %@AE@% and %@AS@% "dog" %@AE@% also affected the string referenced by %@AS@% strptr%@AE@%, because they both point to the same string in memory. The contents of %@AS@% more %@AE@% weren't affected, however, because the %@AB@%strcpy%@AE@% function makes a complete and unique copy of the source string at the memory location referenced by %@AS@% more%@AE@%. %@NL@% %@NL@% Unfortunately, the strings ran together. As we saw in Chapter 1, "Anatomy of a C Program," %@AB@%printf%@AE@% is unlike QuickBASIC's %@AB@%PRINT%@AE@% command or Pascal's %@AB@% %@AB@%Writeln%@AE@% procedure in one respect: it does not automatically move the cursor to the beginning of the next line. You need to include the newline character (%@AB@%\n%@AE@%), which is one of a series of available escape codes discussed in Chapter 4, "Data Types." The program below includes a few examples of escape codes, each of which begins with the backslash character: %@NL@% %@NL@% %@AS@% /* PRTESC.C: Print escape characters \",\n, and \t. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <string.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% char b[80]; %@AS@% int i,j; %@AS@% %@AS@% strcpy( b, "and seven years ago\n" ); %@AS@% printf( "\"Four score\n" ); %@AS@% printf( b ); %@AS@% printf( "\tone tab\n\t\ttwo tabs\n\t\t\tthree tabs\n" ); %@AS@% i = sizeof( b ); %@AS@% j = strlen( b ); %@AS@% printf( "Size is %d\nLength is %d.\n", i, j ); %@AS@% }%@AE@%%@NL@% %@NL@% If you compile and run the PRTESC.C program, the following text prints on the screen: %@NL@% %@NL@% %@AS@% "Four score %@AS@% and seven years ago %@AS@% one tab %@AS@% two tabs %@AS@% three tabs %@AS@% Size is 80 %@AS@% Length is 20.%@AE@%%@NL@% %@NL@% To print a newline character in a string, type a backslash and the letter n (%@AB@%\n%@AE@%). For a quotation mark, use %@AB@%\"%@AE@%. For tabs, use %@AB@%\t%@AE@%. Escape sequences can appear anywhere within a string: %@NL@% %@NL@% %@AS@% printf( "\tone tab\n\t\ttwo tabs\n\t\t\tthree tabs\n" );%@AE@%%@NL@% %@NL@% You'll find complete lists of escape characters in Appendix A, "C Language Guide," and in online help. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Finding the Size%@AE@%%@EH@%%@NL@% %@NL@% The last call to %@AB@%printf%@AE@% in PRTESC.C provides two pieces of information: the size of the character array and the length of the string inside the array. %@NL@% %@NL@% The variable %@AS@% b %@AE@% was declared to be an 80-character array, but the string inside %@AS@%b %@AE@% contains only 20 characters; it holds 19 letters plus one newline character. Although typing %@AB@%\n%@AE@% takes two characters, it's stored in memory as one character─ the ASCII value 10. As we'll see later in this chapter, the newline character is sometimes expanded to two characters (a carriage return and a linefeed) when it is written to disk. But while it's in memory, it's a single character. %@NL@% %@NL@% %@AU@% The sizeof operator examines array size; the %@AE@%%@AB@%strlen%@AE@% function returns the length of a string. %@NL@% %@NL@% There are two methods available to find the size of arrays and strings. The %@AB@%sizeof %@AE@%operator returns the size (in bytes) of an identifier or type. The string-handling function %@AB@%strlen%@AE@% counts the number of characters in a string, up to but not including the null that marks the end of the string: %@NL@% %@NL@% %@AS@% i = sizeof( b ); %@AS@% j = strlen( b ); %@AS@% printf( "Size is %d\nLength is %d.\n", i, j );%@AE@%%@NL@% %@NL@% The final line of the program PRTESC.C prints out two integer values, which follow the format string. When %@AB@%printf%@AE@% evaluates the format string, it substitutes the two values for the %@AB@%%d%@AE@% specifiers: %@NL@% %@NL@% %@AS@% Size is 80 %@AS@% Length is 20%@AE@%%@NL@% %@NL@% The %@AB@%sizeof%@AE@% operator is part of the C language. In this example, it evaluates to the value 80, which is the size of the array. The %@AB@%strlen%@AE@% function is a library function for measuring strings (up to, but not including the null at the end). It returns a 20 because that's the length of the string. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110005 @%%@AB@%Printing Numeric Values%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The printf format string may hold one or more format specifiers.%@AE@% %@NL@% %@NL@% We've seen how %@AB@%printf%@AE@% requires at least one string (or a pointer to a string). To print variables and values, place a comma and the name of the variable or value after the format string. Then, within the format string, include a format specification. See Table 11.2. %@NL@% %@NL@% %@AB@%Table 11.2 %@AB@%Common Format Specifications%@AE@%%@AE@% %@TH: 10 675 02 22 54 @%Specification Format%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%%c%@AE@% Print a character%@AB@%%d%@AE@% Print a decimal integer%@AB@%%f%@AE@% Print a floating-point number%@AB@%%i%@AE@% Print a decimal integer (same as %@AB@%%d%@AE@%)%@AB@%%s%@AE@% Print a string%@AB@%%u%@AE@% Print an unsigned integer%@AB@%%x%@AE@% Print in hexadecimal format%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 10 675 02 22 54 @% The percent sign (%@AB@%%%@AE@%) always marks the beginning of a format specification. The letters %@AB@%c%@AE@%, %@AB@%d%@AE@%, %@AB@%f%@AE@%, %@AB@%i%@AE@%, %@AB@%s%@AE@%, %@AB@%u%@AE@%, and %@AB@%x%@AE@% are called the "type." Between the percent sign and the type, you may include optional specifications for flags, width, or precision values. %@NL@% %@NL@% At the very least, you must include the type, as in the program below: %@NL@% %@NL@% %@AS@% /* NFORMAT.C: Print numbers and a string. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <string.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int a = -765, %@AS@% b = 1, %@AS@% c = 44000, %@AS@% d = 33; %@AS@% float e = 1.33E8, %@AS@% f = -0.1234567, %@AS@% g = 12345.6789, %@AS@% h = 1.0; %@AS@% char i[80]; %@AS@% %@AS@% strcpy( i, "word 1, word 2, word 3, word 4, word 5" ); %@AS@% %@AS@% printf( "Unformatted:\n%d %d %d %d\n", a, b, c, d ); %@AS@% printf( "%f %f %f %f\n", e, f, g, h ); %@AS@% printf( "%s\n", i ); %@AS@% }%@AE@%%@NL@% %@NL@% The output looks like this: %@NL@% %@NL@% %@AS@% Unformatted: %@AS@% -765 1 -21536 33 %@AS@% 133000000.000000 -0.123457 12345.678711 1.000000 %@AS@% word 1, word 2, word 3, word 4, word 5%@AE@%%@NL@% %@NL@% If you carefully compare NFORMAT.C with its output, you'll notice some unexpected results. For example, the variable %@AS@% c%@AE@%, which was initialized to 44000, has somehow changed to -21536. %@NL@% %@NL@% The %@AB@%%d%@AE@% format specification applies to signed integers in the range -32768 to +32767. The value of %@AS@% c %@AE@% (44000) is outside that range, but still within the realm of unsigned integers, which can hold values up to +65535. The proper format specification would be %@AB@%%u%@AE@% (where %@AS@% u %@AE@% represents the unsigned type). %@NL@% %@NL@% Two of the floating-point values have changed, too. The %@AB@%%f%@AE@% specification defaults to 6 digits of precision to the right of the decimal point. The value of %@AS@% f %@AE@% (.1234567) is therefore rounded off to a precision of 6 digits: .123457. Also, the limitations of floating-point accuracy transform the value of %@AS@% g %@AE@% from 12345.6789 to 12345.678711. If you modify the program, changing the %@AS@% float %@AE@% declarations to %@AS@% double%@AE@%, the second problem disappears. The variable %@AS@% g %@AE@% prints correctly as 12345.67. %@NL@% %@NL@% Between the%@AB@%%%@AE@% and the type character, you may include two numbers separated by a period. The first number is called the "width;" the second is the "precision." The width and precision affect integers, floating-point numbers, and strings in different ways. For example, we could specify a width of 2 and precision of 3 for each of the above variables: %@NL@% %@NL@% %@AS@% printf( "\nWidth 2, Precision 3:\n" ); %@AS@% printf( "%2.3d %2.3d %2.3u %2.3d\n", a, b, c, d ); %@AS@% printf( "%2.3f %2.3f %2.3f %2.3f\n", e, f, g, h ); %@AS@% printf( "%2.3s\n", i );%@AE@%%@NL@% %@NL@% (Note that the variable %@AS@% c %@AE@% has a format specifier of %@AS@% %2.3u %@AE@% instead of %@AS@% %@AS@%%2.3d%@AE@%.) The screen displays the following lines: %@NL@% %@NL@% %@AS@% Width 2, Precision 3: %@AS@% -765 001 44000 033 %@AS@% 133000000.000 -0.123 12345.679 1.000 %@AS@% wor%@AE@%%@NL@% %@NL@% For integers, the precision of 3 causes at least 3 digits to print, preceded by leading zeros. For floating-point numbers, the precision of 3 truncates fractions to 3 digits to the right of the decimal point. For strings, the precision of 3 causes only 3 characters to print. The string output is truncated to the right. Numbers are never truncated, however. %@NL@% %@NL@% We can change the width to 8 and the precision to 1: %@NL@% %@NL@% %@AS@% printf( "\nWidth 8, Precision 1:\n" ); %@AS@% printf( "%8.1d %8.1d %8.1u %8.1d\n", a, b, c, d ); %@AS@% printf( "%8.1e %8.1f %8.1f %8.1f\n", e, f, g, h ); %@AS@% printf( "%8.1s\n", i );%@AE@%%@NL@% %@NL@% We made an additional modification by printing the variable %@AS@% e %@AE@% as an %@AB@%%e%@AE@% type instead of an %@AB@%%f%@AE@% type. This prints the value of %@AS@% e %@AE@% (1.33E8) in exponential format: %@NL@% %@NL@% %@AS@% Width 8, Precision 1: %@AS@% -765 1 44000 33 %@AS@% 1.3e+008 -0.1 12345.7 1.0 %@AS@% w%@AE@%%@NL@% %@NL@% The width controls the printing area: all 3 variable types are printed in fields 8 characters wide. The precision of 1 affects different data types in different ways: the integers print at least 1 digit; the floating-point numbers print only the first number to the right of the decimal point; and the string prints as the first character only. Each value prints flush right in its field. %@NL@% %@NL@% Between the %@AB@%%%@AE@% and the width, you may also insert a flag. The plus flag (%@AB@%+%@AE@%), for example, forces numbers to print with a leading sign: %@NL@% %@NL@% %@AS@% printf( "\nForced signs, Width 10, Precision 2:\n" ); %@AS@% printf( "%+10.2d %+10.2d %+10.2u %+10.2d\n", a, b, c, d ); %@AS@% printf( "%+10.2e %+10.2f %+10.2f %+10.2f\n", e, f, g, h ); %@AS@% printf( "%+10.2s\n", i );%@AE@%%@NL@% %@NL@% Note that the plus flag has no effect on strings or on unsigned integers: %@NL@% %@NL@% %@AS@% Forced signs, Width 10, Precision 2: %@AS@% -765 +01 44000 +33 %@AS@% +1.33e+008 -0.12 +12345.68 +1.00 %@AS@% wo%@AE@%%@NL@% %@NL@% Another flag is the number 0, which forces leading zeros to print within the limits of the width. If you only specify the width, the system default is used for the precision. You can use the type %@AB@%%x%@AE@% to represent hexadecimal; it displays the letters a-f in lowercase. If you prefer uppercase, you can use %@AB@%%X%@AE@% instead. %@NL@% %@NL@% %@AS@% printf( "\nHexadecimal, Forced Zeros, Width 6:\n" ); %@AS@% printf( "%06x %06x %06x %06x\n", a, b, c, d );%@AE@%%@NL@% %@NL@% The %@AB@%printf%@AE@% statements above display these lines: %@NL@% %@NL@% %@AS@% Hexadecimal, Forced Zeros, Width 6: %@AS@% 00fd03 000001 00abe0 000021%@AE@%%@NL@% %@NL@% For strings, the width and precision specifiers describe the field width and the number of characters printed. Note the minus sign in the final line, which forces the truncated string to print from the left: %@NL@% %@NL@% %@AS@% printf( "\nWidth 40, Precision 10:\n" ); %@AS@% printf( "%40.10s\n", i ); %@AS@% %@AS@% printf( "\nWidth 40, Precision 20:\n" ); %@AS@% printf( "%40.20s\n", i ); %@AS@% %@AS@% printf( "\nFlush left, Width 40, Precision 20:\n" ); %@AS@% printf( "%-40.20s\n", i );%@AE@%%@NL@% %@NL@% The lines are displayed on the screen as follows: %@NL@% %@NL@% %@AS@% Width 40, Precision 10: %@AS@% word 1, wo %@AS@% %@AS@% Width 40, Precision 20: %@AS@% word 1, word 2, word %@AS@% %@AS@% Flush left, Width 40, Precision 20: %@AS@% word 1, word 2, word %@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110006 @%%@AB@%Using scanf for Keyboard Input%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Pass a variable address to scanf, not a variable value.%@AE@% %@NL@% %@NL@% While %@AB@%printf%@AE@% is the most widely used output function, %@AB@%scanf %@AE@%is the most popular for input. The arguments and format strings passed to%@AB@% scanf%@AE@% resemble the arguments for %@AB@%printf%@AE@%, except for one requirement: the %@AB@%scanf%@AE@% function always takes pointers. You never pass a variable value to %@AB@%scanf%@AE@%, you always pass the variable address so that %@AB@%scanf%@AE@% can store data in the memory location that contains the input variable. %@NL@% %@NL@% The first argument for %@AB@%scanf%@AE@% is always a format string. Additional arguments include the addresses of variables to which values will be assigned. %@NL@% %@NL@% The program below demonstrates several ways to use %@AB@%scanf%@AE@% and various other I/O functions: %@NL@% %@NL@% %@AS@% /* INPUT.C: Read keyboard. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <conio.h> %@AS@% #include <ctype.h>%@AE@%%@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% int num; %@AS@% char c; %@AS@% char name[80]; %@AS@% float rb; %@AS@% %@AS@% puts( "** Type \"Name:\" and your name" ); %@AS@% scanf( "Name: %40s", name ); %@AS@% printf( "** You typed this:\n%s", name ); %@AS@% puts( "\n\n** Try again, with the gets function." ); %@AS@% fflush( stdin ); %@AS@% gets( name ); %@AS@% printf( "** You typed this:\n%s\n", name ); %@AS@% %@AS@% printf( "\n** Now type an integer.\n" ); %@AS@% scanf( "%i", &num ); %@AS@% sprintf( name, "** You typed this number: %i\n", num ); %@AS@% puts( name ); %@AS@% %@AS@% fflush( stdin ); %@AS@% printf( "** Enter a floating-point value.\n" ); %@AS@% scanf( "%f", &rb ); %@AS@% printf( "** The answer is %f or %e\n", rb, rb ); %@AS@% %@AS@% printf( "** Continue? Y or N\n" ); %@AS@% do %@AS@% { %@AS@% c = getch(); %@AS@% c = tolower( c ); %@AS@% } while( c != 'y' && c != 'n' ); %@AS@% }%@AE@%%@NL@% %@NL@% First, the %@AB@%puts%@AE@% function prints a string that requests input from the user. Then %@AB@%scanf%@AE@% reads the input: %@NL@% %@NL@% %@AS@% puts( "** Type \"Name:\" and your name" ); %@AS@% scanf( "Name: %40s", name );%@AE@%%@NL@% %@NL@% Unfortunately, the use of %@AB@%scanf%@AE@% for string input creates some difficulties. For one thing, you're forced to type %@AS@% Name: %@AE@% before typing the rest of the string. (If you don't type %@AS@% Name:%@AE@%, %@AB@%scanf%@AE@% won't put a value into the %@AS@% name %@AE@% variable.) %@NL@% %@NL@% A second problem is that %@AB@%scanf%@AE@% reads the input stream until it finds a white-space character: a SPACE, TAB, or ENTER. %@NL@% %@NL@% The prompt below appears on the screen: %@NL@% %@NL@% %@AS@% ** Type "Name:" and your name%@AE@%%@NL@% %@NL@% You might type this (you must begin the line with %@AS@%"Name:" %@AE@%): %@NL@% %@NL@% %@AS@% Name: F. Scott Fitzgerald%@AE@%%@NL@% %@NL@% The next line takes effect: %@NL@% %@NL@% %@AS@% printf( "** You typed this:\n%s", name );%@AE@%%@NL@% %@NL@% Which prints the following line: %@NL@% %@NL@% %@AS@% ** You typed this: %@AS@% F.%@AE@%%@NL@% %@NL@% The string passed to the %@AB@%scanf%@AE@% function told it to expect %@AS@% "Name:" %@AE@% and then to read a string, storing it in the %@AS@% name %@AE@% variable. %@NL@% %@NL@% Since the %@AB@%scanf%@AE@% function reads strings until it finds a white-space character, the value of %@AS@% name %@AE@% is " %@AS@% F%@AE@%." In addition, the words %@AS@% Scott %@AS@%Fitzgerald %@AE@% are waiting in the input stream. To clear any stream, use the %@AB@%fflush%@AE@% function: %@NL@% %@NL@% %@AS@% puts( "\n\n** Now try it again, with the gets function." ); %@AS@% fflush( stdin ); %@AS@% gets( name );%@AE@%%@NL@% %@NL@% To clear the buffer associated with a stream (including disk files), call %@AB@%fflush%@AE@%, passing the pointer to the file or stream. In the example above, %@AS@% %@AS@%stdin %@AE@% is the standard input device, the keyboard. %@NL@% %@NL@% The %@AB@%puts%@AE@% function acts like a limited version of %@AB@%printf%@AE@%. It prints a string to the standard output device, but can't insert formatted variable values. You pass it a string constant or the name of a string. Also, it always adds a newline to the end of the string it prints. %@NL@% %@NL@% %@AU@% It is usually preferable to use gets when working with string input.%@AE@% %@NL@% %@NL@% The %@AB@%gets%@AE@% function receives an entire line from the standard input device and places the line in an array of characters. It does not include the newline character typed by the user. It does, however, add a null to the end of the line, to make the series of characters into a string. When you're working with string input, %@AB@%gets%@AE@% is generally preferable to %@AB@%scanf%@AE@%. %@NL@% %@NL@% For numeric values, %@AB@%scanf%@AE@% is the function of choice: %@NL@% %@NL@% %@AS@% printf( "\n** Now type an integer.\n" ); %@AS@% scanf( "%i", &num ); %@AS@% sprintf( name, "** You typed the number: %i\n", num ); %@AS@% puts( name );%@AE@%%@NL@% %@NL@% The format string %@AB@%%i%@AE@% forces %@AB@%scanf%@AE@% to treat the input as an integer. The second argument is the address of the variable %@AS@% num%@AE@%. %@NL@% %@NL@% The letter %@AB@%s%@AE@% in %@AB@%sprintf%@AE@% marks it as a string function. (There is also a %@AB@%sscanf%@AE@% function that handles strings, but we won't discuss it here.) Instead of printing the format string to the screen, as %@AB@%printf%@AE@% would do, %@AB@%sprintf%@AE@% prints the results to another string. Note that %@AB@%scanf%@AE@% requires the address of %@AS@% num%@AE@%, but %@AB@%sprintf%@AE@% uses its value. %@NL@% %@NL@% The next %@AB@%scanf%@AE@% in program INPUT.C treats the input as a floating-point number: %@NL@% %@NL@% %@AS@% scanf( "%f", &rb ); %@AS@% printf( "** The answer is %f or %e\n", rb, rb );%@AE@%%@NL@% %@NL@% If you enter -555.12, the computer responds: %@NL@% %@NL@% %@AS@% ** The answer is -555.119995 or -5.551200e+002%@AE@%%@NL@% %@NL@% Finally, the program uses %@AB@%getch%@AE@% to receive a character from the input stream: %@NL@% %@NL@% %@AS@% printf( "** Continue? Y or N\n" ); %@AS@% %@AS@% do %@AS@% { %@AS@% c = getch(); %@AS@% c = tolower( c ); %@AS@% } while( c != 'y' && c != 'n' );%@AE@%%@NL@% %@NL@% The %@AB@%getch%@AE@% function returns a character. That value, in turn, is passed to %@AB@%tolower%@AE@%, which converts any uppercase characters to lowercase (in case the CAPS LOCK key is on). Then, the byte is assigned to the variable %@AS@% c%@AE@%. The %@AB@%do%@AE@% loop continues processing characters until you press %@AS@% y %@AE@% or %@AS@% n%@AE@%. The program then ends. This simple example ends no matter which key ( %@AS@% y %@AE@% or %@AS@% n %@AE@%) you press. A real program would take some action based on the value returned by the %@AB@%getch%@AE@% function. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00110007 @%%@AB@%Standard Disk I/O%@AE@%%@EH@%%@NL@% %@NL@% If you can read input from the keyboard and write output to the screen, you'll find standard disk files relatively easy to manipulate. There are three rules to remember: %@NL@% %@NL@% %@NL@% 1. You can't do anything with a disk file until you open it. The act of opening a file gives you a %@AB@%FILE%@AE@% pointer through which you can access the file.%@NL@% %@NL@% 2. While the file is open, you can use most of the screen and keyboard I/O functions if you precede them with the letter %@AB@%f%@AE@% (%@AB@%fprintf%@AE@% instead of %@AB@%printf%@AE@%, for example). The file-handling functions work the same as their counterparts, but you must add the %@AB@%FILE%@AE@% pointer.%@NL@% %@NL@% 3. When you're finished with a file, it's good programming practice to close it. When %@AB@%exit%@AE@% ends the execution of a program, all previously open files are closed (if you'd rather leave them open, use %@AB@%_exit%@AE@% instead of %@AB@%exit%@AE@%).%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110008 @%%@AB@%Creating and Writing to a Text File%@AE@%%@EH@%%@NL@% %@NL@% The WRFILE.C program opens a text file, writes a string to it, and closes the file. %@NL@% %@NL@% %@AS@% /* WRFILE.C: Create and write to a disk file. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% FILE *fp; %@AS@% %@AS@% if( (fp = fopen( "c:\\testfile.asc","w" )) != NULL ) %@AS@% { %@AS@% fputs( "Example string", fp ); %@AS@% fputc( '\n', fp ); %@AS@% fclose( fp ); %@AS@% } %@AS@% else %@AS@% printf( "error message\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% You must include the standard I/O header file (%@AS@% #include <stdio.h> %@AE@%) whenever you plan to call input or output functions. It contains essential definitions and prototypes that you need. %@NL@% %@NL@% The only variable in this program is %@AS@% fp %@AE@% which is declared as a pointer to a %@AB@%FILE%@AE@%. %@AB@%FILE%@AE@% is defined in STDIO.H as a structure of %@AB@%_iobuf%@AE@% type, but we don't need to know the specifics. We will refer to the variable %@AS@% fp %@AE@% as a "%@AB@%FILE%@AE@% pointer." %@NL@% %@NL@% The first statement combines several operations in one line: %@NL@% %@NL@% %@AS@% if( (fp = fopen( "c:\\testfile.asc", "w" )) != NULL )%@AE@%%@NL@% %@NL@% The %@AB@%fopen%@AE@% function opens a file. It expects two parameters, both of which are literal strings or pointers to strings. You provide the name of the file to be opened and the type (read, write, or append). The six types of files are listed in Table 11.3. %@NL@% %@NL@% %@AB@%Table 11.3 %@AB@%Disk File Types %@AE@%%@AE@% %@TH: 24 1319 02 34 42 @%Type Action%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%r%@AE@% Open an existing file for reading.%@AB@%w%@AE@% Create and open a file for writing. Any existing file is replaced. If the file doesn't exist, a new file is created.%@AB@%a%@AE@% Open a file for appending. Data is added to the end of an existing file or a new file is created.%@AB@%r+%@AE@% Open an existing file for reading and writing. %@AS@%%@AE@%%@AB@%w+%@AE@% Create and open a file for reading and writing. An existing file is replaced.%@AB@%a+%@AE@% Open a file for reading and appending. Data is added to the end of an existing file or a new file is created.%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 24 1319 02 34 42 @% In WRFILE.C, the file called %@AS@% c:\testfile.asc %@AE@% is opened for writing with type %@AS@%"w" %@AE@% (a string, not the character %@AS@% 'w' %@AE@% in single quotes). We plan to write to it. %@NL@% %@NL@% Notice that the file-name string as it appears in the %@AB@%fopen%@AE@% statement contains two backslashes: %@AS@%"c:\\testfile.asc"%@AE@%. If you tried to use the string %@AS@%"c:\testfile. asc"%@AE@%, which looks correct, the character sequence %@AS@% \t %@AE@% would be incorrectly interpreted as a tab character. C automatically converts the two backslashes in the string to a single backslash. %@AS@% %@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Getting a FILE Pointer%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%fopen%@AE@% function returns the address of a %@AB@%FILE%@AE@%. This value is assigned to %@AS@% %@AS@%fp%@AE@%, which is the %@AB@%FILE%@AE@% pointer used in all subsequent file operations. %@NL@% %@NL@% If something goes wrong─if the disk is full or not in the drive or write-protected or whatever─%@AB@%fopen%@AE@% doesn't return a %@AB@%FILE%@AE@% pointer. When %@AB@%fopen%@AE@% fails, it returns a null value. %@NL@% %@NL@% What we're looking for is any %@AB@%FILE%@AE@% pointer that's not null: %@NL@% %@NL@% %@AS@% if( (fp = fopen( "c:\\testfile.asc","w" )) != NULL )%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Writing to the File%@AE@%%@EH@%%@NL@% %@NL@% As we saw earlier, %@AB@%puts%@AE@% displays a string on the screen. Add an %@AB@%f%@AE@% to it and the result is %@AB@%fputs%@AE@%, which works similarly. It sends the string to a specified stream (a file) instead of to the standard output device: %@NL@% %@NL@% %@AS@% fputs( "Example string", fp );%@AE@%%@NL@% %@NL@% The function %@AB@%fputs%@AE@% takes two parameters: a pointer to the string and the %@AB@%FILE%@AE@% pointer. In this and other I/O functions, you refer to the file by name only once (when you use %@AB@%fopen%@AE@%). Thereafter, you use its %@AB@%FILE%@AE@% pointer. %@NL@% %@NL@% The %@AB@%fputs%@AE@% function writes the entire string to the file but does not include the null that marks the end of the string. Nor does it write a newline character─unless the string already contains a newline. %@NL@% %@NL@% The %@AB@%fputc%@AE@% function writes a character to a file. In the following line, the newline character is sent to the file: %@NL@% %@NL@% %@AS@% fputc( '\n', fp );%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Closing the File%@AE@%%@EH@%%@NL@% %@NL@% When the writing is done, %@AB@%fclose%@AE@% closes the file: %@NL@% %@NL@% %@AS@% fclose( fp );%@AE@%%@NL@% %@NL@% Conceptually, you can imagine that file I/O functions such as %@AB@%fputs%@AE@% and %@AB@%fputc%@AE@% write directly to the disk file. In reality, they're storing strings and characters in an intermediate area (called a "memory buffer"). When the buffer fills up, the entire chunk of memory is sent to the file. The process of emptying the buffer is called "flushing." You may forcibly flush the buffer with the %@AB@%fflush%@AE@% and %@AB@%fclose%@AE@% functions. If you do not close the file before exiting the program, the buffer is not flushed and you may lose data that might remain there. %@NL@% %@NL@% The %@AB@%else%@AE@% clause in WRFILE.C should execute only if something has gone wrong with the %@AB@%fopen%@AE@% function: %@NL@% %@NL@% %@AS@% else %@AS@% printf( "error message\n" );%@AE@%%@NL@% %@NL@% This line executes if an error occurs when %@AB@%fopen%@AE@% tries to create the file. Handling errors is covered in more detail later in this chapter. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110009 @%%@AB@%Reading a Text File in Binary Mode%@AE@%%@EH@%%@NL@% %@NL@% The WRFILE.C program that created and wrote to a file was fairly simple. Here's an equally simple program to read the file just created: %@NL@% %@NL@% %@AS@% /* RDFILE.C: Read a file and print characters to the screen. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% int c; %@AS@% FILE *fp; %@AS@% %@AS@% if( fp = fopen( "c:\\testfile.asc", "rb" ) ) %@AS@% { %@AS@% while( (c = fgetc( fp )) != EOF ) %@AS@% printf( " %c\t%d\n", c, c ); %@AS@% printf( "\nEnd of file marker: %d", c ); %@AS@% fclose( fp ); %@AS@% } %@AS@% else %@AS@% printf( "Error in opening file\n" ); %@AS@% }%@AE@%%@NL@% %@NL@% Although we plan to read the characters as eight-bit entities, the variable %@AS@% %@AS@%c %@AE@% should be declared as an %@AB@%int%@AE@% instead of a %@AB@%char%@AE@%. All of the incoming characters will be bytes the size of a %@AB@%char%@AE@%, except one. %@NL@% %@NL@% When the file has been read from beginning to end, the end-of-file (%@AB@%EOF%@AE@%) marker appears on the stream. Within QuickC, an integer value of -1 (0xFFFF) represents %@AB@%EOF%@AE@%. To correctly identify this value, the variable %@AS@% c %@AE@% must be an integer. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Opening a File for Binary Reading%@AE@%%@EH@%%@NL@% %@NL@% In the line below, the %@AB@%fopen%@AE@% function attempts to open a file. The first argument is the file name; the second is the type and mode, both of which may be literal strings or pointers to strings: %@NL@% %@NL@% %@AS@% if( fp = fopen( "c:\\testfile.asc", "rb" ) )%@AE@%%@NL@% %@NL@% The single backslash character used in path specifications must once again be represented by two backslashes. The file type is %@AB@%r%@AE@% for read-only. The additional %@AB@%b%@AE@% character forces the file to be read in binary mode instead of text mode. The differences between binary and text files are discussed later in this chapter. %@NL@% %@NL@% The %@AB@%fopen%@AE@% function returns a pointer to a %@AB@%FILE%@AE@%. If %@AB@%fopen%@AE@% fails, it returns a %@AB@%NULL%@AE@% pointer. %@NL@% %@NL@% Finally, the %@AB@%if%@AE@% expression tests for a null value. The original WRFILE.C program included the %@AS@% != NULL %@AE@% test for inequality. Within the test expression of an %@AB@%if%@AE@% or a %@AB@%while%@AE@%, a 0 value is always false and any other value is considered true. In other words, should %@AS@% fp %@AE@% receive a valid nonzero address from %@AB@%fopen%@AE@%, the program continues. If something goes wrong, the remaining lines don't execute and the program drops through to the %@AB@%else%@AE@%. %@NL@% %@NL@% Note that the expression above uses an assignment operator (%@AB@%=%@AE@%), not an equality operator (%@AB@%==%@AE@%). The value returned by %@AB@%fopen%@AE@% is always assigned to %@AS@% %@AS@%fp %@AE@%; they aren't being compared to each other. Then the %@AB@%if%@AE@% expression tests that value for truth or falsity. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Getting a Character%@AE@%%@EH@%%@NL@% %@NL@% The key to the next line in RDFILE.C is the %@AB@%fgetc%@AE@% function, to which you pass a %@AB@%FILE%@AE@% pointer. It returns the next character from the given file: %@NL@% %@NL@% %@AS@% while( (c = fgetc( fp )) != EOF )%@AE@%%@NL@% %@NL@% The character is assigned to the integer variable %@AS@% c%@AE@%. As long as the character doesn't equal %@AB@%EOF%@AE@%, the %@AB@%while%@AE@% loop continues. %@NL@% %@NL@% The end-of-file marker equals -1, but it's preferable to use the symbolic constant %@AB@%EOF%@AE@%. If the program is transported to another computer, you might find %@AB@%EOF%@AE@% has another value. Using the symbolic constant allows you to maintain compatibility between computers and operating systems. %@NL@% %@NL@% For the same reason, it's preferable to test for %@AB@%NULL%@AE@% instead of assuming that %@AB@%NULL%@AE@% will always equal 0. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Viewing the File%@AE@%%@EH@%%@NL@% %@NL@% Since there's only one line inside the %@AB@%while%@AE@% loop, it's not necessary to enclose it in curly braces. The variable %@AS@% c %@AE@% contains the character read from the file. It then can be printed: %@NL@% %@NL@% %@AS@% printf( " %c\t%d\n", c, c );%@AE@%%@NL@% %@NL@% The characters from the file print twice, once as a character (%@AB@%%c%@AE@%) and once as a decimal number (%@AB@%%d%@AE@%), separated by a tab stop. This %@AB@%printf%@AE@% statement repeats until %@AB@%fgetc%@AE@% (inside the %@AB@%while%@AE@% loop) finds no more characters in the file. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110010 @%%@AB@%Binary and Text Files%@AE@%%@EH@%%@NL@% %@NL@% Normally, you wouldn't write a file in text mode and then read it in binary mode. As a general rule, you pick whichever mode is more appropriate (text mode for text or binary mode for data) and stick with it. %@NL@% %@NL@% A somewhat baffling thing happened in the example above, however. The WRFILE.C program wrote %@AS@%"Example string" %@AE@% to a disk file and then added a newline character. That should be a total of 15 characters. But if you examine the directory, you'll see the file uses 16 bytes. %@NL@% %@NL@% Where did the extra byte come from? %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Testing Text Mode%@AE@%%@EH@%%@NL@% %@NL@% If you ran the RDFILE.C program, you probably noticed two characters followed the line: a carriage return (ASCII 13) and a linefeed (ASCII 10). If you make the following change to the program, the output of RDFILE.C is different: %@NL@% %@NL@% %@AS@% if( (fp = fopen( "c:\\testfile.asc","rt" )) != NULL )%@AE@%%@NL@% %@NL@% The only modification is that the second string is %@AS@%"rt" %@AE@% instead of %@AS@%"rb"%@AE@%. The %@AB@%t%@AE@% represents text mode; the %@AB@%b%@AE@% is binary mode. If you don't specify a mode, the %@AB@%fopen%@AE@% function defaults to text mode. %@NL@% %@NL@% The list below shows the output of the two programs. %@NL@% %@NL@% %@TH: 20 1313 02 33 43 @%RDFILE.C (binary mode) RDFILE.C (text mode)%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AS@%E69%@AE@% %@AS@%E69%@AE@%%@AS@%x120%@AE@% %@AS@%x120%@AE@%%@AS@%a97%@AE@% %@AS@%a97%@AE@%%@AS@%m109%@AE@% %@AS@%m109%@AE@%%@AS@%p112%@AE@% %@AS@%p112%@AE@%%@AS@%l108%@AE@% %@AS@%l108%@AE@%%@AS@%e101%@AE@% %@AS@%e101%@AE@%%@AS@%32%@AE@% %@AS@%32%@AE@%%@AS@%s115%@AE@% %@AS@%s115%@AE@%%@AS@%t116%@AE@% %@AS@%t116%@AE@%%@AS@%r114%@AE@% %@AS@%r114%@AE@%%@AS@%i105%@AE@% %@AS@%i105%@AE@%%@AS@%n110%@AE@% %@AS@%n110%@AE@%%@AS@%g103%@AE@% %@AS@%g103%@AE@%%@AS@%13 %@AE@% %@AS@%10%@AE@%%@AS@%10 %@AE@% %@AS@%End-of-file marker: -1%@AE@%%@AS@%End-of-file marker: -1%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 20 1313 02 33 43 @% In binary mode there seems to be two characters after the string. In text mode there's only one. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Ends-of-Lines, Ends-of-Files%@AE@%%@EH@%%@NL@% %@NL@% The two modes─binary and text─treat end-of-line (%@AB@%EOL%@AE@%) characters and end-of-file (%@AB@%EOF%@AE@%) characters in different ways. %@NL@% %@NL@% In DOS, a line of text ends with a carriage return (CR) and a linefeed (LF), which appear above as ASCII 13 plus ASCII 10. In the UNIX operating system, which has close ties to the C language, a single ASCII 10 (the newline character) marks the end of a line. %@NL@% %@NL@% The once-popular CP/M operating system signals the end of files with a CTRL+Z character (ASCII 26, 0x1A)─a tradition that carried forward to DOS. This is not the case with UNIX (and C), which don't use a unique %@AB@%EOF%@AE@% character. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Text Mode Translations%@AE@%%@EH@%%@NL@% %@NL@% It's important to understand the differences between text mode and binary mode when writing and reading disk files. No translations are made in binary mode. In text mode, however, the end-of-line and end-of-file characters are translated. %@NL@% %@NL@% When you read a file in text mode and a CR-LF combination appears in the stream, the two characters are translated to one newline character. The opposite translation occurs when you write a file in text mode: each CR-LF combination is translated to one newline character. In other words, the newline is represented by two characters on disk and one character in memory. These translations do not occur when you read and write a file in binary mode. %@NL@% %@NL@% When you read a file in text mode and a CTRL+Z (0x1A) character appears in the stream, the character is interpreted as the end-of-file character. However, when you're in text mode and you close a file to which you've been writing, a CTRL+Z is not placed in the file as the last character. In binary mode, the CTRL+Z character has no special meaning (it is not interpreted as the end-of-file character). %@NL@% %@NL@% The difference between text mode and binary mode is relatively minor when you're handling strings, but it's important when you're writing numeric values to disk files. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110011 @%%@AB@%Text Format for Numeric Variables%@AE@%%@EH@%%@NL@% %@NL@% Many programs, of course, use numeric as well as character data. When you wish to save numbers, you have two choices: text mode or binary mode. The SVTEXT.C program below illustrates the less desirable way of creating files for numeric variables. %@NL@% %@NL@% %@AS@% /* SVTEXT.C: Save integer variables as text. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% %@AS@% int list[] = { 53, -23456, 50, 500, 5000, -99 }; %@AS@% extern int errno; %@AS@% char fname[] = "numtext"; %@AS@% char temp[81]; %@AS@% %@AS@% main() %@AS@% { %@AS@% FILE *fptr; %@AS@% int i; %@AS@% %@AS@% if( (fptr = fopen( "numtext","wt" )) != NULL ) %@AS@% { %@AS@% for( i=0; i<6; i++ ) %@AS@% fprintf( fptr, "Item %d: %6d \n", i, list[i] ); %@AS@% fclose( fptr ); %@AS@% } %@AS@% else %@AS@% printf( "Error: Couldn't create file.\n" ); %@AS@% %@AS@% if( (fptr = fopen( "badname", "rt" )) != NULL ) %@AS@% { %@AS@% /* do nothing */ %@AS@% } %@AS@% else %@AS@% { %@AS@% printf( "Error number: %d\n\t", errno ); %@AS@% perror( "Couldn't open file BADNAME\n\t" ); %@AS@% } %@AS@% %@AS@% if( (fptr = fopen( fname, "rt" )) != NULL ) %@AS@% { %@AS@% list[0] = 0; %@AS@% fscanf( fptr, "Item %d: %d \n", &i, &list[0] ); %@AS@% printf( "Values read from file:\t %d %d\n", i, list[0] ); %@AS@% fgets( temp, 80, fptr ); %@AS@% printf( "String from file: \t%s\n", temp ); %@AS@% while( (i = fgetc( fptr )) != '\n' ) %@AS@% printf( "char: %c \t ASCII: %d \n", i, i ); %@AS@% rewind( fptr ); %@AS@% printf( "Rewind to start -->\t%s", fgets( temp, 80, fptr ) ); %@AS@% fclose( fptr ); %@AS@% } %@AS@% else printf( "Trouble opening %s \n", fname ); %@AS@% }%@AE@%%@NL@% %@NL@% The SVTEXT.C program does three things: %@NL@% %@NL@% %@NL@% 1. First, it creates a text file called NUMTEXT. If you TYPE NUMTEXT from the DOS prompt or load the NUMTEXT file into a word processor, it looks like this: %@NL@% %@AS@% Item 0: 53 %@AS@% Item 1: -23456 %@AS@% Item 2: 50 %@AS@% Item 3: 500 %@AS@% Item 4: 5000 %@AS@% Item 5: -99%@AE@%%@NL@% %@NL@% %@NL@% 2. Next, SVTEXT.C deliberately attempts to open a nonexistent file called BADNAME, to cause a disk error. This section serves no purpose except to illustrate error handling.%@NL@% %@NL@% 3. Finally, it reads parts of NUMTEXT, using several file-input functions.%@NL@% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Opening the File for Writing%@AE@%%@EH@%%@NL@% %@NL@% By now, the %@AB@%fopen%@AE@% function should look familiar to you. The only change in the block below is the %@AS@%"wt" %@AE@% mode. The %@AB@%fopen%@AE@% function returns a %@AB@%NULL%@AE@% if any errors occur, so the block after the %@AB@%if%@AE@% should execute if %@AB@%fopen%@AE@% succeeds. %@NL@% %@NL@% %@AS@% if( (fptr = fopen( "numtext","wt" )) != NULL ) %@AS@% { %@AS@% for( i=0; i<6; i++ ) %@AS@% fprintf( fptr, "Item %d: %6d \n", i, list[i] ); %@AS@% fclose( fptr ); %@AS@% } %@AS@% else %@AS@% printf( "Error: Couldn't create file.\n" );%@AE@%%@NL@% %@NL@% The %@AB@%for%@AE@% loop counts from 0 to 5, printing 6 strings to the file. The %@AB@%fprintf%@AE@% function works the same as %@AB@%printf%@AE@% with one change. You must place the %@AB@%FILE%@AE@% pointer before the format string. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Error Handling%@AE@%%@EH@%%@NL@% %@NL@% To illustrate what happens when something goes wrong, the next line creates a disk error (as long as you don't have a file called BADNAME in your working directory). %@NL@% %@NL@% %@AS@% if( (fptr = fopen( "badname", "rt" )) != NULL )%@AE@%%@NL@% %@NL@% The %@AB@%if%@AE@% block is empty, because we expect the program to drop through to the %@AB@%else%@AE@% clause that handles errors: %@NL@% %@NL@% %@AS@% else %@AS@% { %@AS@% printf( "Error number: %d\n\t", errno ); %@AS@% perror( "Couldn't open file BADNAME\n\t" ); %@AS@% }%@AE@%%@NL@% %@NL@% The %@AB@%else%@AE@% block shows two ways you can deal with errors. Note that the %@AB@%errno%@AE@% variable, which was declared as an external integer, has never been assigned a value. QuickC automatically puts error numbers into %@AB@%errno%@AE@%. In this program, the error number is printed to the screen. In your own programs, you might wish to branch to various error-handling routines, based on the value in the system variable %@AB@%errno%@AE@%. For a list of values for %@AB@%errno%@AE@%, see the individual online help entries for file-handling functions. %@NL@% %@NL@% It's important to remember that the standard output device is the screen and that %@AB@%printf%@AE@% sends messages to %@AB@%stdout%@AE@%. However, if you redirect output to a disk file, using a command line such as %@AS@% SVTEXT > MYFILE%@AE@%, the %@AB@%printf%@AE@% statement prints the error message to MYFILE. In most cases, you'd prefer to see the error message on the screen. %@NL@% %@NL@% The second, and better, way to handle I/O errors is the %@AB@%perror%@AE@% function, which prints two strings: one that you pass to it and one that spells out─in English─the error message. This message goes to the standard error stream (%@AB@%stderr%@AE@%), which is always the screen, regardless of whether you've redirected output or not. For this reason, %@AB@%perror%@AE@% is preferable to %@AB@%printf%@AE@% for printing error messages. %@NL@% %@NL@% The error messages should look like this on your screen: %@NL@% %@NL@% %@AS@% Error number: 2 %@AS@% Couldn't open file BADNAME %@AS@% : No such file or directory%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Reading Text with fscanf%@AE@%%@EH@%%@NL@% %@NL@% The final %@AB@%fopen%@AE@% in SVTEXT.C opens the file created earlier: %@NL@% %@NL@% %@AS@% if( (fptr = fopen( fname, "rt" )) != NULL )%@AE@%%@NL@% %@NL@% Note that we passed the name of a string rather than a literal string. %@NL@% %@NL@% Below, %@AB@%fscanf%@AE@% reads in two numeric variables from the first string in the file. Note that it works the same as %@AB@%scanf%@AE@%, but you add the %@AB@%FILE%@AE@% pointer as the first argument: %@NL@% %@NL@% %@AS@% fscanf( fptr, "Item %d: %d \n", &i, &list[0] ); %@AS@% printf( "Values read from file:\t %d %d\n", i, list[0] );%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Reading Text with fgets and fgetc%@AE@%%@EH@%%@NL@% %@NL@% At this point, the first line in the file has been read and converted to two integer values. The file is straight text, so you can treat the second line as a string: %@NL@% %@NL@% %@AS@% fgets( temp, 80, fptr ); %@AS@% printf( "String from file: \t%s\n", temp );%@AE@%%@NL@% %@NL@% The %@AB@%fgets%@AE@% function requires three arguments: a pointer to a string, the maximum number of characters to read, and the %@AB@%FILE%@AE@% pointer. The function stops reading characters when it encounters a newline character or when it reaches the maximum number of characters or the end of the file. %@NL@% %@NL@% If you prefer, you can input the characters one by one: %@NL@% %@NL@% %@AS@% while( (i = fgetc( fptr )) != '\n' ) %@AS@% printf( "char: %c \t ASCII: %d \n", i, i );%@AE@%%@NL@% %@NL@% The %@AB@%printf%@AE@% inside the %@AB@%while%@AE@% loop prints each character as a character (%@AB@%%c%@AE@%) and also as a decimal value (%@AB@%%d%@AE@%). The %@AB@%while%@AE@% loop continues reading characters until it finds the end of the line. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Back to the Beginning%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%rewind%@AE@% function resets the position pointer to the beginning of the file. In the program line below, the first line from the file is printed: %@NL@% %@NL@% %@AS@% rewind( fptr ); %@AS@% printf( "Rewind to start -->\t%s", fgets( temp, 80, fptr ) );%@AE@%%@NL@% %@NL@% The screen output looks like this: %@NL@% %@NL@% %@AS@% Error number: 2 %@AS@% Couldn't open file BADNAME %@AS@% : No such file or directory %@AS@% Values read from file: 0 53 %@AS@% String from file: Item 1: -23456 %@AS@% %@AS@% char: I ASCII: 73 %@AS@% char: t ASCII: 116 %@AS@% char: e ASCII: 101 %@AS@% char: m ASCII: 109 %@AS@% char: ASCII: 32 %@AS@% char: 2 ASCII: 50 %@AS@% char: : ASCII: 58 %@AS@% char: ASCII: 32 %@AS@% char: ASCII: 32 %@AS@% char: ASCII: 32 %@AS@% char: ASCII: 32 %@AS@% char: ASCII: 32 %@AS@% char: 5 ASCII: 53 %@AS@% char: 0 ASCII: 48 %@AS@% char: ASCII: 32 %@AS@% Rewind to start --> Item 0: 53%@AE@%%@NL@% %@NL@% %@AU@% It is inefficient to store numeric data in text format.%@AE@% %@NL@% %@NL@% There seem to be quite a few white-space characters in the text file. Text files are great for text, but they store numeric values in a wasteful way. Binary format offers several advantages. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110012 @%%@AB@%Using Binary Format%@AE@%%@EH@%%@NL@% %@NL@% When you're processing strings of ASCII characters and writing them to disk files, it matters little whether you use text mode or binary mode, as long as you're consistent. The advantage of text mode is that it translates newlines to the carriage-return-line-feed combination, making it possible to use the DOS TYPE command to view the file. %@NL@% %@NL@% When you're processing numeric values (integers and floating-point numbers), however, you may wish to save your variables in binary mode files, in binary format, for the following reasons: %@NL@% %@NL@% %@NL@% ■ Binary format almost always saves disk space. In text mode, the number 12345.678 would require eight bytes for the ASCII numerals, one byte for the decimal point, and one or more bytes for a separator between variables. In binary format, a floating-point number uses four bytes, regardless of its value. Short integers use only two bytes.%@NL@% %@NL@% ■ Binary format generally saves computer time. When you use %@AB@%fprintf%@AE@% to print a numeric value to disk, the computer must translate the internal binary representation to a series of characters. Likewise, when %@AB@%fscanf%@AE@% reads characters into memory, the ASCII values must be translated to the internal binary format. In binary format, none of these translations takes place.%@NL@% %@NL@% ■ Binary format preserves the precision of floating-point numbers. The translation from binary to decimal ASCII and back to binary affects the precision of the value.%@NL@% %@NL@% ■ A binary save of arrays or structures is fast. It's not necessary to read through an array of 100 items and print each one to the disk file. Instead, you call the %@AB@%fwrite%@AE@% function (discussed below) once, passing it the size of the array to be saved.%@NL@% %@NL@% %@STUB@% %@AI@%NOTE %@AE@%Binary mode is separate from binary format. The modes (binary and text) are parameters you pass to the %@AB@%fopen%@AE@% function. They affect the translation of newlines and the placing of %@AI@%EOF%@AE@% markers. The formats (binary and text) are ways of representing numeric values. An integer in binary format always occupies two bytes on disk. An integer in text format uses a variable number of bytes: it might contain one character (5) or six (-10186).%@NL@% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Opening a Binary File%@AE@%%@EH@%%@NL@% %@NL@% The SVBIN.C program below creates two binary mode files with the variables saved in binary format: %@NL@% %@NL@% %@AS@% /* SVBIN.C: Save integer variables in binary format. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #define ASIZE 10 %@AS@% %@AS@% main() %@AS@% { %@AS@% FILE *ap; %@AS@% int zebra[ASIZE], acopy[ASIZE], bcopy[ASIZE]; %@AS@% int i; %@AS@% %@AS@% for( i = 0; i < ASIZE; i++ ) %@AS@% zebra[i] = 7700 + i; %@AS@% %@AS@% if( (ap = fopen( "binfile", "wb" )) != NULL ) %@AS@% { %@AS@% fwrite( zebra, sizeof(zebra), 1, ap ); %@AS@% fclose( ap ); %@AS@% } %@AS@% else %@AS@% perror( "Write error" ); %@AS@% %@AS@% if( (ap = fopen( "morebin", "wb" )) != NULL ) %@AS@% { %@AS@% fwrite( &zebra[0], sizeof(zebra[0]), ASIZE, ap ); %@AS@% fclose( ap ); %@AS@% } %@AS@% else %@AS@% perror( "Write error" ); %@AS@% %@AS@% if( (ap = fopen( "binfile", "rb" )) != NULL ) %@AS@% { %@AS@% printf( "Hexadecimal values in binfile:\n" ); %@AS@% while( (i = fgetc( ap )) != EOF ) %@AS@% printf( "%02X ", i ); %@AS@% rewind( ap ); %@AS@% fread( acopy, sizeof(acopy), 1, ap ); %@AS@% rewind( ap ); %@AS@% fread( &bcopy[0], sizeof( bcopy[0] ), ASIZE, ap); %@AS@% for( i=0; i<ASIZE; i++ ) %@AS@% printf( "\nItem %d = %d\t%d", i, acopy[i], bcopy[i] ); %@AS@% fclose( ap ); %@AS@% %@AS@% } %@AS@% else %@AS@% perror( "Read error" ); %@AS@% %@AS@% }%@AE@%%@NL@% %@NL@% Focus your attention on the %@AS@% zebra %@AE@% array. It contains 10 integers, because the array size %@AS@% ASIZE %@AE@% was defined as 10. First, some values are stored in %@AS@% %@AS@%zebra %@AE@% (in a moment, we'll see why 7700-7709 are significant): %@NL@% %@NL@% %@AS@% for( i = 0; i < ASIZE; i++ ) %@AS@% zebra[i] = 7700 + i;%@AE@%%@NL@% %@NL@% Next, we open a file and use %@AB@%fwrite%@AE@% to write the entire array to disk: %@NL@% %@NL@% %@AS@% if( (ap = fopen( "binfile", "wb" )) != NULL ) %@AS@% { %@AS@% fwrite( zebra, sizeof(zebra), 1, ap ); %@AS@% fclose( ap ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Writing an Array in One Line%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%fwrite%@AE@% function requires four pieces of information: %@NL@% %@NL@% %@NL@% 1. The address of the item (a variable, array, or structure)%@NL@% %@NL@% 2. The size of the item in bytes%@NL@% %@NL@% 3. The number of items to be written%@NL@% %@NL@% 4. The %@AB@%FILE%@AE@% pointer for a previously opened binary mode file%@NL@% %@NL@% %@NL@% In this example, the first argument, %@AS@% zebra %@AE@% is an array and, as you may remember from Chapter 8, "Pointers," the name of an array is the address of the array. %@NL@% %@NL@% To provide the second argument for %@AB@%fwrite%@AE@%, SVBIN.C uses the %@AB@%sizeof%@AE@% operator, which returns the number of bytes a variable requires. Because %@AS@% zebra %@AE@% is an array of 10 integers and integers use 2 bytes each, the size of %@AS@% zebra %@AE@% should be 20. If you view a directory of your disk after running this program, you'll notice that the file BINFILE is exactly 20 bytes long. %@NL@% %@NL@% The third argument tells %@AB@%fwrite%@AE@% how many items to write to the file. We have 1 array, so this parameter is 1. %@NL@% %@NL@% The fourth argument is the %@AB@%FILE%@AE@% pointer returned by %@AB@%fopen%@AE@%. %@NL@% %@NL@% There's another way to copy the 20 bytes of %@AS@% zebra %@AE@% to the file. After writing to BINFILE, the program uses the %@AB@%fopen%@AE@% function to create a second file called MOREBIN. The following %@AB@%fwrite%@AE@% line writes 10 integers instead of 1 array: %@NL@% %@NL@% %@AS@% fwrite( &zebra[0], sizeof(zebra[0]), ASIZE, ap );%@AE@%%@NL@% %@NL@% The second and third arguments have changed. Instead of passing the size of the array (20) and writing 1 copy of the array, we're accessing the size of 1 element (2 bytes) and writing 10 of them (using the symbolic constant %@AB@%ASIZE%@AE@%). The contents of this disk file should match, byte for byte, the contents of BINFILE. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Examining the Binary Contents%@AE@%%@EH@%%@NL@% %@NL@% Finally, we look at what's inside the file BINFILE. It is opened for reading as a binary file: %@NL@% %@NL@% %@AS@% if( (ap = fopen( "binfile", "rb" )) != NULL )%@AE@%%@NL@% %@NL@% A short %@AB@%while%@AE@% loop reads the bytes from BINFILE and displays them in hexadecimal notation: %@NL@% %@NL@% %@AS@% printf( "Hexadecimal values in binfile:\n" ); %@AS@% while( (i = fgetc( ap )) != EOF ) %@AS@% printf( "%02X ", i );%@AE@%%@NL@% %@NL@% After running SVBIN.C, the screen displays these values: %@NL@% %@NL@% %@AS@% 14 1E 15 1E 16 1E 17 1E 18 1E %@AS@% 19 1E 1A 1E 1B 1E 1C 1E 1D 1E%@AE@%%@NL@% %@NL@% The low byte precedes the high byte, so the first two bytes represent the number 0x1E14, which is 7700 in decimal. The next two bytes equal 7701, and so on. %@NL@% %@NL@% A curious thing happens when you run SVBIN.C and then try to treat the 20-byte file as text. If you TYPE BINFILE from the DOS command line, the file appears as gibberish (of course), and you see only 12 of the 20 characters on the screen. Where did the other characters go? Recall the previous discussion of binary and text files. In DOS, a CTRL+Z (0x1A) marks the end of a text file. And in the midst of our binary file is one of those %@AB@%EOF%@AE@% characters. It's not acting as an %@AB@%EOF%@AE@%; it's part of the number 0x1E1A. But if you ever open this file in text mode, you'll be unable to read past the twelfth byte. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Retrieving the Values from Disk%@AE@%%@EH@%%@NL@% %@NL@% Most of the time, you won't want to read a binary file one byte at a time. Instead, you call %@AB@%fread%@AE@%, which reads a disk file and stores the values in a variable, an array, or a structure. The %@AB@%fread%@AE@% function complements %@AB@%fwrite%@AE@%. It takes four parameters: %@NL@% %@NL@% %@NL@% 1. The address of the variable%@NL@% %@NL@% 2. The size of the variable in bytes%@NL@% %@NL@% 3. The number of values to read%@NL@% %@NL@% 4. The %@AB@%FILE%@AE@% pointer that references a binary file opened for reading%@NL@% %@NL@% %@NL@% Here's one way to read values into an array: %@NL@% %@NL@% %@AS@% rewind( ap ); %@AS@% fread( acopy, sizeof( acopy ), 1, ap );%@AE@%%@NL@% %@NL@% The %@AB@%rewind%@AE@% command is necessary because we've already read through the file once. The %@AS@% acopy %@AE@% and %@AS@% bcopy %@AE@% arrays are the same size as our original %@AS@% %@AS@%zebra %@AE@%array. To fill an array with this technique, pass the address, the size of the entire array, a number 1, and the %@AB@%FILE%@AE@% pointer. %@NL@% %@NL@% A second way to fill an array is to pass the size of a single element and the number of elements you want to read: %@NL@% %@NL@% %@AS@% rewind( ap ); %@AS@% fread( &bcopy[0], sizeof( bcopy[0] ), ASIZE, ap );%@AE@%%@NL@% %@NL@% In the first example of %@AB@%fread%@AE@%, we pass the information that the array %@AS@% acopy %@AS@%%@AE@% is 20 bytes long and we want to read it once. In the second example, we pass the size of an integer (2 bytes) and ask for 10 of them. In either case, 20 bytes are transferred. %@NL@% %@NL@% Just to make sure both arrays are equal, we can print them out: %@NL@% %@NL@% %@AS@% for( i = 0; i < ASIZE; i++ ) %@AS@% printf( "\nItem %d = %d\t%d", i, acopy[i], bcopy[i] ); %@AS@% fclose( ap );%@AE@%%@NL@% %@NL@% The screen displays the values 7700 through 7709, which survived the trek from %@AS@% zebra %@AE@% to BINFILE and back again. These values were stored in the %@AS@% %@AS@%zebra %@AE@% array, written to a binary file, then read back into the %@AS@% acopy %@AE@% and %@AS@% %@AS@%bcopy %@AE@% arrays. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00110013 @%%@AB@%Low-Level Input and Output%@AE@%%@EH@%%@NL@% %@NL@% The file-handling routines such as %@AB@%fopen%@AE@%, %@AB@%fprintf%@AE@%, and %@AB@%fclose%@AE@% are called "standard" because they're defined in the ANSI standard. Code that uses the standard routines will generally be portable from one machine to another. %@NL@% %@NL@% In addition to the standard file-handling functions, the QuickC library includes some low-level I/O functions, which allow more direct access to disk files. %@NL@% %@NL@% The low-level I/O routines (also called "system-level") are generally not portable. They work in DOS and OS/2, but they may not work elsewhere. They're also a little more difficult to use. Instead of declaring a pointer to a %@AB@%FILE%@AE@% structure, you must allocate your own buffer and manage transfer of the bytes yourself. You move values into the buffer, then send the contents of the buffer to disk. %@NL@% %@NL@% %@AU@% Low-level routines can be more efficient, but they usually aren't %@AU@%portable.%@AE@% %@NL@% %@NL@% Low-level routines have some advantages, though. One is that you have more control over the machine. Another is that low-level I/O can be faster than standard I/O, if you know what you're doing. The choice is up to you: portability versus efficiency. You should choose one or the other; it's not a good idea to mix standard and system-level routines. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00110014 @%%@AB@%Low-Level Reading and Writing%@AE@%%@EH@%%@NL@% %@NL@% The program RWFILE.C illustrates some of the low-level, file-handling commands. It creates a file, writes to it, and closes it. Then the file is opened for reading and the contents of the file are displayed on the screen. %@NL@% %@NL@% %@AS@% /* RWFILE.C: Read and write a file. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <string.h> %@AS@% #include <fcntl.h> %@AS@% #include <sys\types.h> %@AS@% #include <sys\stat.h> %@AS@% #include <io.h> %@AS@% %@AS@% #define BUFF 512 %@AS@% %@AS@% main() %@AS@% { %@AS@% char inbuffer[BUFF]; %@AS@% char outbuffer[BUFF]; %@AS@% int infile, outfile, length, num; %@AS@% %@AS@% strcpy( outbuffer, "Happy Birthday." ); %@AS@% length = strlen( outbuffer ); %@AS@% length++; %@AS@% %@AS@% if( (outfile = open( "testfile.bin", %@AS@% O_CREAT | O_WRONLY | O_BINARY, S_IWRITE )) != -1 ) %@AS@% { %@AS@% if( (num = write( outfile, outbuffer, length )) == -1 ) %@AS@% perror( "Error in writing" ); %@AS@% printf( "\nBytes written to file: %d\n", num ); %@AS@% close( outfile ); %@AS@% } %@AS@% else %@AS@% perror( "Error opening outfile" );%@AE@%%@NL@% %@NL@% %@AS@% if( (infile = open( "testfile.bin", O_RDONLY | O_BINARY )) != -1 ) %@AS@% { %@AS@% while( length = read( infile, inbuffer, BUFF ) ) %@AS@% printf( "%d bytes received so far.\n", length ); %@AS@% close( infile ); %@AS@% printf( "%s\n", inbuffer ); %@AS@% } %@AS@% else %@AS@% perror( "Error opening infile" ); %@AS@% }%@AE@%%@NL@% %@NL@% Several header files must be included: %@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% #include <fcntl.h> %@AS@% #include <sys\types.h> %@AS@% #include <sys\stat.h> %@AS@% #include <io.h>%@AE@%%@NL@% %@NL@% The symbolic constant %@AS@% BUFF %@AE@% is defined as 512. This value is used immediately in the declaration of two buffers: %@NL@% %@NL@% %@AS@% char inbuffer[BUFF]; %@AS@% char outbuffer[BUFF];%@AE@%%@NL@% %@NL@% Note that we don't need %@AB@%FILE%@AE@% structures anywhere in the program. The standard I/O routines automatically allocated space for a buffer. Since we're operating closer to the DOS level, we must allocate our own buffers, instead of relying on the system. If you set the buffer size to a sufficiently large value, QuickC will run out of stack space. When this happens, you may either make the buffers global variables or use the %@AB@%malloc%@AE@% function to allocate an additional chunk of memory. %@NL@% %@NL@% The %@AB@%open%@AE@% function takes three parameters: %@NL@% %@NL@% %@AS@% if( (outfile = open( "testfile.bin", %@AS@% O_CREAT | O_WRONLY | O_BINARY, S_IWRITE )) != -1 )%@AE@%%@NL@% %@NL@% The first parameter is the file name. The second is a sequence of "oflags" that are combined with the OR operator. The oflags determine which type of file will be opened: it will be created (%@AS@% O_CREAT%@AE@% ), it will be write-only (%@AS@% %@AS@%O_WRONLY%@AE@% ), and it will be a binary─not a text─file (%@AS@% O_BINARY%@AE@% ). When you create a new file, you must include the third parameter: %@AS@% S_IWRITE%@AE@%. %@NL@% %@NL@% The %@AB@%open%@AE@% function returns a file handle, which is assigned to the integer variable %@AS@% outfile%@AE@%. Note that this is an integer, not a pointer to a %@AB@%FILE%@AE@% structure. If anything goes wrong, a value of -1 is returned by %@AB@%open%@AE@%, and we should test for this. %@NL@% %@NL@% Table 11.4 summarizes the differences between %@AB@%fopen%@AE@% and %@AB@%open%@AE@%. %@NL@% %@NL@% %@AB@%Table 11.4 %@AB@%Standard vs. Low-Level%@AE@%%@AE@% %@TH: 11 674 02 10 27 18 21 @%Function Error Parameters Returns Condition%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%fopen%@AE@% File name, type Pointer to %@AB@%FILE %@AE@% NULL (%@AB@%r%@AE@%, %@AB@%w%@AE@%, %@AB@%a%@AE@%), and mode (%@AB@%t%@AE@%,%@AB@% b%@AE@%) %@AB@%open%@AE@% File name, oflags File handle -1 (integer) %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 11 674 02 10 27 18 21 @% %@NL@% %@4@%%@AB@%Low-Level Writing%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%write%@AE@% function takes three parameters: %@NL@% %@NL@% %@NL@% 1. The file handle returned by %@AB@%open%@AE@%%@NL@% %@NL@% 2. The address of the buffer%@NL@% %@NL@% 3. The number of bytes to write%@NL@% %@NL@% %@NL@% You, the programmer, are responsible for filling up the buffer. The %@AB@%write%@AE@% function returns the number of bytes actually written to the file. %@NL@% %@NL@% %@AS@% if( (num = write( outfile, outbuffer, length )) == -1 ) %@AS@% perror( "Error in writing" ); %@AS@% printf( "\nBytes written to file: %d\n", num ); %@AS@% close( outfile );%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Low-Level Reading%@AE@%%@EH@%%@NL@% %@NL@% Next, we open the file for reading. Again, the oflags are required: %@NL@% %@NL@% %@AS@% if( (infile = open( "testfile.bin", O_RDONLY | O_BINARY )) != -1 ) %@AS@% { %@AS@% while( length = read( infile, inbuffer, BUFF ) ) %@AS@% printf( "%d bytes received so far.\n", length ); %@AS@% close( infile ); %@AS@% printf( "%s\n", inbuffer ); %@AS@% }%@AE@%%@NL@% %@NL@% The %@AB@%read%@AE@% function takes three parameters: %@NL@% %@NL@% %@NL@% 1. The file handle%@NL@% %@NL@% 2. The address of the buffer%@NL@% %@NL@% 3. The size of the buffer%@NL@% %@NL@% %@NL@% The value returned is the number of bytes read. The %@AB@%while%@AE@% loop continues as long as there are characters in the stream. In a real application, you'll have to handle the bytes stored in the buffer. %@NL@% %@NL@% The low-level file functions are unbuffered. When you call %@AB@%write%@AE@%, the bytes are written directly to the disk file. The standard file function %@AB@%fwrite%@AE@% doesn't write data to disk; it writes to a buffer. The buffer is transferred to disk when the buffer fills up, when the %@AB@%fflush%@AE@% function is called, or when the file is closed. As a gen-eral rule, you should not mix buffered and unbuffered routines. Use the standard routines or the low-level routines, but not both. %@NL@% %@NL@% This chapter started with keyboard input and screen output and led into discussions of file I/O. The following chapters cover in greater depth assembly language routines and some specialized types of screen output, including high-resolution graphics, fonts, and presentation graphics. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00120001 @%%@1@%%@AB@%Chapter 12 Dynamic Memory Allocation%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% A program that allocates memory "dynamically" (as it runs) can respond flexibly to a user's needs, creating new data structures when the need arises and discarding them when their job is done. %@NL@% %@NL@% As you read this chapter you'll learn how to allocate memory with the %@AB@%malloc%@AE@% library function and free memory with the %@AB@%free%@AE@% function. We'll also look at two related functions, %@AB@%calloc%@AE@% and %@AB@%realloc%@AE@%. %@NL@% %@NL@% Memory allocation requires the use of pointers. If you're not familiar with pointers, read Chapter 8, "Pointers," before tackling this chapter. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00120002 @%%@AB@%Why Allocate?%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The malloc family of library functions can allocate memory during run time.%@AE@% %@NL@% %@NL@% The %@AB@%malloc%@AE@% (memory allocate) family of library functions enables you to allocate blocks of memory dynamically. The capability to create new data structures on the fly lets you tailor a program's behavior precisely to the user's needs. %@NL@% %@NL@% For simple programs, such as the examples in Part 1, memory allocation is largely automatic. When you declare variables, as in the lines %@NL@% %@NL@% %@AS@% int count; %@AS@% char buffer[160];%@AE@%%@NL@% %@NL@% QuickC allocates enough memory to store each variable (2 bytes for the first variable and 160 for the second). This method works fine if you know each vari-able's size in advance. Some program memory needs aren't easy to predict, however. %@NL@% %@NL@% To take a simple example, say you write an address-book program that stores addresses in an array of structures. A novice programmer might begin by declaring an array of, say, 100 structures, in the following manner, %@NL@% %@NL@% %@AS@% struct address list[100];%@AE@%%@NL@% %@NL@% but this approach is needlessly limiting. If your list contains only a few addresses, most of the memory in the array is wasted. And if you want to enter more than 100 addresses, you're out of luck. %@NL@% %@NL@% A better approach is to allocate memory for the array dynamically. This way, the program can use only as much memory as needed for the current address list. Each time you add an address, or delete one, the program can expand or shrink the array as needed. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00120003 @%%@AB@%Memory Allocation Basics%@AE@%%@EH@%%@NL@% %@NL@% We'll use a simple example program, COPYFILE.C, to demonstrate the basics of dynamic memory allocation─how to allocate a memory block, access its contents, and free the block when its purpose is served. %@NL@% %@NL@% The COPYFILE.C program, shown below, dynamically allocates a buffer that it uses to store file data. %@NL@% %@NL@% %@AS@% /* COPYFILE.C: Demonstrate malloc and free functions. */ %@AS@% %@AS@% #include <stdio.h> /* printf function and NULL */ %@AS@% #include <io.h> /* low-level I/O functions */ %@AS@% #include <conio.h> /* getch function */ %@AS@% #include <sys\types.h> /* struct members used in stat.h */ %@AS@% #include <sys\stat.h> /* S_ constants */ %@AS@% #include <fcntl.h> /* O_ constants */ %@AS@% #include <malloc.h> /* malloc function */ %@AS@% #include <errno.h> /* errno global variable */ %@AS@% %@AS@% int copyfile( char *source, char *destin ); %@AS@% %@AS@% main( int argc, char *argv[] ) %@AS@% { %@AS@% if( argc == 3 ) %@AS@% if( copyfile( argv[1], argv[2] ) ) %@AS@% printf( "Copy failed\n" ); %@AS@% else %@AS@% printf( "Copy successful\n" ); %@AS@% else %@AS@% printf( " SYNTAX: COPYFILE <source> <target>\n" ); %@AS@% %@AS@% return 0; %@AS@% } %@AS@% %@AS@% int copyfile( char *source, char *target ) %@AS@% { %@AS@% char *buf; %@AS@% int hsource, htarget, ch; %@AS@% unsigned count = 50000; %@AS@% %@AS@% if( (hsource = open( source, O_BINARY | O_RDONLY )) == - 1 ) %@AS@% return errno; %@AS@% htarget = open( target, O_BINARY | O_WRONLY | O_CREAT | O_EXCL, %@AS@% S_IREAD | S_IWRITE ); %@AS@% if( errno == EEXIST ) %@AS@% { %@AS@% cputs( "Target exists. Overwrite? " ); %@AS@% ch = getch(); %@AS@% if( (ch == 'y') || (ch == 'Y') ) %@AS@% htarget = open( target, O_BINARY | O_WRONLY | O_CREAT | O_TRUNC, %@AS@% S_IREAD | S_IWRITE ); %@AS@% printf( "\n" ); %@AS@% } %@AS@% if( htarget == -1 ) %@AS@% return errno; %@AS@% %@AS@% if( filelength( hsource ) < count ) %@AS@% count = (int)filelength( hsource ); %@AS@% %@AS@% buf = (char *)malloc( (size_t)count ); %@AS@% %@AS@% if( buf == NULL ) %@AS@% { %@AS@% count = _memmax(); %@AS@% buf = (char *)malloc( (size_t)count ); %@AS@% if( buf == NULL ) %@AS@% return ENOMEM; %@AS@% } %@AS@% %@AS@% while( !eof( hsource ) ) %@AS@% { %@AS@% if( (count = read( hsource, buf, count )) == -1 ) %@AS@% return errno; %@AS@% if( (count = write( htarget, buf, count )) == - 1 ) %@AS@% return errno; %@AS@% } %@AS@% %@AS@% close( hsource ); %@AS@% close( htarget ); %@AS@% free( buf ); %@AS@% return 0; %@AS@% }%@AE@%%@NL@% %@NL@% Before we look at how COPYFILE.C works, let's note what it does. Unlike the DOS COPY command, the COPYFILE.C program asks for confirmation before overwriting an existing file. The program expects to receive two file names as command-line parameters: the name of the file to copy and the name of the new file. For instance, the following command copies the file SAMPLE.EXE to the new file EXAMPLE.EXE: %@NL@% %@NL@% %@AS@% copyfile sample.exe example.exe%@AE@%%@NL@% %@NL@% If the target file already exists, COPYFILE.C displays: %@NL@% %@NL@% %@AS@% Target exists. Overwrite?%@AE@%%@NL@% %@NL@% COPYFILE.C overwrites an existing file only if the user presses the Y key in response. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120004 @%%@AB@%Preparing to Allocate Memory%@AE@%%@EH@%%@NL@% %@NL@% The COPYFILE.C program copies the source file in chunks, using an allocated memory block as a buffer for file data. The following program lines are the ones involved in allocating and freeing the memory block. (These are taken from the program in order, but are not consecutive.) %@NL@% %@NL@% %@AS@% #include <malloc.h> /* malloc function */ %@AS@% char *buf; %@AS@% unsigned count = 50000; %@AS@% buf = (char *)malloc( (size_t)count ); %@AS@% free( buf );%@AE@%%@NL@% %@NL@% The first of these, %@NL@% %@NL@% %@AS@% #include <malloc.h> /* malloc function */%@AE@%%@NL@% %@NL@% includes the standard include file MALLOC.H, which contains declarations for %@AB@%malloc%@AE@% and other memory-allocating functions. %@NL@% %@NL@% The %@AB@%malloc%@AE@% function, which the program will call to allocate a memory block, returns the address where the block begins. COPYFILE.C declares the pointer variable %@AS@% buf %@AE@% to store this address: %@NL@% %@NL@% %@AS@% char *buf;%@AE@%%@NL@% %@NL@% As you'll see shortly, the pointer %@AS@% buf %@AE@% will be initialized to point to the allocated block. Once this is done, the program can access the block's contents through the pointer. %@NL@% %@NL@% The COPYFILE.C program declares another variable, %@AS@% count%@AE@%, which is used to tell %@AB@%malloc%@AE@% how much memory (in bytes) to allocate. The program initially sets this value to 50,000: %@NL@% %@NL@% %@AS@% unsigned count = 50000;%@AE@%%@NL@% %@NL@% If the source file is smaller than 50,000 bytes, COPYFILE.C later resets %@AS@% %@AS@%count %@AE@% to the smaller value. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120005 @%%@AB@%Specifying the Size of the Allocated Block%@AE@%%@EH@%%@NL@% %@NL@% Now we're ready to allocate the block. The statement %@NL@% %@NL@% %@AS@% buf = (char *)malloc( (size_t)count) );%@AE@%%@NL@% %@NL@% in COPYFILE.C calls the %@AB@%malloc%@AE@% function, passing the value of %@AS@% count %@AE@% as an argument. This argument indicates the size of the desired block in bytes. In COPYFILE.C this value is 50,000 or the size of the source file, whichever is smaller. %@NL@% %@NL@% Look at the type cast preceding the function argument: %@NL@% %@NL@% %@AS@% (size_t)%@AE@%%@NL@% %@NL@% The cast is performed for ANSI compatibility (%@AB@%malloc%@AE@% is part of the ANSI standard). Under ANSI, %@AB@%malloc%@AE@% is declared as taking an argument of the type %@AS@% %@AS@%size_t%@AE@%. To ensure the portability of your programs, the value passed to %@AB@%malloc%@AE@% should be either declared or cast as type %@AS@% size_t%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120006 @%%@AB@%A Graphic Illustration%@AE@%%@EH@%%@NL@% %@NL@% Figures 12.1 and 12.2 show how the COPYFILE.C program allocates a memory block. The figures are simplified and are not drawn to scale. They represent the program's "data segment," which is the memory area available for the program's data storage. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%The details of data storage differ depending on the current "memory model," %@AI@%an advanced concept that goes beyond the scope of this book. For purposes of %@AI@%discussion, this book assumes the small memory model, which is the default %@AI@%for QuickC.%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% Figure 12.1 represents the program's data segment before COPYFILE.C allocates a block of memory. The shaded area labeled "Declared data" contains the program's declared variables and "stack," which is used for temporary storage. The unshaded area labeled "Heap" contains the memory available for allocation by COPYFILE.C. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Figure 12.2 shows COPYFILE.C immediately after the program calls the %@AB@%malloc%@AE@% function to allocate a block of memory. The allocated block is taken from heap memory and lies directly above the program. If COPYFILE.C allocated a second memory block, that block would lie above the first, further diminishing heap memory. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% While it's common to say the %@AB@%malloc%@AE@% function "creates" a memory block, that terminology is a bit misleading. As Figures 12.1 and 12.2 show, %@AB@%malloc%@AE@% simply gives your program control over memory that's already present. %@NL@% %@NL@% %@AU@% The malloc function does not initialize the memory it allocates.%@AE@% %@NL@% %@NL@% Since the allocated block has been present in memory all along, it may contain random values or values left over from some previous use. The %@AB@%malloc%@AE@% function doesn't initialize allocated memory. Substitute the %@AB@%calloc%@AE@% function for %@AB@%malloc%@AE@% if you want to clear an allocated block before use. (See the section "The calloc Function" below.) %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120007 @%%@AB@%Assigning the Address that malloc Returns%@AE@%%@EH@%%@NL@% %@NL@% If the call to %@AB@%malloc%@AE@% succeeds, %@AB@%malloc%@AE@% returns the address of the memory block it allocates. COPYFILE.C assigns that return value to the pointer variable %@AS@% buf %@AE@% and then accesses the allocated block through %@AS@% buf%@AE@%. %@NL@% %@NL@% Before assigning the address that %@AB@% malloc%@AE@% returns, COPYFILE.C performs a type cast on the address %@NL@% %@NL@% %@AS@% (char *)%@AE@%%@NL@% %@NL@% The type cast indicates which type of memory you are allocating. Prior to the ANSI standard, %@AB@%malloc%@AE@% was declared as returning a pointer to type %@AB@%char%@AE@%, so it was necessary to cast the return value when assigning the value to any other pointer type. %@NL@% %@NL@% Under ANSI, %@AB@%malloc%@AE@% returns a pointer to type %@AB@%void%@AE@%. Since a %@AB@%void%@AE@% pointer can be converted to any pointer type, it's not strictly necessary to cast the return from %@AB@%malloc%@AE@%. (If you omit the cast, QuickC does a silent type conversion.) The type cast improves readability, however. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120008 @%%@AB@%Checking the Return from malloc%@AE@%%@EH@%%@NL@% %@NL@% If a call to %@AB@%malloc%@AE@% fails─usually because not enough memory is available─the function returns a null pointer (defined as %@AS@% NULL %@AE@% in the standard include file STDIO.H). You should always test this return value, even if you're confident the allocation will succeed. If you ignore the return value and access memory through a null pointer, your program may stop with a run-time error or overwrite unpredictable memory addresses. %@NL@% %@NL@% Thus, before attempting to use the allocated memory block, COPYFILE.C checks to make sure the call to %@AB@%malloc%@AE@% succeeded: %@NL@% %@NL@% %@AS@% if( buf == NULL ) %@AS@% { %@AS@% . %@AS@% . %@AS@% . %@AS@% }%@AE@%%@NL@% %@NL@% The %@AB@%if%@AE@% statement tests whether the pointer %@AS@% buf %@AE@% has been set to %@AS@% NULL%@AE@%, which would signal failure. In that case, the program executes the code within the braces of the %@AB@%if%@AE@% statement. %@NL@% %@NL@% Sometimes there may be enough free memory to satisfy only part of your memory request. Look at how COPYFILE.C handles this situation: %@NL@% %@NL@% %@AS@% buf = (char *)malloc( (size_t)count ); %@AS@% %@AS@% if( buf == NULL ) %@AS@% { %@AS@% count = _memmax(); %@AS@% buf = (char *)malloc( (size_t)count ); %@AS@% if( buf == NULL ) %@AS@% return ENOMEM; %@AS@% }%@AE@%%@NL@% %@NL@% If fewer than %@AS@% count %@AE@% bytes of memory are available, the initial call to %@AB@%malloc%@AE@% returns %@AS@% NULL%@AE@%, indicating failure. In that event, COPYFILE.C calls the %@AB@%_memmax%@AE@% library routine to find how much memory is available and assigns that value to the variable %@AS@% count%@AE@%: %@NL@% %@NL@% %@AS@% count = _memmax();%@AE@%%@NL@% %@NL@% Then COPYFILE.C calls %@AB@%malloc%@AE@% again, requesting a smaller amount of memory. This request is bound to succeed unless no memory is available. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120009 @%%@AB@%Accessing an Allocated Memory Block%@AE@%%@EH@%%@NL@% %@NL@% Once you have allocated a block of memory, you can access it through its pointer (%@AS@% buf%@AE@%, in this example). COPYFILE.C uses its allocated block as a file buffer, alternately reading in data from the source file, through the statement %@NL@% %@NL@% %@AS@% if( (count = read( hsource, buf, count )) == -1 ) %@AS@% return errno;%@AE@%%@NL@% %@NL@% and writing it to the target file, through the statement %@NL@% %@NL@% %@AS@% if( (count = write( htarget, buf, count )) == - 1 ) %@AS@% return errno;%@AE@%%@NL@% %@NL@% The %@AB@%read%@AE@% and %@AB@%write%@AE@% function calls occur within %@AB@%if%@AE@% statements that compare the function return values to -1, which would indicate failure. %@NL@% %@NL@% COPYFILE.C treats its allocated block as a single chunk of memory. To access individual data items in an allocated block, you can use either pointer or array notation. Both of the following statements, for instance, refer to the third byte in the block that %@AS@% buf %@AE@% points to: %@NL@% %@NL@% %@AS@% buf[2] = 'x'; %@AS@% *(buf+2) = 'x';%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120010 @%%@AB@%Allocating Memory for Different Data Types%@AE@%%@EH@%%@NL@% %@NL@% Since COPYFILE.C accesses its allocated block through a %@AB@%char%@AE@% pointer, the program must treat the items in that block as %@AB@%char%@AE@% types. If you need to use a different type of memory, simply change the pointer declaration and cast the return from %@AB@%malloc%@AE@% accordingly. For instance, you could use the following statements to allocate a block large enough to store 30 %@AB@%int%@AE@% values: %@NL@% %@NL@% %@AS@% int *buf; %@AS@% %@AS@% buf = (int *)malloc( (size_t)sizeof( int ) * 30 );%@AE@%%@NL@% %@NL@% Here, the %@AB@%sizeof%@AE@% operator eliminates the need to calculate how many bytes of storage 30 integers require. The expression %@NL@% %@NL@% %@AS@% sizeof( int )%@AE@%%@NL@% %@NL@% returns the size of an %@AB@%int%@AE@% type, which we then multiply by the desired number of %@AB@%int%@AE@% items. %@NL@% %@NL@% If the above call to %@AB@%malloc%@AE@% succeeds, you have, in effect, a 30-element array of integers. And since pointer notation and array notation are interchangeable, you can access any element of the array using the pointer name and array notation. For instance, the expression %@NL@% %@NL@% %@AS@% ptr[2] = 50;%@AE@%%@NL@% %@NL@% assigns the value 50 to the third element of the array. Note that this statement accesses the third %@AB@%int%@AE@% element in the array, not the third byte. Pointer references, as explained in Chapter 8, "Pointers," are always scaled by the size of the type used to declare the pointer. %@NL@% %@NL@% Allocating memory for structures is equally straightforward. Say that you want to allocate memory to store 10 structures of the type %@AS@% employee%@AE@%, which is declared in the EMPLOYEE.C program in Chapter 4, "Data Types." The EMPLOYEE.C program uses the following structure type: %@NL@% %@NL@% %@AS@% struct employee %@AS@% { %@AS@% char name[10]; %@AS@% int months; %@AS@% float wage; %@AS@% };%@AE@%%@NL@% %@NL@% You could use the statement %@NL@% %@NL@% %@AS@% struct employee *e_ptr;%@AE@%%@NL@% %@NL@% to declare a pointer to an item of the %@AS@% employee %@AE@% type. Once you have a suitable pointer, you could use the following statement to allocate enough memory to store 10 structures of the same type: %@NL@% %@NL@% %@AS@% e_ptr = (struct employee *) malloc( (size_t)sizeof( struct employee ) * 10 %@AS@% );%@AE@%%@NL@% %@NL@% Here, the %@AB@%sizeof%@AE@% operator %@NL@% %@NL@% %@AS@% sizeof( struct employee )%@AE@%%@NL@% %@NL@% returns the size of a structure of the %@AS@% employee %@AE@% type. %@NL@% %@NL@% If the allocation succeeds, you have, in effect, an array of structures of type %@AS@%employee%@AE@%. Using structure notation, you can access any structure member in the block. The following statements, for instance, initialize the members of the third structure in the array: %@NL@% %@NL@% %@AS@% strcpy( e_ptr[2].name, "Isaac, N." ); %@AS@% e_ptr[2].months = 54; %@AS@% e_ptr[2].wage = (float) 12.21;%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120011 @%%@AB@%Deallocating Memory with the free Function%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% The free function deallocates an allocated memory block.%@AE@% %@NL@% %@NL@% When you have finished using an allocated memory block, you should free (deallocate) the block with the %@AB@%free%@AE@% library function. The %@AB@%free%@AE@% function takes one argument: the address of the block you wish to free. The COPYFILE.C program frees its allocated block with the statement: %@NL@% %@NL@% %@AS@% free( buf );%@AE@%%@NL@% %@NL@% It's your responsibility to pass a valid address to %@AB@%free%@AE@%. Unlike most library functions, %@AB@%free%@AE@% doesn't return any value to indicate success or failure. If you pass an invalid address, the memory block remains allocated and can't be used for any other purpose. %@NL@% %@NL@% Figure 12.3 shows COPYFILE.C after the program frees its allocated block. The %@AB@%free%@AE@% function releases the block from the program's control, returning it to the heap. The same memory is still present, of course. But since your program no longer has control of that memory, you shouldn't attempt to use it. (See "Using Dangling Pointers" in Chapter 10, "Programming Pitfalls," for more information on this point.) %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00120012 @%%@AB@%Specialized Memory-Allocating Functions%@AE@%%@EH@%%@NL@% %@NL@% The C library contains two specialized versions of %@AB@%malloc%@AE@% that you may find useful. The %@AB@%calloc%@AE@% function allocates memory for an array and sets the block's contents to 0. The %@AB@%realloc%@AE@% function can expand or shrink an existing memory block. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120013 @%%@AB@%The calloc Function%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%calloc%@AE@% (calculated allocate) function is especially useful for allocating memory for an array. It works like %@AB@%malloc%@AE@% but takes two arguments: %@NL@% %@NL@% %@NL@% ■ The number of data items for which you wish to allocate memory%@NL@% %@NL@% ■ The size of each data item%@NL@% %@NL@% %@NL@% This scheme eliminates the need for you to calculate the number of bytes needed to store the desired array. For instance, the statement %@NL@% %@NL@% %@AS@% ptr = (int *) calloc( (size_t)30, (size_t)sizeof( int ) );%@AE@%%@NL@% %@NL@% allocates enough memory for a 30-element integer array, and %@NL@% %@NL@% %@AS@% e_ptr = (struct employee *) calloc( (size_t)30, sizeof( struct employee ) %@AS@% );%@AE@%%@NL@% %@NL@% allocates enough memory for a 30-element array of structures of type %@AS@%employee%@AE@%. %@NL@% %@NL@% %@AU@% The calloc library function allocates memory and sets every byte in the %@AU@%block to 0.%@AE@% %@NL@% %@NL@% The %@AB@%calloc%@AE@% function also sets every byte in the requested block to 0. The %@AB@%malloc%@AE@% function, as we noted earlier, doesn't change the contents of an allocated block. If the block contained garbage values before allocation, it contains garbage after allocation, too. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00120014 @%%@AB@%The realloc Function%@AE@%%@EH@%%@NL@% %@NL@% Sometimes you may need to adjust the size of an allocated memory block. The %@AB@%realloc%@AE@% (reallocate) function can expand or shrink an existing memory block. The function takes two arguments: %@NL@% %@NL@% %@NL@% ■ The address of an existing allocated block%@NL@% %@NL@% ■ The size (in bytes) you want to give the block%@NL@% %@NL@% %@NL@% %@AU@% The realloc library function expands or shrinks an existing allocated %@AU@%block.%@AE@% %@NL@% %@NL@% If enough memory is available to accommodate the resized block, %@AB@%realloc%@AE@% allocates sufficient memory and copies as much of the existing block as the new block will hold. If the new block is smaller than the original, data is truncated. %@NL@% %@NL@% For instance, if you had allocated a 30-element %@AB@%int%@AE@% array with the statement %@NL@% %@NL@% %@AS@% ptr = (int *) calloc( (size_t)30, (size_t)sizeof( int ) );%@AE@%%@NL@% %@NL@% the following statement would expand the block to contain 20 extra elements, for a total of 50: %@NL@% %@NL@% %@AS@% ptr = (int *)realloc( ptr, (size_t)sizeof( int ) * 50 );%@AE@%%@NL@% %@NL@% The address you pass to %@AB@%realloc%@AE@% can be the address returned from a previous call to any memory-allocation function: %@AB@%malloc%@AE@%, %@AB@%calloc%@AE@%, or %@AB@%realloc%@AE@% itself. %@NL@% %@NL@% Like %@AB@%malloc%@AE@%, both %@AB@%calloc%@AE@% and %@AB@%realloc%@AE@% return a null address if they fail. Remember to check the return value whenever you call a memory-allocating function. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00120015 @%%@AB@%Keeping Out of Trouble%@AE@%%@EH@%%@NL@% %@NL@% Here are a few rules to help you avoid trouble when allocating memory dynamically: %@NL@% %@NL@% %@NL@% ■ Always check the return value when allocating memory.%@NL@% %@NL@% ■ Be careful not to index past the boundaries of an allocated memory block.%@NL@% %@NL@% ■ Free allocated memory as soon as you have finished using it.%@NL@% %@NL@% ■ Make sure that the address you pass to the %@AB@%free%@AE@% function is valid.%@NL@% %@NL@% ■ Don't use a pointer to an allocated block after freeing the block.%@NL@% %@NL@% %@NL@% Most of these points were mentioned earlier, but the second deserves a little elaboration. As you may recall from earlier chapters, the C language doesn't check array subscripts or pointer references for validity. It's important to remember this rule when using a pointer to access an allocated block. %@NL@% %@NL@% For instance, suppose that you allocate a 30-element integer array with the statement %@NL@% %@NL@% %@AS@% ptr = (int *) malloc( (size_t)sizeof( int ) * 30 );%@AE@%%@NL@% %@NL@% and then execute either of these statements: %@NL@% %@NL@% %@AS@% ptr[32] = 80; %@AS@% *(ptr+32) = 80;%@AE@%%@NL@% %@NL@% Since the array has only 30 elements, both of the latter statements overwrite memory outside the allocated memory block. The statements store the value 80 in the address four bytes (two %@AB@%int%@AE@% elements) above the highest element in the array. %@NL@% %@NL@% While uncontrolled pointer operations always carry the potential for disaster, they can create especially tricky program bugs if you write just beyond an allocated memory block. %@NL@% %@NL@% Near the beginning of each allocated block is a tiny "link" containing information about the block. The memory-allocating functions use these links to keep track of allocated memory, and the more blocks you have allocated, the more important it is to keep all the links intact. If a bad pointer reference overwrites a link, it can cause problems in an entirely unexpected part of your program. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00130001 @%%@1@%%@AB@%Chapter 13 Graphics%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% This chapter explains how to call graphics functions that set points, draw lines, change colors, and draw shapes such as rectangles and circles. The first section lists the three steps to using high-resolution graphics, defines important graphics terms, and works through an example program step by step, showing how to use the basic functions. The next sections explain coordinate systems and show how to display graphics inside viewports and windows. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00130002 @%%@AB@%Graphics Mode%@AE@%%@EH@%%@NL@% %@NL@% There are three steps to displaying graphics in QuickC: %@NL@% %@NL@% %@NL@% 1. Use the %@AB@%_getvideoconfig%@AE@% function to determine which video adapter is installed. (See the section "Checking the Current Video Mode.")%@NL@% %@NL@% 2. Use the %@AB@%_setvideomode%@AE@% function to set the desired graphics mode for the installed video adapter. (See the section "Setting the Video Mode.")%@NL@% %@NL@% 3. Draw the graphics on the screen. (See the section "Writing a Graphics Program.")%@NL@% %@NL@% %@NL@% There are several definitions you need to know before you can create graphics programs. The following list explains the most useful terms: %@NL@% %@NL@% %@NL@% ■ The "%@AI@%x%@AE@% axis" determines the horizontal position on the screen. The "origin" (point 0, 0) is in the upper left corner. The maximum number of horizontal "pixels" (picture elements) varies from 320 to 640 to 720, depending on the graphics card installed and the graphics mode in effect.%@NL@% %@NL@% ■ The "%@AI@%y%@AE@% axis" is the vertical position. The origin is the upper left corner. The number of vertical pixels ranges from 200 to 480.%@NL@% %@NL@% ■ Each graphics mode offers a "palette" from which you may choose the colors to be displayed. You may have access to 2, 4, 8, 16, or 256 "color indexes," depending on the graphics card in the computer and the graphics mode in effect.%@NL@% %@NL@% ■ The CGA (Color Graphics Adapter) modes offer four fixed palettes containing predefined colors that may not be changed. In EGA (Enhanced Graphics Adapter), MCGA (Multicolor Graphics Array), and VGA (Video Graphics Array) graphics modes, you may change any of the color indexes by providing a color value that describes the mix of colors you wish to use. %@NL@% %@NL@% ■ A color index is always a short integer. A color value is always a long integer. When you're calling graphics functions that require color-related parameters, you should be aware of the difference between color indexes and color values.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130003 @%%@AB@%Checking the Current Video Mode%@AE@%%@EH@%%@NL@% %@NL@% Before or after entering graphics mode, you may inquire about the current video configuration. This requires a special structure type called %@AB@%videoconfig%@AE@%, which is defined in the GRAPH.H header file. You pass the address of the structure to the function %@AB@%_getvideoconfig%@AE@%, which returns the current video configuration information. %@NL@% %@NL@% All graphics programs should include the graphics header file and declare a structure of type %@AB@%videoconfig%@AE@%. The structure contains the following elements: %@NL@% %@NL@% %@AS@% short numxpixels; /*number of pixels on x axis*/ %@AS@% short numypixels; /*number of pixels on y axis*/ %@AS@% short numtextcols; /*number of text columns available*/ %@AS@% short numtextrows; /*number of text rows available*/ %@AS@% short numcolors; /*number of color indexes*/ %@AS@% short bitsperpixel; /*number of bits per pixel*/ %@AS@% short numvideopages;/*number of available video pages*/ %@AS@% short mode; /*current video mode*/ %@AS@% short adapter; /*active display adapter*/ %@AS@% short monitor; /*active display monitor*/ %@AS@% short memory; /*adapter video memory in K bytes*/%@AE@%%@NL@% %@NL@% These variables within the %@AB@%videoconfig%@AE@% structure are initialized when you call %@AB@%_getvideoconfig%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130004 @%%@AB@%Setting the Video Mode%@AE@%%@EH@%%@NL@% %@NL@% Before you can start drawing pictures on the screen, your program must tell the graphics adapter to switch from video text mode to graphics mode. To do this, call %@AB@%_setvideomode%@AE@%, passing it a single integer that tells it which mode to display. The following constants are defined in the GRAPH.H file. The dimensions are listed in pixels for graphics mode and in columns for video text modes. %@NL@% %@NL@% %@TH: 43 1718 02 16 30 30 @%Constant Video Mode Mode Type/Hardware%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%_DEFAULTMODE %@AE@% Restores to original mode Both/All%@AB@%_ERESCOLOR%@AE@% 640 x 350, 4 or 16 color Graphics/EGA%@AB@%_ERESNOCOLOR%@AE@% 640 x 350, BW Graphics/EGA%@AB@%_HERCMONO%@AE@% 720 x 348, BW for HGC Graphics/HGC%@AB@%_HRES16COLOR%@AE@% 640 x 200, 16 color Graphics/EGA%@AB@%_HRESBW%@AE@% 640 x 200, BW Graphics/CGA%@AB@%_MRES4COLOR%@AE@% 320 x 200, 4 color Graphics/CGA%@AB@%_MRES16COLOR%@AE@% 320 x 200, 16 color Graphics/EGA%@AB@%_MRES256COLOR%@AE@% 320 x 200, 256 color Graphics/VGA/ MCGA%@AB@%_MRESNOCOLOR%@AE@% 320 x 200, 4 gray Graphics/CGA%@AB@%_ORESCOLOR%@AE@% 640 x 400, 1 of 16 colors Graphics/ Olivetti(R)%@AB@%_TEXTBW40%@AE@% 40-column text, 16 gray Text/CGA%@AB@%_TEXTBW80%@AE@% 80-column text, 16 gray Text/CGA%@AB@%_TEXTC40%@AE@% 40-column text, 16/8 color Text/CGA%@AB@%_TEXTC80%@AE@% 80-column text, 16/8 color Text/CGA%@AB@%_TEXTMONO%@AE@% 80-column text, BW Text/MDA%@AB@%_VRES2COLOR%@AE@% 640 x 480, BW Graphics/VGA/ MCGA%@AB@%_VRES16COLOR%@AE@% 640 x 480, 16 color Graphics/VGA%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 43 1718 02 16 30 30 @% If %@AB@%_setvideomode%@AE@% returns a 0, it means the hardware does not support the selected mode. You may continue to select alternate video modes until a nonzero value is returned. If the hardware configuration doesn't support any of the selected video modes, take the appropriate exit action. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130005 @%%@AB@%Writing a Graphics Program%@AE@%%@EH@%%@NL@% %@NL@% The SINE.C program below graphs a sine curve. The program illustrates how to call many of the important graphics functions. The %@AB@%main%@AE@% function calls five other functions, which are defined later in this chapter. To view the complete program, use online help. %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% When you installed QuickC on your system, you may have chosen not to include the graphics library. If this is the case, the programs in this chapter won't compile unless you explicitly link the graphics library. See the %@AI@%Microsoft QuickC Tool Kit %@AE@%for information about linking libraries.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% %@AS@% %@AS@% /* SINE.C: Basic graphics commands. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <stdlib.h> %@AS@% #include <graph.h> %@AS@% #include <math.h> %@AS@% #include <conio.h> %@AS@% #define PI 3.14159 %@AS@% %@AS@% void graphics_mode( void ); %@AS@% void draw_lines( void ); %@AS@% void sine_wave( void ); %@AS@% void draw_shapes( void ); %@AS@% void end_program( void ); %@AS@% int newx( int ); %@AS@% int newy( int ); %@AS@% %@AS@% struct videoconfig myscreen; %@AS@% int maxx, maxy; %@AS@% unsigned char diagmask[8] = %@AS@% { 0x93, 0xC9, 0x64, 0xB2, 0x59, 0x2C, 0x96, 0x4B }; %@AS@% unsigned char linemask[8] = %@AS@% { 0xFF, 0x00, 0x7F, 0xFE, 0x00, 0x00, 0x00, 0xCC }; %@AS@% %@AS@% %@AS@% main() %@AS@% { %@AS@% graphics_mode(); %@AS@% draw_lines(); %@AS@% sine_wave(); %@AS@% draw_shapes(); %@AS@% end_program(); %@AS@% } %@AS@% /* %@AS@% Definitions of functions go here %@AS@% */%@AE@%%@NL@% %@NL@% The SINE.C program's output is shown in Figure 13.1. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Turning on Graphics Mode%@AE@%%@EH@%%@NL@% %@NL@% Before you can display graphics, you must put the graphics adapter into a graphics mode. The %@AB@%_setvideomode%@AE@% function performs this task. Before calling %@AB@%_setvideomode%@AE@%, you must decide which graphics modes are acceptable for your purposes. The first function in SINE.C is named %@AS@% graphics_mode%@AE@%. It selects the highest possible resolution available, based on the graphics card currently in use. %@NL@% %@NL@% Four header files are included in the SINE.C program: %@NL@% %@NL@% %@AS@% #include <stdio.h>%@AE@%%@NL@% %@NL@% %@AS@% #include <stdlib.h>%@AE@%%@NL@% %@NL@% %@AS@% #include <graph.h>%@AE@%%@NL@% %@NL@% %@AS@% #include <math.h>%@AE@%%@NL@% %@NL@% Although the MATH.H file is not required for graphics programs, we include it in the SINE.C program because it contains floating-point math functions such as %@AB@%sin%@AE@%. %@NL@% %@NL@% Later in the program we'll need to get information about the screen size, so the %@AB@%videoconfig%@AE@% structure called %@AS@% myscreen %@AE@% is declared: %@NL@% %@NL@% %@AS@% struct videoconfig myscreen;%@AE@%%@NL@% %@NL@% The functions called by %@AB@%main%@AE@% aren't in the standard library; they're defined within SINE.C. %@NL@% %@NL@% The first function is %@AS@% graphics_mode%@AE@%, which turns on graphics capabilities: %@NL@% %@NL@% %@AS@% void graphics_mode( void ) %@AS@% { %@AS@% _getvideoconfig( &myscreen ); %@AS@% switch( myscreen.adapter ) %@AS@% { %@AS@% case _CGA: %@AS@% _setvideomode( _HRESBW ); %@AS@% break; %@AS@% case _OCGA: %@AS@% _setvideomode( _ORESCOLOR ); %@AS@% break; %@AS@% case _EGA: %@AS@% case _OEGA: %@AS@% if( myscreen.monitor == _MONO ) %@AS@% _setvideomode( _ERESNOCOLOR ); %@AS@% else %@AS@% _setvideomode( _ERESCOLOR ); %@AS@% break; %@AS@% case _VGA: %@AS@% case _OVGA: %@AS@% case _MCGA: %@AS@% _setvideomode( _VRES2COLOR ); %@AS@% break; %@AS@% case _HGC: %@AS@% _setvideomode( _HERCMONO ); %@AS@% break; %@AS@% default: %@AS@% printf( "This program requires a CGA, EGA, VGA, or Hercules %@AS@%card\n" ); %@AS@% exit( 0 ); %@AS@% } %@AS@% _getvideoconfig( &myscreen ); %@AS@% maxx = myscreen.numxpixels - 1; %@AS@% maxy = myscreen.numypixels - 1; %@AS@% }%@AE@%%@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% NOTE %@AI@%If you use a Hercules(R) adapter, you must run the MSHERC.COM program before %@AI@%attempting to display any graphics. Always run MSHERC.COM before running %@AI@%QuickC (do not run it from QuickC's DOS shell).%@AE@%%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@%%@NL@% %@NL@% The function begins by calling %@AB@%_getvideoconfig%@AE@%, passing the address of the %@AB@%videoconfig%@AE@% structure. Within the structure a member called %@AB@%adapter%@AE@% tells us the type of adapter currently in use. With that knowledge, and a switch statement, we can enter the appropriate graphics mode. %@NL@% %@NL@% But how much screen do we have to work with? The screen might be 720 x 348, 640 x 480, 640 x 400, 640 x 350, or 640 x 200. Whenever you call %@AB@%_setvideomode%@AE@%, you can ask for information about the currently displayed screen with %@AB@%_getvideoconfig%@AE@%. Just pass it the address of the %@AB@%videoconfig%@AE@% structure that was declared earlier:%@AB@% %@AE@%%@NL@% %@NL@% %@AS@% _getvideoconfig( &myscreen ); %@AS@% maxx = myscreen.numxpixels - 1; %@AS@% maxy = myscreen.numypixels - 1;%@AE@%%@NL@% %@NL@% Let's say your computer has an EGA card, which means that at this point, %@AB@%_ERESNOCOLOR%@AE@% is in effect. The horizontal screen size is 640 pixels and vertical screen size is 350. The two assignments above assign these values to %@AS@% maxx %@AE@% and %@AS@% maxy%@AE@%, less 1. The horizontal resolution might be 640, but the pixels are numbered 0-639. Thus, the %@AS@% maxx %@AE@% variable─the highest available pixel number─must be 1 less than the total number of pixels: %@NL@% %@NL@% %@AS@% myscreen.numxpixels - 1%@AE@%%@NL@% %@NL@% Two short functions perform conversions from an imaginary 1000 x 1000 screen to whatever graphics mode is in effect. From this point forward, the program will assume it has 1000 pixels in each direction, passing the values to %@AS@% %@AS@%newx %@AE@% and %@AS@% newy %@AE@% for conversion to actual coordinates: %@NL@% %@NL@% %@AS@% int newx( int xcoord ) %@AS@% { %@AS@% int nx; %@AS@% float tempx; %@AS@% tempx = ((float)maxx)/ 1000.0; %@AS@% tempx = ((float)xcoord) * tempx + 0.5; %@AS@% return( (int)tempx ); %@AS@% } %@AS@% %@AS@% int newy( int ycoord ) %@AS@% { %@AS@% int ny; %@AS@% float tempy; %@AS@% tempy = ((float)maxy)/ 1000.0; %@AS@% tempy = ((float)ycoord) * tempy + 0.5; %@AS@% return( (int)tempy ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Drawing Rectangles and Lines%@AE@%%@EH@%%@NL@% %@NL@% The next function called in SINE.C is %@AS@% draw_lines%@AE@%. As the name implies, the %@AS@% %@AS@%draw_lines %@AE@% function draws several lines on the screen: a rectangle around the outer edges of the screen and three horizontal lines that cut the screen into quarters. %@NL@% %@NL@% %@AS@% void draw_lines( void ) %@AS@% { %@AS@% _rectangle( _GBORDER, 0, 0, maxx, maxy ); %@AS@% /* _setcliprgn( 20, 20, maxx - 20, maxy - 20 ); */ %@AS@% _setvieworg( 0, newy( 500 ) ); %@AS@% %@AS@% _moveto( 0, 0 ); %@AS@% _lineto( newx( 1000 ), 0 ); %@AS@% _setlinestyle( 0xAA3C ); %@AS@% _moveto( 0, newy( -250) ); %@AS@% _lineto( newx( 1000 ), newy( -250 ) ); %@AS@% _setlinestyle( 0x8888 ); %@AS@% _moveto( 0, newy( 250 ) ); %@AS@% _lineto( newx( 1000 ), newy( 250 ) ); %@AS@% }%@AE@%%@NL@% %@NL@% The call to the%@AB@% _rectangle%@AE@% function has five arguments. The first argument is the fill flag, which may be either %@AB@%_GBORDER%@AE@% or %@AB@%_GFILLINTERIOR%@AE@%. Choose %@AB@%_GBORDER%@AE@% if you want a rectangle of four lines (a border only, in the current line style). Or you can choose %@AB@%_GFILLINTERIOR%@AE@% if you want a solid rectangle (filled in with the current color and fill pattern). We will discuss how to choose the color and fill pattern later in this chapter. %@NL@% %@NL@% The second and third arguments are the %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates of one corner of the rectangle. The fourth and fifth arguments are the coordinates of the opposite corner. Since the coordinates for the two corners are (%@AS@% 0, 0 %@AE@%) and (%@AS@% maxx%@AE@%, %@AS@%maxy %@AE@%) , the call to %@AB@%_rectangle%@AE@% frames the screen. %@NL@% %@NL@% %@AS@% _rectangle( _GBORDER, 0, 0, maxx, maxy );%@AE@%%@NL@% %@NL@% Drawing lines is a two-step process. Move to one location on the screen and draw the line to another location, using the %@AB@%_moveto%@AE@% and %@AB@%_lineto%@AE@% functions: %@NL@% %@NL@% %@AS@% _setlinestyle( 0xAA3C ); %@AS@% _moveto( 0, newy(-250) ); %@AS@% _lineto( newx(1000), newy(-250) );%@AE@%%@NL@% %@NL@% Use the %@AB@%_setlinestyle%@AE@% function to change from a solid line to a dashed line by passing it one integer value. In the example above, the number 0xAA3C causes the line to become the graphics equivalent of binary 1010 1010 0011 1100. %@NL@% %@NL@% The %@AB@%_moveto%@AE@% function positions an imaginary pixel cursor at a spot on the screen. Nothing visible appears on the screen. The %@AB@%_lineto%@AE@% function draws a line. The negative value -250 might seem to be an impossible screen coordinate. It would be, but the program has changed the viewport organization of the screen with the %@AB@%_setvieworg%@AE@% function. The top half of the screen now contains negative %@AI@%y%@AE@% coordinates, and the bottom half contains positive %@AI@%y%@AE@% coordinates. Viewports are explained in more detail later in this chapter. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Setting a Pixel%@AE@%%@EH@%%@NL@% %@NL@% The next step in the SINE.C program is to draw the sine curve. This requires the %@AS@% sine_wave %@AE@% function which is shown below. This function calculates positions for two sine waves and plots them on the screen: %@NL@% %@NL@% %@AS@% void sine_wave( void ) %@AS@% { %@AS@% int locx, locy; %@AS@% double i, rad; %@AS@% %@AS@% for( i = 0; i < 1000; i += 3 ) %@AS@% { %@AS@% rad = -sin( (PI * (float) i) / 250.0 ); %@AS@% locx = newx( (int) i ); %@AS@% locy = newy( (int) (rad * 250.0) ); %@AS@% _setpixel( locx, locy ); %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% The only graphics function called is %@AB@%_setpixel%@AE@%, which takes two parameters, an %@AI@%x%@AE@% and a %@AI@%y%@AE@% coordinate. The function turns on the pixel at that location. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Drawing Shapes%@AE@%%@EH@%%@NL@% %@NL@% After the sine curve is drawn, the SINE.C program calls the %@AS@% draw_shapes %@AE@% function to draw two rectangles and two ellipses on the screen. The fill mask alternates between %@AB@%_GBORDER%@AE@% and %@AB@%_GFILLINTERIOR%@AE@%: %@NL@% %@NL@% %@AS@% void draw_shapes( void ) %@AS@% { %@AS@% _setlinestyle( 0xFFFF ); %@AS@% _setfillmask( diagmask ); %@AS@% _rectangle( _GBORDER, newx( 50 ), newy( -325 ), newx( 200 ), newy( -425 %@AS@%) ); %@AS@% _rectangle(_GFILLINTERIOR,newx(550),newy(-325),newx(700),newy(-425)); %@AS@% %@AS@% _setfillmask( linemask ); %@AS@% _ellipse( _GBORDER, newx( 50 ), newy( 325 ), newx( 200 ), newy( 425 ) %@AS@%); %@AS@% _ellipse( _GFILLINTERIOR,newx( 550 ),newy( 325 ),newx( 700 ),newy( 425 %@AS@%) ); %@AS@% }%@AE@%%@NL@% %@NL@% Note that %@AB@%_setlinestyle%@AE@% resets the line pattern to solid. If you omit this function (or comment it out), the first rectangle would be drawn with dashes instead of a solid line. %@NL@% %@NL@% The %@AB@%_ellipse%@AE@% function draws an ellipse on the screen. Its parameters resemble the parameters for %@AB@%_rectangle%@AE@%. Both functions require a fill flag and two corners of a "bounding rectangle." When the ellipse is drawn, four points touch the edges of the bounding rectangle. %@NL@% %@NL@% The %@AB@%_GFILLINTERIOR%@AE@% flag fills the shape with the current fill pattern. To select a pattern, you must first use the %@AB@%_setfillmask%@AE@% function, passing the address of an eight-byte array of unsigned characters. Earlier in the program %@AS@% diagmask %@AE@% was defined as the shape shown in Table 13.1 below. %@NL@% %@NL@% %@AB@%Table 13.1 %@AB@%Fill Patterns%@AE@%%@AE@% %@TH: 11 790 02 34 42 @%Bit Pattern Value in diagmask%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% ∙ ∙ ∙ ∙ %@AS@%diagmask[0] %@AE@%= 0x93 ∙ ∙ ∙ ∙ %@AS@%diagmask[1] %@AE@%= 0xC9∙ ∙ ∙ ∙ ∙ %@AS@%diagmask[2] %@AE@%= 0x64 ∙ ∙ ∙ ∙ %@AS@%diagmask[3] %@AE@%= 0xB2∙ ∙ ∙ ∙ %@AS@%diagmask[4] %@AE@%= 0x59∙ ∙ ∙ ∙ ∙ %@AS@%diagmask[5] %@AE@%= 0x2C ∙ ∙ ∙ ∙ %@AS@%diagmask[6] %@AE@%= 0x96∙ ∙ ∙ ∙ %@AS@%diagmask[7] %@AE@%= 0x4B%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 11 790 02 34 42 @% %@NL@% %@4@%%@AB@%Exiting Graphics Mode%@AE@%%@EH@%%@NL@% %@NL@% The final function to be called by the SINE.C program is %@AS@% end_program%@AE@%, which waits for a key press and then sets the screen back to normal: %@NL@% %@NL@% %@AS@% void end_program( void ) %@AS@% { %@AS@% getch(); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130006 @%%@AB@%Using Color Graphics Modes%@AE@%%@EH@%%@NL@% %@NL@% In this example, the program COLOR.C sets a mode with as many color choices as possible for the available hardware: %@NL@% %@NL@% %@AS@% /* COLOR.C: Sets a medium resolution mode %@AS@% with maximum color choices. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <stdlib.h> %@AS@% #include <graph.h> %@AS@% #include <conio.h> %@AS@% struct videoconfig vc; %@AS@% %@AS@% main() %@AS@% { %@AS@% if( _setvideomode( _MRES256COLOR ) ); %@AS@% else if( _setvideomode( _MRES16COLOR ) ); %@AS@% else if( _setvideomode( _MRES4COLOR ) ); %@AS@% else %@AS@% { %@AS@% printf( "Error: No color graphics capability\n" ); %@AS@% exit( 0 ); %@AS@% } %@AS@% %@AS@% _getvideoconfig( &vc ); %@AS@% %@AS@% printf( "%d available colors\n", vc.numcolors ); %@AS@% printf( "%d horizontal pixels\n", vc.numxpixels ); %@AS@% printf( "%d vertical pixels\n", vc.numypixels ); %@AS@% %@AS@% getch(); %@AS@% _clearscreen( _GCLEARSCREEN ); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% }%@AE@%%@NL@% %@NL@% Although color graphics are an improvement over black and white, if you use color you must make a compromise. When you request the maximum number of colors, you sacrifice some resolution─a 320 x 200 screen instead of a higher resolution. Thus, the COLORS.C program always creates a screen 320 pixels wide and 200 pixels high. Note also the use of the function %@AB@%_clearscreen%@AE@%, which clears the screen in any video mode (text or graphics). %@NL@% %@NL@% To view every possible graphics mode, you can run the program GRAPHIC.C shown below. Explanations of the various color graphics modes─CGA, EGA, and VGA─follow. %@NL@% %@NL@% %@AS@% /* GRAPHIC.C: Display every graphics mode. */ %@AS@% #include <stdio.h> %@AS@% #include <graph.h> %@AS@% #include <conio.h> %@AS@% %@AS@% struct videoconfig screen; %@AS@% int modes[12] = %@AS@% { %@AS@% _MRES4COLOR, _MRESNOCOLOR, _HRESBW, _HERCMONO, %@AS@% _MRES16COLOR, _HRES16COLOR, _ERESNOCOLOR, _ERESCOLOR, %@AS@% _VRES2COLOR, _VRES16COLOR, _MRES256COLOR, _ORESCOLOR %@AS@% }; %@AS@% %@AS@% void print_menu( void ); %@AS@% void show_mode( char ); %@AS@% %@AS@% main() %@AS@% { %@AS@% char key; %@AS@% print_menu(); %@AS@% while( (key = getch()) != 'x' ) %@AS@% show_mode( key ); %@AS@% } %@AS@% %@AS@% void print_menu( void ) %@AS@% { %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% _clearscreen( _GCLEARSCREEN ); %@AS@% printf( "Please choose a graphics mode\nType 'x' to exit.\n\n" ); %@AS@% printf( "0 _MRES4COLOR\n1 _MRESNOCOLOR\n2 _HRESBW\n" ); %@AS@% printf( "3 _HERCMONO\n4 _MRES16COLOR\n5 _HRES16COLOR\n" ); %@AS@% printf( "6 _ERESNOCOLOR\n7 _ERESCOLOR\n" ); %@AS@% printf( "8 _VRES2COLOR\n9 _VRES16COLOR\na _MRES256COLOR\n" ); %@AS@% printf( "b _ORESCOLOR\n" ); %@AS@% } %@AS@% %@AS@% void show_mode( char which ) %@AS@% { %@AS@% int nc, i; %@AS@% int height, width; %@AS@% int mode = which; %@AS@% %@AS@% if( mode < '0' || mode > '9' ) %@AS@% if( mode == 'a' ) %@AS@% mode = '9' + 1; %@AS@% else if( mode == 'b' ) %@AS@% mode = '9' + 2;%@AE@%%@NL@% %@NL@% %@AS@% else %@AS@% return; %@AS@% %@AS@% if( _setvideomode( modes[mode - '0'] ) ) %@AS@% { %@AS@% _getvideoconfig( &screen ); %@AS@% nc = screen.numcolors; %@AS@% width = screen.numxpixels/nc; %@AS@% height = screen.numypixels/2; %@AS@% for( i = 0; i < nc; i++ ) %@AS@% { %@AS@% _setcolor( i ); %@AS@% _rectangle( _GFILLINTERIOR, i * width, 0, (i + 1) * width, height ); %@AS@% } %@AS@% } %@AS@% else %@AS@% { %@AS@% printf( " \nVideo mode %c is not available.\n", which ); %@AS@% printf( "Please press a key.\n" ); %@AS@% } %@AS@% getch(); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% print_menu(); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%CGA Color Graphics Modes%@AE@%%@EH@%%@NL@% %@NL@% The CGA color graphics modes %@AB@%_MRES4COLOR%@AE@% and %@AB@%_MRESNOCOLOR%@AE@% display four colors selected from one of several predefined palettes of colors. They display these foreground colors against a background color which can be any one of the 16 available colors. With the CGA hardware, the palette of foreground colors is predefined and cannot be changed. Each palette number is an integer as shown in Table 13.2. %@NL@% %@NL@% %@AB@%Table 13.2 %@AB@%Available CGA Colors%@AE@%%@AE@% %@TH: 8 529 03 18 14 16 28 @%Palette Number Color Index 1 2 3%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%0 Green Red Brown1 Cyan Magenta Light gray2 Light green Light red Yellow3 Light cyan Light magenta White%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 8 529 03 18 14 16 28 @% The %@AB@%_MRESNOCOLOR%@AE@% graphics mode produces palettes containing various shades of gray on black-and-white monitors. The %@AB@%_MRESNOCOLOR%@AE@% mode displays colors when used with a color display. However, only two palettes %@NL@% %@NL@% are available with a color display. You can use the %@AB@%_selectpalette%@AE@% function to select one of these predefined palettes. Table 13.3 shows the correspondence between the color indexes and the palettes. %@NL@% %@NL@% %@AB@%Table 13.3 %@AB@%CGA Colors: _MRESNOCOLOR Mode%@AE@%%@AE@% %@TH: 6 404 03 18 13 12 33 @%Palette Number Color Index 1 2 3%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%0 Blue Red Light gray1 Light blue Light red White%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 6 404 03 18 13 12 33 @% You may use the %@AB@%_selectpalette%@AE@% function only with the %@AB@%_MRES4COLOR%@AE@% and %@AB@%_MRESNOCOLOR%@AE@% graphics modes. To change palettes in other graphics modes, use the %@AB@%_remappalette%@AE@% or %@AB@%_remapallpalette%@AE@% functions. %@NL@% %@NL@% The following program sets the video mode to %@AB@%_MRES4COLOR%@AE@% and then cycles through background colors and palette combinations. It works on computers equipped with CGA, EGA, MCGA, or VGA cards. A color monitor is required. %@NL@% %@NL@% %@AS@% /* CGA.C: Demonstrate CGA colors. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <graph.h> %@AS@% #include <conio.h> %@AS@% %@AS@% long bkcolor[8] = %@AS@% { %@AS@% _BLACK, _BLUE, _GREEN, _CYAN, %@AS@% _RED, _MAGENTA, _BROWN, _WHITE %@AS@% }; %@AS@% %@AS@% char *bkcolor_name[] = %@AS@% { %@AS@% "_BLACK", "_BLUE", "_GREEN", "_CYAN", %@AS@% "_RED", "_MAGENTA", "_BROWN", "_WHITE" %@AS@% };%@AE@%%@NL@% %@NL@% %@AS@% main() %@AS@% { %@AS@% int i, j, k; %@AS@% _setvideomode( _MRES4COLOR ); %@AS@% for( i=0; i<= 3; i++ ) %@AS@% { %@AS@% _selectpalette( i ); %@AS@% for( k=0; k <= 7; k++ ) %@AS@% { %@AS@% _setbkcolor( bkcolor[k] ); %@AS@% for( j=0; j<=3; j++ ) %@AS@% { %@AS@% _settextposition( 1, 1 ); %@AS@% printf( "background color: %8s\n", bkcolor_name[k] ); %@AS@% printf( "palette: %d\ncolor: %d\n", i, j ); %@AS@% _setcolor( j ); %@AS@% _rectangle( _GFILLINTERIOR, 160, 100, 320, 200 ); %@AS@% getch(); %@AS@% } %@AS@% } %@AS@% } %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%EGA, MCGA, and VGA Palettes%@AE@%%@EH@%%@NL@% %@NL@% At the beginning of this chapter, we mentioned the difference between color indexes and color values. An analogy might make things clearer. Imagine a painter who owns 64 tubes of paint and a painter's palette that has room for only 16 globs of paint at any one time. A painting created under these constraints could contain only 16 colors (selected from a total of 64). One of the EGA graphics modes (%@AB@%_ERESCOLOR%@AE@%) is similar: 16 color indexes chosen from a total of 64 color values. (Color indexes are sometimes called "color attributes," or "pixel values." Color values are sometimes called "actual colors.") %@NL@% %@NL@% %@AB@%VGA Color Mixing%@AE@% - VGA offers the widest variety of color values: 262,144 (256K). Depending on the graphics mode, the VGA palette size may be 2, 16, or 256. When you select a color value, you specify a level of intensity ranging from 0-63 for each of the red, green, and blue color values. The long integer that defines a color value consists of four bytes (32 bits):%@NL@% %@NL@% %@AS@% MSB LSB %@AS@% zzzzzzzz zzBBBBBB zzGGGGGG zzRRRRRR%@AE@%%@NL@% %@NL@% The most-significant byte must contain all zeros. The two high bits in the remaining three bytes must also be 0. To mix a light red (pink), turn red all the way up, and mix in some green and blue: %@NL@% %@NL@% %@AS@% 00000000 00100000 00100000 00111111%@AE@%%@NL@% %@NL@% To represent this value in hexadecimal, use the number %@AS@% 0x0020203FL%@AE@% (the %@AS@% L %@AE@% marks it as a long value). You could also use the following macro: %@NL@% %@NL@% %@AS@% #define RGB ( r, g, b ) (0x3F3F3FL & ((long)(b) << 16 | (g) << 8 | (r)))%@AE@%%@NL@% %@NL@% To create pure yellow (100% red plus 100% green) and assign it to a variable %@AS@% y1%@AE@%, use this line: %@NL@% %@NL@% %@AS@% y1 = RGB( 63, 63, 0 );%@AE@%%@NL@% %@NL@% For white, turn all the colors on: %@AS@% RGB( 63, 63, 63 )%@AE@%. For black, set all colors to 0: %@AS@% RGB( 0, 0, 0 )%@AE@%. %@NL@% %@NL@% %@AB@%EGA Color Mixing%@AE@% - Mixing colors in EGA modes is similar to the mixing described above, but there are fewer intensities for the red, green, and blue components. In the modes that offer 64 colors, the R, G, and B values cover 2 bits and can range from 0 to 3. The long integer that defines an RGB color looks like this:%@NL@% %@NL@% %@AS@% MSB LSB %@AS@% zzzzzzzz zzBB???? zzGG???? zzRR????%@AE@%%@NL@% %@NL@% The bits marked %@AS@% z %@AE@% must be zeros and the bits marked with question marks can be any value. To form a pure red color value, you would use the constant %@AS@% 0x00000030L%@AE@%. For cyan (blue plus green), use %@AS@% 0x00303000L%@AE@%. The RGB macro defined above is easily modified for EGA monitors: %@NL@% %@NL@% %@AS@% #define EGARGB( r, g, b ) (0x3F3F3FL & ((long)(b) << 20 | (g) << 12 | (r %@AS@% << 4)))%@AE@%%@NL@% %@NL@% In this macro, you would pass values in the range 0-3 instead of 0-63. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%EGA Color Graphics Modes%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_MRES16COLOR%@AE@%, %@AB@%_HRES16COLOR%@AE@%, or %@AB@%_ERESCOLOR%@AE@% video modes display the best color graphics with an EGA adapter. The CGA modes will also display on the EGA but with the lower CGA resolution and decreased color options. %@NL@% %@NL@% The %@AB@%_remappalette%@AE@% function assigns a new color value to a color index. For example, when you first enter an EGA graphics mode, color index 1 equals the color value blue. To reassign the pure red color value to color index 1, you could use this line: %@NL@% %@NL@% %@AS@% _remappalette( 1, 0x000030L );%@AE@%%@NL@% %@NL@% Or, use the symbolic constant %@AB@%_RED%@AE@%, which is defined in the %@AS@% GRAPH.H %@AE@% file: %@NL@% %@NL@% %@AS@% _remappalette( 1, _RED );%@AE@%%@NL@% %@NL@% After this function call, any object currently drawn in color index 1 will instantly switch from blue to red. %@NL@% %@NL@% For EGA graphics, the first value is an integer in the range 0-15 and the second value is a%@AB@% long int%@AE@% defined as a mixture of red, green, and blue (you may also use the symbolic constants such as %@AB@%_RED%@AE@%). %@NL@% %@NL@% The %@AB@%_remapallpalette%@AE@% function changes all of the color indexes simultaneously. You pass it an array of color values. The first color value in the list becomes the new color associated with the color index 0. %@NL@% %@NL@% The number in a function call to set the color (such as %@AB@%_setcolor%@AE@%) is an index into the palette of available colors. In the default text palette, an index of 1 refers to blue but the palette could be remapped to change index 1 to any other available color. As a result, the color produced by that pixel value also changes. The number of color indexes depends on the number of colors supported by the current video mode. %@NL@% %@NL@% The %@AB@%_remappalette%@AE@% and %@AB@%_remapallpalette%@AE@% functions work in all modes but only with the EGA, MCGA, or VGA hardware. The %@AB@%_remappalette%@AE@% and %@AB@%_remapallpalette%@AE@% functions fail and return a value of -1 when you attempt to remap a palette without the EGA, MCGA, or VGA hardware. %@NL@% %@NL@% The following program draws a rectangle with a red interior. In the default EGA palette, color index 4 is red. This color index is changed to %@AB@%_BLUE%@AE@% in this program. %@NL@% %@NL@% %@AS@% /* EGA.C: EGA palettes. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <conio.h> %@AS@% #include <graph.h> %@AS@% %@AS@% main() %@AS@% { %@AS@% _setvideomode( _ERESCOLOR ); %@AS@% _setcolor( 4 ); %@AS@% _rectangle( _GFILLINTERIOR, 50, 50, 200, 200 ); %@AS@% %@AS@% _settextposition( 1, 1 ); %@AS@% printf( "Normal palette\n" ); %@AS@% printf( "Press a key" ); %@AS@% getch(); %@AS@% %@AS@% _remappalette( 4, _BLUE ); %@AS@% %@AS@% _settextposition( 1, 1 ); %@AS@% printf( "Remapped palette\n" ); %@AS@% printf( "Press a key" ); %@AS@% getch(); %@AS@% %@AS@% _remappalette( 4, _RED ); %@AS@% %@AS@% _settextposition( 1, 1 ); %@AS@% printf( "Restored palette\n" ); %@AS@% printf( "Press a key to clear the screen" ); %@AS@% getch(); %@AS@% %@AS@% _clearscreen( _GCLEARSCREEN ); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%VGA Color Graphics Modes%@AE@%%@EH@%%@NL@% %@NL@% The VGA card adds graphics modes %@AB@%_VRES2COLOR%@AE@%, %@AB@%_VRES16COLOR%@AE@%, and %@AB@%_MRES256COLOR%@AE@% to your repertoire. EGA and CGA modes can also be used with the VGA hardware, but with either lower resolution or fewer color choices. %@NL@% %@NL@% The VGA color graphics modes operate with a range of 262,144 (256K) color values. The %@AB@%_VRES2COLOR%@AE@% graphics mode displays two colors, the %@AB@%_VRES16COLOR%@AE@% graphics mode displays 16, and the %@AB@%_MRES256COLOR%@AE@% graphics mode displays 256 colors from the available VGA colors. %@NL@% %@NL@% %@AB@%Changing the Palette%@AE@% - The %@AB@%_remappalette%@AE@% function changes a color index to a specified color value. The function below remaps the color index 1 to the color value given by the symbolic constant %@AB@%_RED%@AE@% (which represents red). After this statement is executed, whatever was displayed as blue will now appear as red:%@NL@% %@NL@% %@AS@% _remappalette( 1, _RED ); /*reassign color index 1 %@AS@% to VGA red */%@AE@%%@NL@% %@NL@% Use the %@AB@%_remapallpalette%@AE@% function to remap all of the available color indexes simultaneously. The function's argument references an array of color values that reflects the remapping. The first color number in the list becomes the new color associated with color index 0. %@NL@% %@NL@% Symbolic constants for the default color numbers are supplied so that the remapping of VGA colors is compatible with EGA practice. The names of these constants are self-explanatory. For example, the color numbers for black, red, and light yellow are represented by the symbolic constants %@AB@%_BLACK%@AE@%, %@AB@%_RED%@AE@%, and %@AB@%_LIGHTYELLOW%@AE@%. %@NL@% %@NL@% All of the VGA display modes operate with any VGA video monitor. Colors are displayed as shades of gray when the monochrome analog display is connected. %@NL@% %@NL@% If you have a VGA card, the HORIZON.C program illustrates what can be done with the range of 256 colors: %@NL@% %@NL@% %@AS@% /* HORIZON.C: VGA graphics with cycling of 256 colors. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <stdlib.h> %@AS@% #include <conio.h> %@AS@% #include <graph.h> %@AS@% %@AS@% #define RED 0x0000003FL %@AS@% #define GRN 0x00003F00L %@AS@% #define BLU 0x003F0000L %@AS@% #define WHT 0x003F3F3FL %@AS@% #define STEP 21 %@AS@% %@AS@% struct videoconfig screen; %@AS@% long int rainbow[512]; %@AS@% %@AS@% main() %@AS@% { %@AS@% int i; %@AS@% long int col, gray; %@AS@% %@AS@% if( _setvideomode( _MRES256COLOR ) == 0 ) %@AS@% { %@AS@% printf( "This program requires a VGA card.\n" ); %@AS@% exit( 0 ); %@AS@% } %@AS@% for( col = 0; col < 64; col++ ) %@AS@% { %@AS@% gray = col | (col << 8) | (col << 16); %@AS@% rainbow[col] = rainbow[col + 256] = BLU & gray; %@AS@% rainbow[col + 64] = rainbow[col + 64 + 256] = BLU | gray; %@AS@% rainbow[col + 128] = rainbow[col + 128 + 256] = RED | (WHT & ~gray); %@AS@% rainbow[col + 192] = rainbow[col + 192 + 256] = RED & ~gray; %@AS@% } %@AS@% _setvieworg( 160, 85 ); %@AS@% %@AS@% for( i = 0; i < 255; i++ ) %@AS@% { %@AS@% _setcolor( 255 - i ); %@AS@% _moveto( i, i - 255 ); %@AS@% _lineto( -i, 255 - i ); %@AS@% _moveto( -i, i - 255 ); %@AS@% _lineto( i, 255 - i ); %@AS@% _ellipse( _GBORDER, -i, -i / 2, i, i / 2 ); %@AS@% } %@AS@% for( i = 0; !kbhit(); i += STEP, i %= 256 ) %@AS@% _remapallpalette( &(rainbow[i]) ); %@AS@% %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130007 @%%@AB@%Using the Color Video Text Modes%@AE@%%@EH@%%@NL@% %@NL@% Two color video text modes, %@AB@%_TEXTC40%@AE@% and %@AB@%_TEXTC80%@AE@%, can be used with the CGA, EGA, and VGA displays. These modes display steady or blinking text in any of 16 foreground colors with any one of 8 background colors. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Basics of Text Color Selection%@AE@%%@EH@%%@NL@% %@NL@% In a video text mode, each displayed character requires two bytes of video memory. The first byte contains the ASCII code representing the character and the second byte contains the display attribute. In the CGA color video text modes, the attribute byte determines the color and whether it will blink. Sixteen colors are available: the CGA pixel values, and the default EGA and VGA pixel values. Since the EGA and VGA palette can be remapped, these values can be made to correspond to any set of 16 colors with the appropriate palette mapping. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Using Text Colors%@AE@%%@EH@%%@NL@% %@NL@% Use the %@AB@%_gettextcolor%@AE@% and %@AB@%_getbkcolor%@AE@% functions to find the current text foreground and background colors. %@NL@% %@NL@% Values in the range 0-15 are interpreted as normal color. Values in the range 16-31 are the same colors as those in the range 0-15 but with blinking text. %@NL@% %@NL@% Use the %@AB@%_settextcolor%@AE@% and %@AB@%_setbkcolor%@AE@% functions to set foreground and background colors in video text mode. These functions use a single argument that specifies the pixel value to be used for text displayed with the %@AB@%_outtext%@AE@% function. The color indexes for color video text modes are defined in Table 13.4. %@NL@% %@NL@% %@AB@%Table 13.4 %@AB@%Text Colors%@AE@%%@AE@% %@TH: 11 556 02 08 10 08 50 @%Number Color Number Color%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%0 Black 8 Dark gray1 Blue 9 Light blue2 Green 10 Light green3 Cyan 11 Light cyan4 Red 12 Light red5 Magenta 13 Light magenta6 Brown 14 Light brown7 White 15 Light white%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 11 556 02 08 10 08 50 @% %@NL@% %@4@%%@AB@%Displaying Color Text%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_settextposition%@AE@% function moves the cursor to a row and column for displaying color text. The %@AB@%_outtext%@AE@% function displays the text. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Example: Viewing Text Colors%@AE@%%@EH@%%@NL@% %@NL@% The following program displays a chart showing all possible combinations of text and background colors: %@NL@% %@NL@% %@AS@% /* COLTEXT.C: Display text in color. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <conio.h> %@AS@% #include <graph.h> %@AS@% %@AS@% char buffer [80]; %@AS@% %@AS@% main() %@AS@% { %@AS@% int blink,fgd; %@AS@% long bgd; %@AS@% %@AS@% _clearscreen( _GCLEARSCREEN ); %@AS@% printf( "Text color attributes:\n" ); %@AS@% %@AS@% for( blink=0; blink<=16; blink+=16 ) %@AS@% { %@AS@% for( bgd=0; bgd<8; bgd++ ) %@AS@% { %@AS@% _setbkcolor( bgd ); %@AS@% _settextposition( bgd + ((blink / 16) * 9) + 3, 1 ); %@AS@% _settextcolor( 7 ); %@AS@% sprintf( buffer, "Bgd: %d Fgd:", bgd ); %@AS@% _outtext( buffer ); %@AS@% %@AS@% for( fgd=0; fgd<16; fgd++ ) %@AS@% { %@AS@% _settextcolor( fgd+blink ); %@AS@% sprintf( buffer, " %2d ", fgd+blink ); %@AS@% _outtext( buffer ); %@AS@% } %@AS@% } %@AS@% } %@AS@% getch(); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00130008 @%%@AB@%Text Coordinates%@AE@%%@EH@%%@NL@% %@NL@% Before you can write a program to print a word %@AI@%over there%@AE@% on the screen, you need a system that describes to the compiler where %@AI@%there%@AE@% really is. QuickC divides the text screen into rows and columns. See Figure 13.2. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Two important conventions to keep in mind about video text mode are: %@NL@% %@NL@% %@NL@% 1. Numbering starts at 1, not 0. An 80-column screen contains columns 1-80.%@NL@% %@NL@% 2. The row is always listed before the column.%@NL@% %@NL@% %@NL@% If the screen is in a video text mode that displays 25 rows and 80 columns (as in Figure 13.2), the rows are numbered 1-25 and the columns are numbered 1-80. In functions such as %@AB@%_settextposition%@AE@%, which is called in the next example program, the parameters you pass are row and column (in that order). %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00130009 @%%@AB@%Graphics Coordinates%@AE@%%@EH@%%@NL@% %@NL@% A similar (but slightly different) system is used for locating pixels on a graphics screen. There are three ways of describing the location of pixels on the screen: %@NL@% %@NL@% %@NL@% 1. The physical screen coordinates%@NL@% %@NL@% 2. The viewport coordinates%@NL@% %@NL@% 3. The window coordinates%@NL@% %@NL@% %@NL@% Each method is explained in the following sections. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130010 @%%@AB@%The Physical Screen%@AE@%%@EH@%%@NL@% %@NL@% Suppose you write a program that calls %@AB@%_setvideomode%@AE@% and puts the screen into the VGA graphics mode %@AB@%_VRES16COLOR%@AE@%. This gives you a screen containing 640 horizontal pixels and 480 vertical pixels. The individual pixels are named by their location relative to the %@AI@%x%@AE@% axis and %@AI@%y%@AE@% axis, as shown in Figure 13.3. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Two important differences between text coordinates and pixel coordinates are: %@NL@% %@NL@% %@NL@% 1. Numbering starts at 0, not 1. If there are 640 pixels, they're numbered 0-639.%@NL@% %@NL@% 2. The %@AI@%x%@AE@% coordinate (equivalent to a text column) is listed before the %@AI@%y%@AE@% coordinate.%@NL@% %@NL@% %@NL@% The upper left corner is called the "origin." The %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates for the origin are always (0, 0). If you use variables to refer to pixel locations, declare them as integers. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Changing the Origin with _setvieworg%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_setvieworg%@AE@% function changes the current location of the viewport's origin. When you first enter graphics mode, the "viewport" is equivalent to the physical %@NL@% %@NL@% screen. You pass two integers, which represent the %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates of a physical screen location. For example, the following line would move the origin to the physical screen location (50, 100): %@NL@% %@NL@% %@AS@% _setvieworg( 50, 100 );%@AE@%%@NL@% %@NL@% The effect on the screen is illustrated in Figure 13.4. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% The number of pixels hasn't changed, but the names given to the points have changed. The %@AI@%x%@AE@% axis now ranges from -50 to +589 instead of 0 to 639. The %@AI@%y%@AE@% axis now covers the values -100 to +379. (If you own an adapter other than the VGA, the numbers are different but the effect is the same.) %@NL@% %@NL@% All standard graphics functions are affected by the new origin, including %@AB@%_arc%@AE@%, %@AB@%_ellipse%@AE@%, %@AB@%_lineto%@AE@%, %@AB@%_moveto%@AE@%, %@AB@%_pie%@AE@%, and %@AB@%_rectangle%@AE@%. %@NL@% %@NL@% For example, if you call the %@AB@%_rectangle%@AE@% function after relocating the viewport origin, and pass it the values (0, 0) and (40, 40), the rectangle would be drawn 50 pixels from the left edge of the screen and 100 pixels from the top. It would not appear in the upper left corner. %@NL@% %@NL@% The values passed to %@AB@%_setvieworg%@AE@% are always physical screen locations. Suppose you called the same function twice: %@NL@% %@NL@% %@AS@% _setvieworg( 50, 100 ); %@AS@% _setvieworg( 50, 100 );%@AE@%%@NL@% %@NL@% The viewport origin would not move to (100, 200). It would remain at the phys-ical screen location (50, 100). %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Defining a Clipping Region with _setcliprgn%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_setcliprgn%@AE@% function creates an invisible rectangular area on the screen called a "clipping region." Attempts to draw inside the clipping region are successful, while attempts to draw outside the region are not. %@NL@% %@NL@% When you first enter a graphics mode, the default clipping region occupies the entire screen. QuickC ignores any attempts to draw outside the screen. %@NL@% %@NL@% Changing the clipping region requires one call to %@AB@%_setcliprgn%@AE@%. Suppose you've entered the CGA graphics mode %@AB@% _MRES4COLOR%@AE@%, which has a screen resolution of 320 x 200. If you draw a diagonal line from (0, 0) to (319, 199), from the top left to the bottom right corner, the screen looks like Figure 13.5. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% You could create a clipping region with this line: %@NL@% %@NL@% %@AS@% _setcliprgn( 10, 10, 309, 189 )%@AE@%%@NL@% %@NL@% With the clipping region in effect, the same %@AB@%_lineto%@AE@% command would put the line shown in Figure 13.6 on the screen. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% The broken lines don't actually print on the screen. They indicate the outer bounds of the clipping region. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130011 @%%@AB@%Viewport Coordinates%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_setviewport%@AE@% function establishes a new viewport within the boundaries of the physical screen. A standard viewport has two distinguishing features: %@NL@% %@NL@% %@NL@% 1. The origin of a viewport is in the upper left corner.%@NL@% %@NL@% 2. The clipping region matches the outer boundaries of the viewport.%@NL@% %@NL@% %@NL@% The %@AB@%_setviewport%@AE@% function does the same thing as calling the %@AB@%_setvieworg%@AE@% and the %@AB@%_setcliprgn%@AE@% functions. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00130012 @%%@AB@%Real Coordinates in a Window%@AE@%%@EH@%%@NL@% %@NL@% Functions that refer to coordinates on the physical screen and within the viewport require integer values. In real-life graphing applications, you might wish to use floating-point values─stock prices, the price of wheat, average rainfall, and so on. The %@AB@%_setwindow%@AE@% function allows you to scale the screen to almost any size. In addition, the window-related functions take double-precision, floating-point values instead of integers. %@NL@% %@NL@% For example, say you want to graph 12 months of average temperatures that range from -40 to +100. You could add the following line to your program: %@NL@% %@NL@% %@AS@% _setwindow( TRUE, 1.0, -40.0, 12.0, 100.0 );%@AE@%%@NL@% %@NL@% The first argument is the invert flag, which puts the lowest %@AI@%y%@AE@% value in the bottom left corner. The minimum and maximum Cartesian coordinates follow (the decimal point marks them as floating-point values). The new organization of the screen is shown in Figure 13.7. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Note that January and December are plotted on the left and right edges of the screen. In an application like this, it might be better to number the %@AI@%x%@AE@% axis from 0.0 to 13.0, to provide some extra space. %@NL@% %@NL@% If you next plot a point with %@AB@%_setpixel_w%@AE@% or draw a line with %@AB@%_lineto_w%@AE@%, the values are automatically scaled to the established window. %@NL@% %@NL@% Follow these four steps to use real-coordinate graphics: %@NL@% %@NL@% %@NL@% 1. Enter a graphics mode with %@AB@%_setvideomode%@AE@%.%@NL@% %@NL@% 2. Use %@AB@%_setviewport%@AE@% to create a viewport area. (This step is optional if you plan to use the entire screen.)%@NL@% %@NL@% 3. Create a real-coordinate window with %@AB@%_setwindow%@AE@%, passing an %@AB@%int%@AE@% invert flag and four %@AB@%double%@AE@% %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates for the minimum and maximum values.%@NL@% %@NL@% 4. Draw graphics shapes with %@AB@%_rectangle_w%@AE@% and other functions. Do not confuse %@AB@%_rectangle%@AE@% (the viewport function) with %@AB@%_rectangle_w%@AE@% (the window function for drawing rectangles). All window functions end with an underscore and a letter %@AB@%w%@AE@% or an underscore and %@AB@%wxy%@AE@%.%@NL@% %@NL@% %@NL@% Real-coordinate graphics can give you a lot of flexibility. For example, you can fit either axis into a small range (such as 151.25 to 151.45) or into a large range (-50,000 to +80,000), depending on the type of data you're graphing. In addition, by changing the window coordinates, you can create the effects of zooming in or panning across a figure. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Example Program%@AE@%%@EH@%%@NL@% %@NL@% The program below illustrates some ways to use the real-coordinate windowing functions. %@NL@% %@NL@% %@AS@% /* REALG.C: Real-coordinate graphics. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <conio.h> %@AS@% #include <graph.h> %@AS@% %@AS@% #define TRUE 1 %@AS@% #define FALSE 0 %@AS@% %@AS@% int four_colors( void ); %@AS@% void three_graphs( void ); %@AS@% void grid_shape( void ); %@AS@% %@AS@% int halfx, halfy; %@AS@% struct videoconfig screen; %@AS@% double bananas[] = %@AS@% { %@AS@% -0.3, -0.2, -0.224, -0.1, -0.5, +0.21, +2.9, %@AS@% +0.3, +0.2, 0.0, -0.885, -1.1, -0.3, -0.2, %@AS@% +.001, +.005, +0.14, 0.0, -0.9, -0.13, +0.3 %@AS@% }; %@AS@% %@AS@% main() %@AS@% { %@AS@% if( four_colors() ) %@AS@% three_graphs(); %@AS@% else %@AS@% printf( "This program requires a CGA, EGA,\ %@AS@% or VGA graphics card.\n" ); %@AS@% } %@AS@% /* %@AS@% . Additional functions defined below %@AS@% . %@AS@% . %@AS@% */%@AE@%%@NL@% %@NL@% The %@AB@%main%@AE@% function is very short. It calls the %@AS@% four_colors %@AE@% function (defined below), which attempts to enter a graphics mode where at least four colors are available. If it succeeds, the %@AS@% three_graphs %@AE@% function is called, which uses the numbers in the %@AS@% bananas %@AE@% array to draw three graphs. The REALG.C screen output is shown in Figure 13.8. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% It's worth noting that the %@AS@% grid_shape %@AE@% function (defined below) that draws the graphs is using the same numbers in each case. However, the program uses three different real-coordinate windows. The two windows in the top half are the same size in physical coordinates, but they have different window sizes. In all three cases, the grid is 2 units wide. In the upper left corner, the window is 4 units wide; in the upper right, the window is 6 units wide, which makes the graph appear smaller. %@NL@% %@NL@% In two of the three graphs, one of the lines goes off the edge, outside the clipping region. The lines do not intrude into the other windows, since defining a window creates a clipping region. %@NL@% %@NL@% Finally, note that the graph on the bottom of the screen seems to be upside down with respect to the two graphs above it. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Checking the Adapter%@AE@%%@EH@%%@NL@% %@NL@% The first step in any graphics program is to enter a graphics mode. The %@AS@% %@AS@%four_colors %@AE@% function performs this step: %@NL@% %@NL@% %@AS@% /* four_colors function from REALG.C. */ %@AS@% %@AS@% int four_colors( void ) %@AS@% { %@AS@% _getvideoconfig( &screen ); %@AS@% switch( screen.adapter ) %@AS@% { %@AS@% case _CGA: %@AS@% case _OCGA: %@AS@% _setvideomode( _MRES4COLOR ); %@AS@% break; %@AS@% case _EGA: %@AS@% case _OEGA: %@AS@% _setvideomode( _ERESCOLOR ); %@AS@% break; %@AS@% case _VGA: %@AS@% case _OVGA: %@AS@% _setvideomode( _VRES16COLOR ); %@AS@% break; %@AS@% default: %@AS@% return( FALSE ); %@AS@% } %@AS@% _getvideoconfig( &screen ); %@AS@% return( TRUE ); %@AS@% }%@AE@%%@NL@% %@NL@% The %@AB@%_getvideoconfig%@AE@% function places some information into the %@AB@%videoconfig%@AE@% structure called %@AS@% screen%@AE@%. Then we use the member %@AS@% screen.adapter %@AE@% in a %@AB@%switch%@AE@% statement construct to turn on the matching graphics mode. The symbolic constants %@AB@%_CGA%@AE@% and the rest are defined in the GRAPH.H file. The modes that begin with the letter %@AB@%O%@AE@% are Olivetti modes. %@NL@% %@NL@% If the computer is equipped with a color card, %@AB@%_getvideoconfig%@AE@% returns a %@AB@%TRUE%@AE@%. If it is not, it returns a %@AB@%FALSE%@AE@%, which causes %@AB@%main%@AE@% to skip the %@AS@% %@AS@%three_graphs %@AE@% function. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Three Windows, Three Graphs%@AE@%%@EH@%%@NL@% %@NL@% If the %@AS@% four_colors %@AE@% function works properly, %@AB@%main%@AE@% calls the function below, which prints the three graphs. %@NL@% %@NL@% %@AS@% /* three_graphs function from REALG.C. */ %@AS@% %@AS@% void three_graphs( void ) %@AS@% { %@AS@% int xwidth, yheight, cols, rows; %@AS@% struct _wxycoord upleft, botright; %@AS@% %@AS@% _clearscreen( _GCLEARSCREEN ); %@AS@% xwidth = screen.numxpixels; %@AS@% yheight = screen.numypixels; %@AS@% halfx = xwidth/2; %@AS@% halfy = yheight/2; %@AS@% cols = screen.numtextcols; %@AS@% rows = screen.numtextrows; %@AS@% %@AS@% /* first window */ %@AS@% _setviewport( 0, 0, halfx-1, halfy-1 ); %@AS@% _settextwindow( 1, 1, rows/2, cols/2 ); %@AS@% _setwindow( FALSE, -2.0, -2.0, 2.0, 2.0 ); %@AS@% grid_shape(); %@AS@% _rectangle( _GBORDER, 0, 0, halfx-1, halfy-1 ); %@AS@% %@AS@% /* second window */ %@AS@% _setviewport( halfx, 0, xwidth-1, halfy-1 ); %@AS@% _settextwindow( 1, cols/2+1, rows/2, cols ); %@AS@% _setwindow( FALSE, -3.0, -3.0, 3.0, 3.0 ); %@AS@% grid_shape(); %@AS@% _rectangle_w( _GBORDER, -3.0, -3.0, 3.0, 3.0 ); %@AS@% %@AS@% /* third window */ %@AS@% _setviewport( 0, halfy, xwidth-1, yheight-1 ); %@AS@% _settextwindow( rows/2+1, 1, rows, cols ); %@AS@% _setwindow( TRUE, -3.0, -1.5, 1.5, 1.5 ); %@AS@% grid_shape(); %@AS@% upleft.wx = -3.0; %@AS@% upleft.wy = -1.5; %@AS@% botright.wx = 1.5; %@AS@% botright.wy = 1.5; %@AS@% _rectangle_wxy( _GBORDER, &upleft, &botright ); %@AS@% %@AS@% getch(); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% }%@AE@%%@NL@% %@NL@% %@AB@%Clearing the Screen%@AE@% - Although entering a graphics mode automatically clears the screen, it doesn't hurt to be sure, so %@AS@% three_graphs %@AE@% calls the %@AB@%_clearscreen%@AE@% function:%@NL@% %@NL@% %@AS@% _clearscreen( _GCLEARSCREEN );%@AE@%%@NL@% %@NL@% The %@AB@%_GCLEARSCREEN%@AE@% constant causes the entire physical screen to clear. Other options include %@AB@%_GVIEWPORT%@AE@% and %@AB@%_GWINDOW%@AE@%, which clear the current viewport and the current text window, respectively. %@NL@% %@NL@% %@AB@%The First Window%@AE@% - After assigning values to some variables, the %@AS@% %@AS@%three_graphs %@AE@% function creates the first window:%@NL@% %@NL@% %@AS@% _setviewport( 0, 0, halfx - 1, halfy - 1 ); %@AS@% _settextwindow( 1, 1, rows / 2, cols / 2 ); %@AS@% _setwindow( FALSE, -2.0, -2.0, 2.0, 2.0 );%@AE@%%@NL@% %@NL@% First a viewport is defined to cover the upper left quarter of the screen. Next, a text window is defined within the boundaries of that border. (Note the numbering starts at 1 and the row location precedes the column.) Finally, a window is defined. The %@AB@%FALSE%@AE@% constant forces the %@AI@%y%@AE@% axis to increase from top to bottom. The corners of the window are (-2.0, -2.0) in the upper left and (2.0, 2.0) in the bottom right corner. %@NL@% %@NL@% Next, the function %@AS@% grid_shape %@AE@% is called, and a border is added to the window: %@NL@% %@NL@% %@AS@% grid_shape(); %@AS@% _rectangle( _GBORDER, 0, 0, halfx-1, halfy-1 );%@AE@%%@NL@% %@NL@% Note that this is the standard %@AB@%_rectangle%@AE@% function, which takes coordinates relative to the viewport (not window coordinates). %@NL@% %@NL@% %@AB@%Two More Windows%@AE@% - The two other windows are similar to the first. All three call %@AS@% grid_shape %@AE@% (defined below), which draws a grid from location (-1.0, -1.0) to (+1.0, +1.0). The grid appears in different sizes because the coordinates in the windows vary. The second window ranges from (-3.0, -3.0) to (+3.0, +3.0), so the width of the grid is one-third the width of the second window, while it is one-half the width of the first.%@NL@% %@NL@% Note also that the third window contains a %@AB@%TRUE%@AE@% as the first argument. This causes the%@AI@% y %@AE@%axis to increase from bottom to top, instead of top to bottom. As a result, this graph appears to be upside down in relation to the other two. %@NL@% %@NL@% After calling %@AS@% grid_shape%@AE@%, the program frames each window with one of the following functions: %@NL@% %@NL@% %@AS@% _rectangle( _GBORDER, 0, 0, halfx -1, halfy -1 );%@AE@%%@NL@% %@NL@% %@AS@% _rectangle_w( _GBORDER, -3.0, -3.0, 3.0, 3.0 ); %@AE@%%@NL@% %@NL@% %@AS@% _rectangle_wxy( _GBORDER, &upleft, &botright );%@AE@%%@NL@% %@NL@% All three functions contain a fill flag as the first argument. The %@AB@%_rectangle%@AE@% function takes integer arguments that refer to the viewport screen coordinates. The function %@AB@%_rectangle_w%@AE@% takes four double-precision, floating-point values referring to window coordinates: upper left %@AI@%x%@AE@%, upper left %@AI@%y%@AE@%, lower right %@AI@%x%@AE@%, and lower right %@AI@%y%@AE@%. The function %@AB@%_rectangle_wxy%@AE@% takes two arguments: the addresses of two structures of type %@AB@%_wxycoord%@AE@%, which contains two %@AB@%double%@AE@% types named %@AB@%wx%@AE@% and %@AB@%wy%@AE@%. The structure is defined in GRAPH.H. The values are assigned just before %@AB@%_rectangle_wxy%@AE@% is called. %@NL@% %@NL@% %@AB@%Text, Colors, and Lines%@AE@% - The %@AS@% grid_shape %@AE@% function is shown below:%@NL@% %@NL@% %@AS@% /* grid_shape from the REALG.C program. */ %@AS@% %@AS@% void grid_shape( void ) %@AS@% { %@AS@% int i, numc, x1, y1, x2, y2; %@AS@% double x, y; %@AS@% char txt[80];%@AE@%%@NL@% %@NL@% %@AS@% numc = screen.numcolors; %@AS@% for( i = 1; i <numc; i++ ) %@AS@% { %@AS@% _settextposition( i, 2 ); %@AS@% _settextcolor( i ); %@AS@% sprintf( txt, "Color %d", i ); %@AS@% _outtext( txt ); %@AS@% } %@AS@% _setcolor( 1 ); %@AS@% _rectangle_w( _GBORDER, -1.0, -1.0, 1.0, 1.0 ); %@AS@% _rectangle_w( _GBORDER, -1.02, -1.02, 1.02, 1.02 );%@AE@%%@NL@% %@NL@% %@AS@% for( x = -0.9, i = 0; x <0.9; x += 0.1 ) %@AS@% { %@AS@% _setcolor( 2 ); %@AS@% _moveto_w( x, -1.0 ); %@AS@% _lineto_w( x, 1.0 ); %@AS@% _moveto_w( -1.0, x ); %@AS@% _lineto_w( 1.0, x ); %@AS@% %@AS@% _setcolor( 3 ); %@AS@% _moveto_w( x - 0.1, bananas[i++] ); %@AS@% _lineto_w( x, bananas[i] ); %@AS@% } %@AS@% _moveto_w( 0.9, bananas[i++] ); %@AS@% _lineto_w( 1.0, bananas[i] ); %@AS@% }%@AE@%%@NL@% %@NL@% First, the number of available color indexes is assigned to the %@AS@% numc %@AE@% variable and a %@AB@%for%@AE@% loop displays all of the available colors: %@NL@% %@NL@% %@AS@% numc = screen.numcolors; %@AS@% for( i = 1; i < numc; i++ ) %@AS@% { %@AS@% _settextposition( i, 2 ); %@AS@% _settextcolor( i ); %@AS@% sprintf( txt, "Color %d", i ); %@AS@% _outtext( txt ); %@AS@% }%@AE@%%@NL@% %@NL@% The names of the functions are self-explanatory. The advantage of using %@AB@%_outtext%@AE@% in graphics mode is that, unlike %@AB@%printf%@AE@%, you can control the text color. %@NL@% %@NL@% The function names that end with %@AB@%_w%@AE@% work the same as their viewport equivalents, except you pass double-precision, floating-point values instead of integers. For example, you pass integers to %@AB@%_lineto%@AE@% but floating-point values to %@AB@%_lineto_w.%@AE@% %@NL@% %@NL@% If you're interested in further explorations of graphics, Chapters 14 and 15 introduce Presentation Graphics and fonts, both of which offer even more graphics options. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00140001 @%%@1@%%@AB@%Chapter 14 Presentation Graphics%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% Presentation Graphics is the name given to a library of chart-generating functions included with the QuickC package. With these functions your QuickC programs can display data as a variety of graphs such as pie charts, bar and column charts, line graphs, and scatter diagrams. Whole columns of unintelligible numbers can be reduced to a single expressive picture with Presentation Graphics. %@NL@% %@NL@% This chapter shows you how to use the Presentation Graphics library in your QuickC programs. The first section is an introduction to Presentation Graphics. It explains terminology and describes some of the library's many capabilities. The middle sections of this chapter list the steps involved in writing a charting program and illustrate them with short examples. %@NL@% %@NL@% The concluding portions of the chapter delve more deeply into Presentation Graphics. Here you'll learn about the Presentation Graphics default data structures and how to manipulate them. The final section presents a short reference list of all the functions that comprise the Presentation Graphics library. %@NL@% %@NL@% To use Presentation Graphics you need a graphics adapter and a monitor capable of bit-mapped display─the same equipment mentioned in Chapter 13, "Graphics." Support is provided for CGA, EGA, VGA, MCGA, Hercules monochrome graphics, and Olivetti Color Board. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00140002 @%%@AB@%Terminology%@AE@%%@EH@%%@NL@% %@NL@% Certain terms and phrases pertaining to Presentation Graphics and its functions are used throughout this chapter. The following description of Presentation Graphics terminology will help you better understand this chapter. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Data Series%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Groups or series of data can be graphed on the same chart.%@AE@% %@NL@% %@NL@% Data that are related by a common idea or purpose constitutes a "series." For example, the prices of a futures commodity over the course of a year form a single series of data. The commodity's volume and open interest form two more series for the same period of time. Presentation Graphics allows you to plot multiple series on the same graph. In theory only your system's memory capacity restricts the number of data series that can appear on a graph. However, there are practical considerations. %@NL@% %@NL@% Characteristics such as color and pattern help distinguish one series from an-other. You can more readily differentiate series on a color monitor than you can on a monochrome monitor. The number of series that can comfortably appear on the same chart depends on the chart type and the number of available colors. Only experimentation can tell you what is best for your system. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Categories%@AE@%%@EH@%%@NL@% %@NL@% Categories are non-numeric data. A set of categories forms a frame of reference for the comparisons of numeric data. For example, the months of the year are categories against which numeric data such as rainfall can be plotted. %@NL@% %@NL@% Regional sales provide another example. A chart can show comparisons of a company's sales in different parts of the country. Each region forms a category. The sales within each region are numeric data that have meaning only within the context of a particular category. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Values%@AE@%%@EH@%%@NL@% %@NL@% Values are numeric data. Sales, stock prices, air temperatures, populations─all are series of values that can be plotted against categories or against other values. %@NL@% %@NL@% Presentation Graphics allows you to overlay different series of value data on a single graph. For example, average monthly temperatures or monthly sales of heating oil during different years─or a combination of temperatures and sales─can be plotted together on the same graph. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Pie Charts%@AE@%%@EH@%%@NL@% %@NL@% %@AU@%(Please refer to the printed book.)%@AE@%%@NL@% %@NL@% "Pie charts" are used to represent data by showing the relationship of each part to the whole. A good example is a company's monthly sales figures. The sales to the company's various accounts can be represented as slices of the pie. %@NL@% %@NL@% Presentation Graphics can display either a standard or an "exploded" pie chart. The exploded view shows the pie with one or more pieces separated for emphasis. Presentation Graphics optionally labels each slice of a pie chart with a percentage figure. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Bar and Column Charts%@AE@%%@EH@%%@NL@% %@NL@% %@AU@%(Please refer to the printed book.)%@AE@%%@NL@% %@NL@% As the name implies, a "bar chart" shows data as horizontal bars. Bar charts show comparisons among items rather than absolute value. %@NL@% %@NL@% "Column charts"%@NL@% %@NL@% %@AU@%(Please refer to the printed book.)%@AE@%%@NL@% %@NL@% are vertical bar charts. Column charts are frequently used to show variations over a period of time, since they suggest time flow better than a bar chart %@NL@% %@4@%%@AB@%Line Graphs%@AE@%%@EH@%%@NL@% %@NL@% %@AU@%(Please refer to the printed book.)%@AE@%%@NL@% %@NL@% "Line graphs" illustrate trends or changes in data. They show how a series of values varies against some category─for example, average temperatures throughout a particular year. %@NL@% %@NL@% Traditionally, line graphs show a collection of data points connected by lines; hence the name. However, Presentation Graphics can also plot points that are not connected by lines. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Scatter Diagrams%@AE@%%@EH@%%@NL@% %@NL@% %@AU@%(Please refer to the printed book.)%@AE@%%@NL@% %@NL@% A "scatter diagram" is the only type of graph available in Presentation Graphics that compares values with values. A scatter diagram simply plots points. One value may correspond to several other values. %@NL@% %@NL@% Scatter diagrams illustrate the relationship between numeric values in different groups of data. They graphically show trends and correlations not easily detected from rows and columns of raw numbers. This explains why scatter diagrams are a favorite tool of statisticians and forecasters. %@NL@% %@NL@% They are most useful with relatively large populations of data. Consider, for example, the relationship between personal income and family size. If you poll one thousand wage earners for their income and family size, you have a scatter diagram with one thousand points. If you combine your results so that you're left with one average income for each family size, you have a line graph. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Axes%@AE@%%@EH@%%@NL@% %@NL@% All Presentation Graphics charts except pie charts are displayed with two perpendicular reference lines called "axes." The vertical or %@AI@%y%@AE@% axis runs from top to bottom of the chart and is placed against the left side of the screen. The horizontal or %@AI@%x%@AE@% axis runs from left to right across the bottom of the screen. %@NL@% %@NL@% %@AU@% The chart type determines which axes are used for category and value data.%@AE@% %@NL@% %@NL@% The %@AI@%x%@AE@% axis is the category axis for column and line charts and the value axis for bar charts. The %@AI@%y%@AE@% axis is the value axis for column and line charts and the category axis for bar charts. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Chart Windows%@AE@%%@EH@%%@NL@% %@NL@% The "chart window" defines that part of the screen on which the chart is drawn. Normally the window fills the entire screen, but Presentation Graphics allows you to resize the window for smaller graphs. By redefining the chart window to different screen locations, you can view separate graphs together on the same screen. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Data Windows%@AE@%%@EH@%%@NL@% %@NL@% While the chart window defines the entire graph including axes and labels, the "data window" defines only the actual plotting area. This is the portion of the graph to the right of the %@AI@%y%@AE@% axis and above the %@AI@%x%@AE@% axis. You cannot directly specify the size of the data window. Presentation Graphics automatically determines its size based on the dimensions of the chart window. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Chart Styles%@AE@%%@EH@%%@NL@% %@NL@% Each of the five types of Presentation Graphics charts can appear in two different chart styles, as described in Table 14.1. %@NL@% %@NL@% %@AB@%Table 14.1 %@AB@%Presentation Graphics Chart Styles%@AE@%%@AE@% %@TH: 8 488 02 12 20 44 @%Chart Type Chart Style #1 Chart Style #2%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%Pie With percentages Without percentagesBar Side-by-side StackedColumn Side-by-side StackedLine Points with lines Points onlyScatter Points with lines Points only%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 8 488 02 12 20 44 @% Bar and column charts have only one style when displaying a single series of data. The styles "side-by-side" and "stacked" are applicable when more than one series appear on the same chart. The first style arranges the bars or columns for the different series side by side, showing relative heights or lengths. The stacked style, illustrated in Figure 14.1 for a column chart, emphasizes relative sizes between bars or columns. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Legends%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% Legends help identify individual data series.%@AE@% %@NL@% %@NL@% When displaying more than one data series on a chart, Presentation Graphics uses different colors, line styles, or patterns to differentiate the series. Presentation Graphics also can display a "legend" that labels the different series of a chart. For a pie chart, the legend labels individual slices of the pie. %@NL@% %@NL@% The format is similar to the legends found on printed graphs and maps. A sample of the color and pattern used to graph the series appears next to the series label. This identifies which set of data the labels belong to. The "Palettes" section later in this chapter explains how different data series are identified by color and pattern. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00140003 @%%@AB@%Presentation Graphics Program Structure%@AE@%%@EH@%%@NL@% %@NL@% QuickC programs that use Presentation Graphics typically follow seven steps: %@NL@% %@NL@% %@AB@%Step%@AE@% %@AB@%Comments%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% Include required header files. Along with other header files your program may need, you must include the files GRAPH.H and PGCHART.H. Set video mode to graphics. Refer to Chapter 13, "Graphics," for a discussion of video modes supported by QuickC. This chapter explains how to change modes within a QuickC program. Initialize Presentation Graphics Presentation Graphics places charting chart parameters in a data structure. These environment. parameters determine how a graph will appear on the screen. Collectively they make up the "chart environment," described in the section "Customizing Presentation Graphics." Presentation Graphics sets the environment parameters to default values. The amount of initialization that must be done by your program depends on how extensively it relies on defaults. Assemble plot data. Data can be collected in a variety of ways: by calculating it elsewhere in the program, reading it from files, or entering it from the keyboard. All plot data must be assembled in arrays because the Presentation Graphics functions locate them through pointers. Call Presentation Graphics Display your chart. functions. Pause while chart is on the Your program should pause after a chart screen. is displayed. This step allows sufficient time to read the chart. A common method is to wait for a keyboard entry before resuming. Reset video mode. When your program detects the signal to continue, it should normally reset the video to its original mode. Once your program successfully compiles, you must link it to the library modules PGCHART.LIB and GRAPHICS.LIB. Use the Microsoft Overlay Linker %@NL@% %@NL@% QLINK.EXE or the QCL command-line interface to link programs outside the QuickC environment. For descriptions of QLINK and QCL, see the %@AI@%Microsoft %@AI@%QuickC Tool Kit%@AE@%, Chapter 1, "Creating Executable Programs." %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00140004 @%%@AB@%Five Example Chart Programs%@AE@%%@EH@%%@NL@% %@NL@% You'll have a better idea of Presentation Graphics capabilities once you've seen what it can do. To that end some simple examples are presented in this section. The sample programs that follow use only five of the 22 Presentation Graphics functions: %@AB@%_pg_initchart%@AE@%, %@AB@%_pg_defaultchart%@AE@%, %@AB@%_pg_chartpie%@AE@%, %@AB@%_pg_chart%@AE@%, and %@AB@%_pg_chartscatter%@AE@%. Appendix B, "C Library Guide," and online help document these functions and their arguments. But the example code is straightforward, and you should be able to follow easily for now. Each program is commented so that you can recognize the seven steps given above. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%A Sample Data Set%@AE@%%@EH@%%@NL@% %@NL@% Suppose a grocer wants to graph the sales of orange juice over the course of a single year. Sales figures are on a monthly basis, so the grocer selects as category data the months of the year from January through December. The sales figures are shown below. %@NL@% %@NL@% %@TH: 15 614 02 26 50 @%Month Quantity (cases)%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%January 33February 27March 42April 64May 106June 157July 182August 217September 128October 62November 43December 36%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 15 614 02 26 50 @% %@NL@% %@4@%%@AB@%Example: Pie Chart%@AE@%%@EH@%%@NL@% %@NL@% The following program uses Presentation Graphics to display a pie chart for the grocer's data. The chart, which is shown in Figure 14.2, remains on the screen until a key is pressed. %@NL@% %@NL@% The Presentation Graphics functions return values that identify error conditions. A return value of 0 indicates that the function has completed its work without error. Refer to the header file PGCHART.H and online help for descriptions of the nonzero error codes. %@NL@% %@NL@% %@AS@% /* PIE.C: Create sample pie chart. */ %@AS@% %@AS@% #include <conio.h> %@AS@% #include <string.h> %@AS@% #include <graph.h> %@AS@% #include <pgchart.h>%@AE@%%@NL@% %@NL@% %@AS@% #define MONTHS 12 %@AS@% %@AS@% typedef enum {FALSE, TRUE} boolean; %@AS@% %@AS@% float far value[MONTHS] = %@AS@% { %@AS@% 33.0, 27.0, 42.0, 64.0,106.0,157.0, %@AS@% 182.0,217.0,128.0, 62.0, 43.0, 36.0 %@AS@% }; %@AS@% char far *category[MONTHS] = %@AS@% { %@AS@% "Jan", "Feb", "Mar", "Apr", %@AS@% "May", "Jun", "Jly", "Aug", %@AS@% "Sep", "Oct", "Nov", "Dec" %@AS@% }; %@AS@% short far explode[MONTHS] = {0}; %@AS@% %@AS@% main() %@AS@% { %@AS@% chartenv env; %@AS@% int mode = _VRES16COLOR; %@AS@% %@AS@% /* Set highest video mode available */ %@AS@% while(!_setvideomode( mode )) %@AS@% mode--; %@AS@% if(mode == _TEXTMONO) %@AS@% return( 0 ); %@AS@% %@AS@% /* Initialize chart library and a default pie chart */ %@AS@% _pg_initchart(); %@AS@% _pg_defaultchart( &env, _PG_PIECHART, _PG_PERCENT ); %@AS@% %@AS@% /* Add titles and some chart options */ %@AS@% strcpy( env.maintitle.title, "Good Neighbor Grocery" ); %@AS@% env.maintitle.titlecolor = 6; %@AS@% env.maintitle.justify = _PG_RIGHT; %@AS@% strcpy( env.subtitle.title, "Orange Juice Sales" ); %@AS@% env.subtitle.titlecolor = 6; %@AS@% env.subtitle.justify = _PG_RIGHT; %@AS@% env.chartwindow.border = FALSE;%@AE@%%@NL@% %@NL@% %@AS@% /* Parameters for call to _pg_chartpie are: %@AS@% * %@AS@% * env - Environment variable %@AS@% * category - Category labels %@AS@% * value - Data to chart %@AS@% * explode - Separated pieces %@AS@% * MONTHS - Number of data values %@AS@% */ %@AS@% if(_pg_chartpie( &env, category, value, %@AS@% explode, MONTHS )) %@AS@% { %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% _outtext( "Error: can't draw chart" ); %@AS@% } %@AS@% else %@AS@% { %@AS@% getch(); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% } %@AS@% return( 0 ); %@AS@% } %@AE@%%@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Example: Bar Chart%@AE@%%@EH@%%@NL@% %@NL@% The code for the PIE.C program needs only minor alterations to produce bar, column, and line charts for the same data: %@NL@% %@NL@% %@NL@% ■ Replace the call to %@AB@%_pg_chartpie%@AE@% with %@AB@%_pg_chart%@AE@%. This function produces bar, column, and line charts depending on the value of the second argument for %@AB@%_pg_defaultchart%@AE@%.%@NL@% %@NL@% ■ Give new arguments to %@AB@%_pg_defaultchart%@AE@% that specify chart type and style.%@NL@% %@NL@% ■ Assign titles for the %@AI@%x%@AE@% axis and %@AI@%y%@AE@% axis in the structure %@AS@% env %@AE@%.%@NL@% %@NL@% ■ Remove references to array %@AS@% explode %@AE@%(applicable only to pie charts).%@NL@% %@NL@% %@NL@% The following example produces the bar chart shown in Figure 14.3. %@NL@% %@NL@% %@AS@% /* BAR.C: Create sample bar chart. */ %@AS@% #include <conio.h> %@AS@% #include <string.h> %@AS@% #include <graph.h> %@AS@% #include <pgchart.h> %@AS@% #define MONTHS 12 %@AS@% typedef enum {FALSE, TRUE} boolean; %@AS@% float far value[MONTHS] = %@AS@% { %@AS@% 33.0, 27.0, 42.0, 64.0,106.0,157.0, %@AS@% 182.0,217.0,128.0, 62.0, 43.0, 36.0 %@AS@% }; %@AS@% char far *category[MONTHS] = %@AS@% { %@AS@% "Jan", "Feb", "Mar", "Apr", %@AS@% "May", "Jun", "Jly", "Aug", %@AS@% "Sep", "Oct", "Nov", "Dec" %@AS@% }; %@AS@% %@AS@% main() %@AS@% { %@AS@% chartenv env; %@AS@% int mode = _VRES16COLOR; %@AS@% /* Set highest video mode available */ %@AS@% while(!_setvideomode( mode )) %@AS@% mode--; %@AS@% if(mode == _TEXTMONO) %@AS@% return(0); %@AS@% %@AS@% /* Initialize chart library and a default bar chart */ %@AS@% _pg_initchart(); %@AS@% _pg_defaultchart( &env, _PG_BARCHART, _PG_PLAINBARS ); %@AS@% %@AS@% /* Add titles and some chart options */ %@AS@% strcpy( env.maintitle.title, "Good Neighbor Grocery" ); %@AS@% env.maintitle.titlecolor = 6; %@AS@% env.maintitle.justify = _PG_RIGHT; %@AS@% strcpy( env.subtitle.title, "Orange Juice Sales" ); %@AS@% env.subtitle.titlecolor = 6; %@AS@% env.subtitle.justify = _PG_RIGHT; %@AS@% strcpy( env.yaxis.axistitle.title, "Months" ); %@AS@% strcpy( env.xaxis.axistitle.title, "Quantity (cases)" ); %@AS@% env.chartwindow.border = FALSE; %@AS@% %@AS@% /* Parameters for call to _pg_chart are: %@AS@% * env - Environment variable %@AS@% * category - Category labels %@AS@% * value - Data to chart %@AS@% * MONTHS - Number of data values */ %@AS@% if(_pg_chart( &env, category, value, MONTHS )) %@AS@% { %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% _outtext( "Error: can't draw chart" ); %@AS@% } %@AS@% else %@AS@% { %@AS@% getch(); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% } %@AS@% return(0); %@AS@% }%@AE@%%@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Example: Column Chart%@AE@%%@EH@%%@NL@% %@NL@% The grocer's bar chart becomes a column chart in two easy steps. Simply specify the new chart type when calling %@AB@%_pg_defaultchart%@AE@% and switch the axis titles. To produce a column chart for the data, replace the call to%@AB@% %@AB@%_pg_defaultchart%@AE@% with: %@NL@% %@NL@% %@AS@% _pg_defaultchart( &env, _PG_COLUMNCHART, _PG_PLAINBARS );%@AE@%%@NL@% %@NL@% and replace the last two calls to %@AB@%strcpy%@AE@% with: %@NL@% %@NL@% %@AS@% strcpy( env.xaxis.axistitle.title, "Months" ); %@AS@% strcpy( env.yaxis.axistitle.title, "Quantity (cases)" );%@AE@%%@NL@% %@NL@% Notice that now the %@AI@%x%@AE@% axis is labeled "Months" and the %@AI@%y %@AE@%axis is labeled "Quantity (cases)." Figure 14.4 shows the resulting column chart. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Example: Line Chart%@AE@%%@EH@%%@NL@% %@NL@% Creating an equivalent line chart requires only one change. Use the same code as for the column chart and replace the call to %@AB@%_pg_defaultchart%@AE@% with: %@NL@% %@NL@% %@AS@% _pg_defaultchart( &env, _PG_LINECHART, _PG_POINTANDLINE );%@AE@%%@NL@% %@NL@% Figure 14.5 shows the line chart for the grocer's data. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Example: Scatter Diagram%@AE@%%@EH@%%@NL@% %@NL@% Now suppose that the store owner wants to compare the sales of orange juice to the sales of another product, say hot chocolate. Possible monthly sales are shown below. %@NL@% %@NL@% %@TH: 15 729 02 12 22 42 @%Months Orange Juice (cases) Hot Chocolate (cases)%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%January 33 37February 27 37March 42 30April 64 19May 106 10June 157 5July 182 2August 217 1September 128 7%@AB@%%@AE@%October 62 15November 43 28December 36 39%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 15 729 02 12 22 42 @% The program SCATTER.C displays a scatter diagram that illustrates the relationship between the sales of orange juice and hot chocolate throughout a 12-month period. %@NL@% %@NL@% %@AS@% /* SCATTER.C: Create sample scatter diagram. */ %@AS@% %@AS@% #include <conio.h> %@AS@% #include <string.h> %@AS@% #include <graph.h> %@AS@% #include <pgchart.h> %@AS@% %@AS@% #define MONTHS 12 %@AS@% typedef enum {FALSE, TRUE} boolean; %@AS@% %@AS@% /* Orange juice sales */ %@AS@% %@AS@% float far xvalue[MONTHS] = %@AS@% { %@AS@% 33.0, 27.0, 42.0, 64.0,106.0,157.0, %@AS@% 182.0,217.0,128.0, 62.0, 43.0, 36.0 %@AS@% }; %@AS@% /* Hot chocolate sales */ %@AS@% %@AS@% float far yvalue[MONTHS] = %@AS@% { %@AS@% 37.0, 37.0, 30.0, 19.0, 10.0, 5.0, %@AS@% 2.0, 1.0, 7.0, 15.0, 28.0, 39.0 %@AS@% }; %@AS@% %@AS@% main() %@AS@% { %@AS@% chartenv env; %@AS@% int mode = _VRES16COLOR; %@AS@% %@AS@% /* Set highest video mode available */ %@AS@% %@AS@% while(!_setvideomode( mode )) %@AS@% mode--; %@AS@% if(mode == _TEXTMONO) %@AS@% return(0);%@AE@%%@NL@% %@NL@% %@AS@% /* Initialize chart library and default %@AS@% * scatter diagram %@AS@% */ %@AS@% _pg_initchart(); %@AS@% _pg_defaultchart( &env, _PG_SCATTERCHART, %@AS@% _PG_POINTONLY ); %@AS@% %@AS@% /* Add titles and some chart options */ %@AS@% %@AS@% strcpy( env.maintitle.title, "Good Neighbor Grocery" ); %@AS@% env.maintitle.titlecolor = 6; %@AS@% env.maintitle.justify = _PG_RIGHT; %@AS@% strcpy( env.subtitle.title, %@AS@% "Orange Juice vs Hot Chocolate" ); %@AS@% env.subtitle.titlecolor = 6; %@AS@% env.subtitle.justify = _PG_RIGHT; %@AS@% env.yaxis.grid = TRUE; %@AS@% strcpy( env.xaxis.axistitle.title, %@AS@% "Orange Juice Sales" ); %@AS@% strcpy( env.yaxis.axistitle.title, %@AS@% "Hot Chocolate Sales" ); %@AS@% env.chartwindow.border = FALSE; %@AS@% %@AS@% /* Parameters for call to _pg_chartscatter are: %@AS@% * env - Environment variable %@AS@% * xvalue - X-axis data %@AS@% * yvalue - Y-axis data %@AS@% * MONTHS - Number of data values %@AS@% */%@AE@%%@NL@% %@NL@% %@AS@% if(_pg_chartscatter( &env, xvalue, %@AS@% yvalue, MONTHS )) %@AS@% { %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% _outtext( "Error: can't draw chart" ); %@AS@% } %@AS@% else %@AS@% { %@AS@% getch(); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% } %@AS@% return(0); %@AS@% } %@AE@%%@NL@% %@NL@% Figure 14.6 shows the results of SCATTER.C. Notice that the scatter points form a slightly curved line, indicating a correlation exists between the sales of the two products. The store owner can conclude from the scatter diagram that the demand for orange juice is roughly inverse to the demand for hot chocolate. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00140005 @%%@AB@%Palettes%@AE@%%@EH@%%@NL@% %@NL@% Presentation Graphics displays each data series in a way that makes it discernible from other series. It does this by defining a separate "palette" for every data series in a chart. Palettes consist of entries that determine color, line style, fill pattern, and plot character used to graph the series. %@NL@% %@NL@% Presentation Graphics maintains its palettes as an array of structures. The header file PGCHART.H defines the palette structures as: %@NL@% %@NL@% %@AS@% /* Typedef for pattern bitmap */ %@AS@% typedef unsigned char fillmap[8]; %@AS@% %@AS@% /* Typedef for palette entry definition */ %@AS@% typedef struct %@AS@% { %@AS@% unsigned short color; %@AS@% unsigned short style; %@AS@% fillmap fill; %@AS@% char plotchar; %@AS@% } paletteentry; %@AS@% %@AS@% /* Typedef for palette definition */ %@AS@% typedef paletteentry palettetype[_PG_PALETTELEN];%@AE@%%@NL@% %@NL@% It's important not to confuse the Presentation Graphics palettes with the adapter display palettes, which are register values kept by the video controller. The function %@AB@%_selectpalette%@AE@% described in Chapter 13, "Graphics," sets the display palette. It does not define the data series palettes used by Presentation Graphics. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140006 @%%@AB@%Color Pool%@AE@%%@EH@%%@NL@% %@NL@% Presentation Graphics organizes all chart colors into a "color pool." The color pool consists of pixel values valid for the current graphics mode. (Refer to Chapter 13, "Graphics," or the Glossary for a definition of pixel values.) Palette structures contain color codes that refer to the color pool. A palette's color code determines the color used to graph the data series associated with the palette. Colors of labels, titles, legends, and axes are also determined by the contents of the color pool. %@NL@% %@NL@% The first element of the color pool is always 0, which is the pixel value for the screen background color. The second element is always the highest pixel value available for the graphics mode. The remaining elements are repeating sequences of available pixel values, beginning with 1. %@NL@% %@NL@% As shown above, the first member of a palette data structure is: %@NL@% %@NL@% %@AS@% unsigned short color;%@AE@%%@NL@% %@NL@% This variable defines the color code for the data series associated with the palette. The color code is neither a display attribute nor a pixel value. It is an index number of the color pool. %@NL@% %@NL@% An example should make this clearer. A graphics mode of %@AB@%_MRES4COLOR%@AE@% (320 x 200 graphics) provides four colors for display. Pixel values from 0 to 3 determine the possible pixel colors─say, black, green, red, and brown respectively. In this case the first 8 elements of the color pool would be the following: %@NL@% %@NL@% %@TH: 11 550 02 18 13 45 @%Color Pool Index Pixel Value Color%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%0 0 Black1 3 Brown2 1 Green3 2 Red4 3 Brown5 1 Green6 2 Red7 3 Brown%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 11 550 02 18 13 45 @% Notice that the sequence of available foreground colors repeats from the third element. The first data series in this case would be plotted in brown, the second series in green, the third series in red, the fourth series again in brown, and so forth. %@NL@% %@NL@% Video adapters such as the EGA or the Hercules InColor(tm) Card allow 16 on-screen colors. This allows Presentation Graphics to graph more series without duplicating colors. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140007 @%%@AB@%Style Pool%@AE@%%@EH@%%@NL@% %@NL@% Presentation Graphics matches the color pool with a collection of different line styles called the "style pool." Entries in the style pool define the appearance of lines such as axes and grids. Lines can be solid, dotted, dashed, or of some combination. %@NL@% %@NL@% The second member of a palette structure defines a style code as: %@NL@% %@NL@% %@AS@% unsigned short style;%@AE@%%@NL@% %@NL@% Each palette contains a style code that refers to an entry in the style pool in the same way that it contains a color code that refers to an entry in the color pool. The style code value in a palette is applicable only to line graphs and lined scatter diagrams. The style code determines the appearance of the lines drawn between points. %@NL@% %@NL@% The palette's style code adds further variety to the lines of a multiseries graph. It is most useful when the number of lines in a chart exceeds the number of available colors. For example, a graph of nine different data series must repeat colors if only three foreground colors are available for display. However, the style code for each color repetition will be different, ensuring that none of the lines looks the same. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140008 @%%@AB@%Pattern Pool%@AE@%%@EH@%%@NL@% %@NL@% Presentation Graphics also maintains a pool of "fill patterns." Patterns determine the fill design for column, bar, and pie charts. The third member of a palette structure holds the palette's fill pattern. The pattern member is an array: %@NL@% %@NL@% %@AS@% fillmap fill;%@AE@%%@NL@% %@NL@% where %@AS@% fillmap %@AE@% is type-defined as: %@NL@% %@NL@% %@AS@% typedef unsigned char fillmap[8];%@AE@%%@NL@% %@NL@% Each fill pattern array holds an 8 x 8 bit map that defines the fill pattern for the data series associated with the palette. Table 14.2 shows how a fill pattern of diagonal stripes is created with the %@AS@% fill %@AE@% pattern array. %@NL@% %@NL@% The bit map below corresponds to screen pixels. Each of the 8 layers of the map are binary numbers, where a solid circle signifies 1 and an open circle signifies 0. Thus the first layer of the map─that is, the first byte─represents the binary number 10011001, which is the decimal number 153. %@NL@% %@NL@% %@AB@%Table 14.2 %@AB@%Fill Patterns%@AE@%%@AE@% %@TH: 11 765 02 35 41 @%Bit Map Value in fill%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% ∙ ∙ ∙ ∙ %@AS@% fill[0]%@AE@% = 153 ∙ ∙ ∙ ∙ %@AS@% fill[1]%@AE@% = 204∙ ∙ ∙ ∙ %@AS@% fill[2]%@AE@% = 102∙ ∙ ∙ ∙ %@AS@% fill[3]%@AE@% = 51 ∙ ∙ ∙ ∙ %@AS@% fill[4]%@AE@% = 153 ∙ ∙ ∙ ∙ %@AS@% fill[5]%@AE@% = 204∙ ∙ ∙ ∙ %@AS@% fill[6]%@AE@% = 102∙ ∙ ∙ ∙ %@AS@% fill[7]%@AE@% = 51%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 11 765 02 35 41 @% If you wish to create the above pattern for your chart's first data series, you must reset the %@AS@% fill %@AE@% array for the first palette structure. You can do this in five steps: %@NL@% %@NL@% %@NL@% 1. Declare a structure of type %@AB@%palettetype%@AE@% to hold the palette parameters.%@NL@% %@NL@% 2. Call %@AB@%_pg_initchart%@AE@% to initialize the palettes with default values.%@NL@% %@NL@% 3. Call the Presentation Graphics function %@AB@%_pg_getpalette%@AE@% to retrieve a copy of the current palette data.%@NL@% %@NL@% 4. Assign the values given in Table 14.2 to the array %@AS@% fill %@AE@% for the first palette. %@NL@% %@NL@% 5. Call the Presentation Graphics function %@AB@%_pg_setpalette%@AE@% to load the modified palette values.%@NL@% %@NL@% %@NL@% The following lines of code demonstrate these five steps: %@NL@% %@NL@% %@AS@% /* Declare a structure array for palette data. */ %@AS@% %@AS@% palettetype palette_struct; %@AS@% . %@AS@% . %@AS@% . %@AS@% /* Initialize chart library */ %@AS@% %@AS@% _pg_initchart(); %@AS@% . %@AS@% . %@AS@% . %@AS@% /* Copy current palette data into palette_struct */ %@AS@% %@AS@% _pg_getpalette( palette_struct ); %@AS@% %@AS@% /* Reinitialize fill pattern for first palette using %@AS@% values in Table 14.2 */ %@AS@% %@AS@% palette_struct[1].fill[0] = 153; %@AS@% palette_struct[1].fill[1] = 204; %@AS@% palette_struct[1].fill[2] = 102; %@AS@% palette_struct[1].fill[3] = 51; %@AS@% palette_struct[1].fill[4] = 153; %@AS@% palette_struct[1].fill[5] = 204; %@AS@% palette_struct[1].fill[6] = 102; %@AS@% palette_struct[1].fill[7] = 51; %@AS@% %@AS@% /* Load new palette data */ %@AS@% %@AS@% _pg_setpalette( palette_struct );%@AE@%%@NL@% %@NL@% Now when you display your bar or column chart the first series appears filled with the striped pattern shown in Table 14.2. %@NL@% %@NL@% Pie charts are a bit different. The idea of multiple series does not really apply to them. Instead, palette structures correspond to individual slices. If the number of slices exceeds the constant %@AB@%_PG_PALETTELEN%@AE@%, palettes are recycled. Thus the first palette dictates not only the appearance of the first slice, but of slice number %@AB@%_PG_PALETTELEN%@AE@% as well. The second palette determines the appearance of both the second slice and of slice number %@AB@%_PG_PALETTELEN%@AE@% + 1, and so forth. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140009 @%%@AB@%Character Pool%@AE@%%@EH@%%@NL@% %@NL@% The last member of a palette structure is an index number in a pool of ASCII characters: %@NL@% %@NL@% %@AS@% char plotchar;%@AE@%%@NL@% %@NL@% The member %@AS@%plotchar %@AE@% represents plot points on line graphs and scatter diagrams. Each palette uses a different character to distinguish plot points between data series. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00140010 @%%@AB@%Customizing Presentation Graphics%@AE@%%@EH@%%@NL@% %@NL@% Presentation Graphics is built for flexibility. You can use its system of default values to produce professional-looking charts with a minimum of programming effort. Or you can fine-tune the appearance of your charts by overriding default values and initializing variables explicitly in your program. The following section shows you how. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140011 @%%@AB@%Chart Environment%@AE@%%@EH@%%@NL@% %@NL@% The header file PGCHART.H defines a structure type %@AB@%chartenv%@AE@%. This structure type organizes the set of variables known as the "chart environment." The chart environment describes everything about a chart except the plots themselves. It's the blank page, in other words, ready for plotting data. The environment determines the appearance of text, axes, grid lines, and legends. %@NL@% %@NL@% Calling the %@AB@%_pg_defaultchart%@AE@% function fills the chart environment with default values. Presentation Graphics allows you to reset any variable in the environment before displaying a chart. Except for adjusting the palette values, all initialization of data is done through a %@AB@%chartenv%@AE@% type structure. %@NL@% %@NL@% The sample chart programs provided earlier illustrate how to adjust variables in the chart environment. These programs create a structure %@AS@% env %@AE@% of the type %@AB@%chartenv%@AE@%. The structure %@AS@% env %@AE@% contains the chart environment variables, initialized by the call to %@AB@%_pg_defaultchart%@AE@%. Environment variables such as the chart title are then given specific values, as in: %@NL@% %@NL@% %@AS@% strcpy( env.maintitle.title, "Good Neighbor Grocery" );%@AE@%%@NL@% %@NL@% Environment variables that determine colors and line styles deserve special mention. The chart environment holds several such variables, which can be recognized by their names. For example, the variable %@AI@%titlecolor%@AE@% specifies the color of title text. Similarly, the variable %@AI@%gridstyle%@AE@% specifies the line style used to draw the chart grid. %@NL@% %@NL@% %@AU@% Colors and line styles in the chart environment are taken from palettes.%@AE@% %@NL@% %@NL@% These variables are index numbers, but do not refer directly to the color pool or line pool. They correspond instead to palette numbers. If you set %@AI@%titlecolor%@AE@% to 2, Presentation Graphics uses the color code in the second palette to determine the title's color. Thus the title in this case would be the same color as the chart's second data series. If you change the color code in the palette, you'll also change the title's color. %@NL@% %@NL@% A structure of type %@AB@%chartenv%@AE@% consists of four secondary structures. The file PGCHART.H type-defines the secondary structures as: %@NL@% %@NL@% %@AS@% titletype %@AS@% axistype %@AS@% windowtype %@AS@% legendtype%@AE@%%@NL@% %@NL@% The remainder of this section describes the chart environment of Presentation Graphics. It first examines structures of the four secondary types that make up the chart environment structure. The section concludes with a description of the %@AB@%chartenv%@AE@% structure type. Each discussion begins with a brief explanation of the structure's purpose, followed by a listing of the structure type definition as it appears in the PGCHART.H file. All symbolic constants are defined in the file PGCHART.H. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00140012 @%%@AB@%titletype%@AE@%%@EH@%%@NL@% %@NL@% Structures of type %@AB@%titletype%@AE@% determine text, color, and placement of titles appearing in the graph. The PGCHART.H file defines the structure type as: %@NL@% %@NL@% %@AS@% typedef struct %@AS@% { %@AS@% char title[_PG_TITLELEN]; /* Title text */ %@AS@% short titlecolor; /* Palette color %@AS@% for title text */ %@AS@% short justify; /* _PG_LEFT, _PG_CENTER, %@AS@% _PG_RIGHT */ %@AS@% } titletype;%@AE@%%@NL@% %@NL@% The following list describes %@AB@%titletype%@AE@% members: %@NL@% %@NL@% %@AB@%Member Variable%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AI@%justify%@AE@% An integer specifying how the title is justified within the chart window. The symbolic constants defined in the PGCHART.H file for this variable are %@AB@%_PG_LEFT%@AE@%, %@AB@%_PG_CENTER%@AE@%, and %@AB@%%@AE@% %@AB@%_PG_RIGHT%@AE@%. %@AI@%titlecolor%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies a title's color. The default value for %@AI@%titlecolor%@AE@% is 1. %@AI@%title%@AE@%%@AB@%[_PG_TITLELEN]%@AE@% A character array containing title text. For example, if %@AS@% env %@AE@% is a structure of type%@AB@% chartenv%@AE@%, then %@AS@% env.maintitle.title%@AE@% holds the character string used for the main title of the chart. Similarly, %@AS@%%@AE@% %@AS@%env.xaxis.axistitle.title%@AE@% contains the axis title. The number of characters in a title must be one less than %@AB@%%@AE@% %@AB@%_PG_TITLELEN%@AE@% to allow room for a null terminator. %@NL@% %@3@%%@CR:C6A00140013 @%%@AB@%axistype%@AE@%%@EH@%%@NL@% %@NL@% Structures of type %@AB@%axistype%@AE@% contain variables for the axes such as color, scale, grid style, and tick marks. The PGCHART.H file defines the structure type as: %@NL@% %@NL@% %@AS@% typedef struct %@AS@% { %@AS@% short grid; /* TRUE=grid lines drawn; %@AS@% FALSE=no lines */ %@AS@% short gridstyle; /* Style bytes for grid */ %@AS@% titletype axistitle; /* Title definition %@AS@% for axis */ %@AS@% short axiscolor; /* Color for axis */ %@AS@% short labeled; /* TRUE=ticks marks and titles %@AS@% drawn */ %@AS@% short rangetype; /* _PG_LINEARAXIS, %@AS@% _PG_LOGAXIS */ %@AS@% float logbase; /* Base used if log axis */ %@AS@% short autoscale; /* TRUE=next 7 values %@AS@% calculated by system */ %@AS@% float scalemin; /* Minimum value of scale */ %@AS@% float scalemax; /* Maximum value of scale */ %@AS@% float scalefactor; /* Scale factor for data on %@AS@% this axis */ %@AS@% titletype scaletitle; /* Title definition for %@AS@% scaling factor */ %@AS@% float ticinterval; /* Distance between tick marks %@AS@% (world coord.) */ %@AS@% short ticformat; /* _PG_EXPFORMAT or %@AS@% _PG_DECFORMAT */ %@AS@% short ticdecimals; /* Number of decimals for tick %@AS@% labels (max=9) */ %@AS@% } axistype;%@AE@%%@NL@% %@NL@% The following list describes %@AB@%axistype%@AE@% member variables: %@NL@% %@NL@% %@AB@%Member Variable%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AI@%autoscale%@AE@% A boolean variable. If %@AI@%autoscale%@AE@% is %@AB@%TRUE%@AE@%, Presentation Graphics automatically determines values for %@AI@% scalefactor%@AE@%, %@AI@%scalemax%@AE@%, %@AI@%scalemin%@AE@%, %@AI@%%@AE@% %@AI@%scaletitle%@AE@%, %@AI@%ticdecimals%@AE@%, %@AI@%ticformat%@AE@%, and %@AI@%%@AE@% %@AI@%ticinterval%@AE@% (see below). If %@AI@%autoscale%@AE@% equals %@AB@%FALSE%@AE@%, these seven variables must be specified in your program. %@AI@%axiscolor%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies the color used for the axis and parallel grid lines. (See description for %@AI@%gridstyle%@AE@% above.) Note that this member does not determine the color of the axis title. That selection is made through the structure %@AI@%%@AE@% %@AI@%axistitle%@AE@%. %@AI@%axistitle%@AE@% A%@AB@% titletype%@AE@% structure that defines the title of the associated axis. The title of the %@AI@%y%@AE@% axis displays vertically to the left of the %@AI@%y%@AE@% axis, and the title of the %@AI@%x%@AE@% axis displays horizontally below the %@AI@%x%@AE@% axis. %@AI@%grid%@AE@% A boolean true/false value that determines whether grid lines are drawn for the associated axis. Grid lines span the data window perpendicular to the axis. %@AI@%gridstyle%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies the grid's line style. Lines can be solid, dashed, dotted, or some combination. The default value for %@AI@%%@AE@% %@AI@%gridstyle%@AE@% is 1. Note that the color of the parallel axis determines the color of the grid lines. Thus the %@AI@%x%@AE@% axis grid is the same color as the %@AI@%y%@AE@% axis, and the %@AI@%y%@AE@% axis grid is the same color as the %@AI@%x%@AE@% axis. %@AI@%labeled%@AE@% A boolean value that determines whether tick marks and labels are drawn on the axis. Axis labels should not be confused with axis titles. Axis labels are numbers or descriptions such as "23.2" or "January" attached to each tick mark. %@AI@%logbase%@AE@% If %@AI@%rangetype%@AE@% is logarithmic, the %@AI@%logbase%@AE@% variable determines the log base used to scale the axis. Default value is 10. %@AI@%rangetype%@AE@% An integer that determines whether the scale of the axis is linear or logarithmic. The %@AI@%rangetype%@AE@% variable applies only to value data. Specify a linear scale with the %@AB@%%@AE@% %@AB@%_PG_LINEARAXIS%@AE@% constant. A linear scale is best when the difference between axis minimum and maximum is relatively small. For example, a linear axis range 0-10 results in 10 tick marks evenly spaced along the axis. Use %@AB@%_PG_LOGAXIS%@AE@% to specify a logarithmic %@AI@%rangetype%@AE@%. Logarithmic scales are useful when the range is very large or when the data varies exponentially. Line graphs of exponentially varying data can be made straight with a logarithmic %@AI@%%@AE@% %@AI@%rangetype%@AE@%. %@AI@%scalefactor%@AE@% All numeric data are scaled by dividing each value by %@AI@%scalefactor%@AE@%. For relatively small values, the variable %@AI@%%@AE@% %@AI@%scalefactor%@AE@% should be 1, which is the default. But data with large values should be scaled by an appropriate factor. For example, data in the range 2 million-20 million should be plotted with %@AI@%scale-min%@AE@% set to 2, %@AI@%scalemax%@AE@% set to 20, and %@AI@%scalefactor%@AE@% set to 1 million. If %@AI@%autoscale%@AE@% is set to %@AB@%TRUE%@AE@%, Presentation Graphics automatically determines a suitable value for %@AI@%%@AE@% %@AI@%scalefactor%@AE@% based on the range of data to be plotted. Presentation Graphics selects only values that are a factor of 1 thousand─that is, values such as 1 thousand, 1 million, or 1 billion. It then labels the %@AI@%scaletitle%@AE@% appropriately (see below). If you desire some other value for scaling, you must set %@AI@%%@AE@% %@AI@%autoscale%@AE@% to %@AB@%FALSE%@AE@% and set %@AI@%scalefactor%@AE@% to the desired scaling value. %@AI@%scalemax%@AE@% Highest value represented by the axis. %@AI@%scalemin%@AE@% Lowest value represented by the axis. %@AI@%scaletitle%@AE@% A %@AB@%titletype%@AE@% structure defining a string of text that describes the value of %@AI@%scalefactor%@AE@%. If %@AI@%%@AE@% %@AI@%autoscale%@AE@% is %@AB@%TRUE%@AE@%, Presentation Graphics automatically writes a scale description to %@AI@%scaletitle%@AE@%. If%@AI@% %@AE@% %@AI@%autoscale%@AE@% equals %@AB@%FALSE%@AE@% and %@AI@%scalefactor%@AE@% is 1, %@AI@%scaletitle.title%@AE@% should be blank. Otherwise your program should copy an appropriate scale description to %@AI@%%@AE@% %@AI@%scaletitle.title%@AE@%, such as "( x 1000)," "(in millions of units)," "times 10 thousand dollars," etc. For the %@AI@%y%@AE@% axis, the %@AI@%scaletitle%@AE@% text displays vertically between the axis title and the %@AI@%y%@AE@% axis. For the %@AI@%x %@AE@%axis,%@AI@% %@AE@% the scale title appears below the%@AI@% x%@AE@% axis title. %@AI@%ticdecimals%@AE@% Number of digits to display after the decimal point in tick labels. Maximum value is 9. Note that this variable applies only to axes with value data. It is ignored for the category axis. %@AI@%ticformat%@AE@% An integer that determines the format of the labels assigned to each tick mark. Set %@AI@%ticformat%@AE@% to %@AB@%_PG_EXPFORMAT%@AE@% for exponential format or set it to %@AB@%%@AE@% %@AB@%_PG_DECFORMAT%@AE@% for decimal. The default is %@AB@%_PG_DECFORMAT%@AE@%. Note that this variable applies only to axes with value data. It is ignored for the category axis. %@AI@%ticinterval%@AE@% Sets interval between tick marks on the axis. The tick interval is measured in the same units as the numeric data associated with the axis. For example, if 2 sequential tick marks correspond to the values 20 and 25, the tick interval between them is 5. Note that this variable applies only to axes with value data. It is ignored for the category axis. %@NL@% %@3@%%@CR:C6A00140014 @%%@AB@%windowtype%@AE@%%@EH@%%@NL@% %@NL@% Structures of type %@AB@%windowtype%@AE@% contain sizes, locations, and color codes for the three windows produced by Presentation Graphics: the chart window, the data window, and the legend. Refer to the "Terminology" section at the beginning of this chapter for definitions of these terms. Windows are located on the screen relative to the screen's logical origin. By changing the logical origin, you can display charts that are partly or completely off the screen. The PGCHART.H file defines %@AB@%windowtype%@AE@% as: %@NL@% %@NL@% %@AS@% typedef struct %@AS@% { %@AS@% short x1; /* Left edge of window in %@AS@% pixels */ %@AS@% short y1; /* Top edge of window in %@AS@% pixels */ %@AS@% short x2; /* Right edge of window in %@AS@% pixels */ %@AS@% short y2; /* Bottom edge of window in %@AS@% pixels */ %@AS@% short border; /* TRUE for border, FALSE %@AS@% otherwise */ %@AS@% short background; /* Internal palette color for %@AS@% window background */ %@AS@% short borderstyle; /* Style bytes for window %@AS@% border */ %@AS@% short bordercolor; /* Internal palette color for %@AS@% window border */ %@AS@% } windowtype;%@AE@%%@NL@% %@NL@% The following list describes %@AB@%windowtype%@AE@% member variables: %@NL@% %@NL@% %@AB@%Member Variable%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AI@%x1%@AE@%, %@AI@%y1%@AE@%, %@AI@%x2%@AE@%, %@AI@%y2%@AE@% Window coordinates in pixels. The ordered pair (%@AI@%x1%@AE@%, %@AI@%y1%@AE@%) specifies the coordinate of the upper left corner of the window. The ordered pair (%@AI@%x2%@AE@%, %@AI@%y2%@AE@%) specifies the coordinate of the lower right corner. The reference point for the coordinates depends on the type of window. The chart window is located relative to the logical origin, usually the upper left corner of the screen. The data and legend windows are located relative to the upper left corner of the chart window. This allows you to change the position of the chart window without having to redefine coordinates for the other two windows. %@AI@%background%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies the window's background color. The default value for %@AI@%background%@AE@% is 1. %@AI@%border%@AE@% A boolean variable that determines whether a border frame is drawn around a window. %@AI@%bordercolor%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies the color of the window's border frame. The default value is 1. %@AI@%borderstyle%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies the line style of the window's border frame. The default value is 1. %@NL@% %@3@%%@CR:C6A00140015 @%%@AB@%legendtype%@AE@%%@EH@%%@NL@% %@NL@% Structures of type %@AB@%legendtype%@AE@% contain size, location, and colors of the chart legend. The PGCHART.H file defines the structure type as: %@NL@% %@NL@% %@AS@% typedef struct %@AS@% { %@AS@% short legend; /* TRUE=draw legend; %@AS@% FALSE=no legend */ %@AS@% short place; /* _PG_RIGHT, _PG_BOTTOM, %@AS@% _PG_OVERLAY */ %@AS@% short textcolor; /* Palette color for text*/ %@AS@% short autosize; /* TRUE=system calculates %@AS@% legend size */ %@AS@% windowtypelegendwindow; /* Window definition for %@AS@% legend */ %@AS@% } legendtype;%@AE@%%@NL@% %@NL@% The following list describes %@AB@%legendtype%@AE@% member variables: %@NL@% %@NL@% %@AB@%Member Variable%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AI@%autosize%@AE@% A boolean true/false variable that determines whether Presentation Graphics is to automatically calculate the size of the legend. If %@AI@%autosize%@AE@% equals %@AB@%FALSE%@AE@%, the legend window must be specified in the %@AI@%legendwindow%@AE@% structure (see below). %@AI@%legend%@AE@% A boolean true/false variable that determines whether a legend is to appear on the chart. The %@AI@%legend%@AE@% variable is ignored by functions that graph single-series charts. %@AI@%legendwindow%@AE@% A %@AB@%windowtype%@AE@% structure that defines coordinates, background color, and border frame for the legend. Coordinates given in %@AI@%legendwindow%@AE@% are ignored if %@AI@%%@AE@% %@AI@%autosize%@AE@% is %@AB@%TRUE%@AE@%. %@AI@%place%@AE@% An integer that specifies the location of the legend relative to the data window. Setting the variable %@AI@%place%@AE@% equal to the constant %@AB@%_PG_RIGHT%@AE@% positions the legend to the right of the data window. Setting %@AI@%place%@AE@% to %@AB@%_PG_BOTTOM%@AE@% positions the legend below the data window. Setting %@AI@%place%@AE@% to %@AB@%_PG_OVERLAY%@AE@% positions the legend within the data window. These settings influence the size of the data window. If %@AI@%place%@AE@% is equal to %@AB@%_PG_BOTTOM%@AE@% or %@AB@%_PG_RIGHT%@AE@%, Presentation Graphics automatically sizes the data window to accommodate the legend. If %@AI@%place%@AE@% equals %@AB@%_PG_OVERLAY%@AE@% the data window is sized without regard to the legend. %@AI@%textcolor%@AE@% An integer between 1 and %@AB@%_PG_PALETTELEN%@AE@% that specifies the color of text within the legend window. %@NL@% %@3@%%@CR:C6A00140016 @%%@AB@%chartenv%@AE@%%@EH@%%@NL@% %@NL@% A structure of type%@AB@% chartenv%@AE@% defines the chart environment. The following code shows that a %@AB@%chartenv%@AE@% type structure consists almost entirely of structures of the four types discussed above. %@NL@% %@NL@% The PGCHART.H file defines the %@AB@%chartenv%@AE@% structure type as: %@NL@% %@NL@% %@AS@% typedef struct %@AS@% { %@AS@% short charttype; /* Chart type */ %@AS@% short chartstyle; /* Chart style */ %@AS@% windowtype chartwindow; /* Window definition for %@AS@% overall chart */ %@AS@% windowtype datawindow; /* Window definition for data %@AS@% part of chart */ %@AS@% titletype maintitle; /* Main chart title */ %@AS@% titletype subtitle; /* Chart subtitle */ %@AS@% axistype xaxis; /* Definition for x axis */ %@AS@% axistype yaxis; /* Definition for y axis */ %@AS@% legendtype legend; /* Definition for legend */ %@AS@% } chartenv;%@AE@%%@NL@% %@NL@% %@AU@% Initialize the chart environment with the _pg_defaultchart function.%@AE@% %@NL@% %@NL@% Note that all the data in a %@AB@%chartenv%@AE@% type structure is initialized by calling the %@AB@%_pg_defaultchart%@AE@% function. If your program does not call %@AB@%_pg_defaultchart%@AE@%, it must explicitly define every variable in the chart environment─a tedious and unnecessary procedure. The recommended method for adjusting the appearance of your chart is to initialize variables for the proper chart type by calling the %@AB@%_pg_defaultchart%@AE@% function, and then reassign selected environment variables such as titles. %@NL@% %@NL@% The following list describes %@AB@%chartenv%@AE@% member variables: %@NL@% %@NL@% %@AB@%Member Variable%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AI@%chartstyle%@AE@% An integer that determines the style of the chart (see Table 14.1). Legal values for %@AI@%%@AE@% %@AI@%chartstyle%@AE@% are %@AB@%_PG_PERCENT%@AE@% and %@AB@%_PG_NOPERCENT%@AE@% for pie charts; %@AB@%_PG_STACKEDBARS%@AE@% and %@AB@%%@AE@% %@AB@%_PG_PLAINBARS%@AE@% for bar and column charts; and %@AB@%_PG_POINTANDLINE%@AE@% and %@AB@%_PG_POINTONLY%@AE@% for line graphs and scatter diagrams. This variable corresponds to the third argument for the %@AB@%_pg_defaultchart%@AE@% function. %@AI@%charttype%@AE@% An integer that determines the type of chart displayed. The value of the variable %@AI@%charttype%@AE@% is %@AB@%_PG_BARCHART%@AE@%, %@AB@%%@AE@% %@AB@%_PG_COLUMNCHART%@AE@%, %@AB@%_PG_LINECHART%@AE@%, %@AB@%%@AE@% %@AB@%_PG_SCATTERCHART%@AE@%, or %@AB@%_PG_PIECHART%@AE@%. This variable corresponds to the second argument for the %@AB@%_pg_defaultchart%@AE@% function. %@AI@%chartwindow%@AE@% A %@AB@%windowtype%@AE@% structure that defines the appearance of the chart window. %@AI@%datawindow%@AE@% A %@AB@%windowtype%@AE@% structure that defines the appearance of the data window. %@AI@%legend%@AE@% A %@AB@%legendtype%@AE@% structure that defines the appearance of the legend window. %@AI@%maintitle%@AE@% A %@AB@%titletype%@AE@% structure that defines the appearance of the main title of the chart. %@AI@%subtitle%@AE@% A %@AB@%titletype%@AE@% structure that defines the appearance of the chart's subtitle. %@AI@%xaxis%@AE@% An %@AB@%axistype%@AE@% structure that defines the appearance of the %@AI@%x%@AE@% axis. (This variable is not applicable for pie charts.) %@AI@%yaxis%@AE@% An %@AB@%axistype%@AE@% structure that defines the appearance of the %@AI@%y%@AE@% axis. (This variable is not applicable for pie charts.) %@NL@% %@2@%%@CR:C6A00140017 @%%@AB@%An Overview of the Presentation Graphics Functions%@AE@%%@EH@%%@NL@% %@NL@% The chapter concludes with a few words about the 22 functions that make up the Presentation Graphics library. They are listed in Table 14.3 for convenient reference. Refer to Appendix B, "C Library Guide," or online help for a description of the functions and their arguments. %@NL@% %@NL@% %@AB@%Table 14.3 %@AB@%Presentation Graphics Functions%@AE@%%@AE@% %@TH: 11 975 02 21 22 33 @%Primary Functions Secondary Functions%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%_pg_initchart%@AE@% %@AB@%_pg_hlabelchart%@AE@% %@AB@%_pg_setpalette%@AE@%%@AB@%_pg_defaultchart%@AE@% %@AB@%_pg_vlabelchart%@AE@% %@AB@%_pg_resetpalette%@AE@%%@AB@%_pg_chart%@AE@% %@AB@%_pg_analyzechart%@AE@% %@AB@%_pg_getstyleset%@AE@%%@AB@%_pg_chartms%@AE@% %@AB@%_pg_analyzechartms%@AE@% %@AB@%_pg_setstyleset%@AE@%%@AB@%_pg_chartscatter%@AE@% %@AB@%_pg_analyzescatter%@AE@% %@AB@%_pg_resetstyleset%@AE@%%@AB@%_pg_chartscatterms%@AE@% %@AB@%_pg_analyzescatterms%@AE@% %@AB@%_pg_getchardef%@AE@%%@AB@%_pg_chartpie%@AE@% %@AB@%_pg_analyzepie%@AE@% %@AB@%_pg_setchardef%@AE@% %@AB@%_pg_getpalette%@AE@%%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 11 975 02 21 22 33 @% In most cases you need only be concerned with seven of the routines, called the "primary functions." These functions initialize variables and display the selected chart types. As demonstrated in example programs earlier in this chapter, you can create very acceptable charts with programs that call only three of the Presentation Graphics primary functions. %@NL@% %@NL@% The 15 secondary functions of Presentation Graphics do not directly display charts. Most of them retrieve or set data in the Presentation Graphics chart environment. %@NL@% %@NL@% Of special interest among the secondary functions are the "analysis functions," identified by the prefix %@AB@%_pg_analyze%@AE@% in their function names. These five functions calculate default values that pertain to a given chart type and data set. Calling an analysis function has the same effect as calling a corresponding primary function, except that the chart is not displayed. This allows you to pass on to the library the burden of calculating values. You can then make modifications to the resulting values and call a primary routine to display the chart. %@NL@% %@NL@% Use the %@AB@%_pg_hlabelchart%@AE@% and %@AB@%_pg_vlabelchart%@AE@% functions to display text on your chart that is not part of a title or axis label. These functions enable you to attach notes or other messages to your chart. You may also find them useful for labeling separate lines of a multiseries line graph. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00150001 @%%@1@%%@AB@%Chapter 15 Fonts%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% Preceding chapters have discussed how to write QuickC programs that generate graphics and display charts. QuickC has yet another capability when it comes to graphics: fonted text. Your programs can display various styles and sizes of text in any graphics image or chart. %@NL@% %@NL@% This chapter tells how. It assumes you have already read Chapter 13, "Graphics." You should understand such terms as "graphics mode" and "text mode," and be familiar with the functions %@AB@%_setvideomode%@AE@% and %@AB@%_moveto%@AE@%. Other than that, there's very little to it. Fonts are simple to learn and even simpler to use, yet they can add to your graphics a final touch of polish. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00150002 @%%@AB@%QuickC Fonts%@AE@%%@EH@%%@NL@% %@NL@% A "font" is a collection of stylized text characters. Each font consists of several type sizes and a typeface. %@NL@% %@NL@% "Typeface" is a printer's term that refers to the style of the displayed text─ Courier, for example, or Roman. The list on the following page shows six of the typefaces available with QuickC's font library. %@NL@% %@NL@% "Type size" measures the screen area occupied by individual characters. This term is also borrowed from the printer's lexicon, but for our purposes is specified in units of screen pixels. For example, "Courier 16 x 9" denotes text of Courier typeface, with each character occupying a screen area of 16 vertical pixels by 9 horizontal pixels. %@NL@% %@NL@% QuickC's font functions use two methods to create fonts. The first technique generates Courier, Helv, and Tms Rmn fonts through a "bit-mapping" (or "raster-mapping") technique. Bit-mapping defines character images with binary data. Each bit in the map corresponds to a screen pixel. If a bit is 1, its associated pixel is set to the current screen color. A bit value of 0 clears the pixel. Video adapters use this same technique to display text in graphics mode. %@NL@% %@NL@% The second method creates the remaining three type styles─Modern, Script, and Roman─as "vector-mapped" fonts. Vector-mapping represents each character in terms of lines and arcs. In a literal sense vector-mapped characters are drawn on the screen. You might think of bit-mapped characters as being stenciled. %@NL@% %@NL@% Each method has advantages and disadvantages. Bit-mapped characters are more completely formed since the pixel mapping is predetermined. However, they cannot be scaled. Vector-mapped text can be scaled to any size, but the characters tend to lack the solid appearance of the bit-mapped characters. %@NL@% %@NL@% %@AU@%(This figure may be found in the printed book.)%@AE@%%@NL@% %@NL@% Table 15.1 lists available sizes for each font. Notice that the bit-mapped fonts come in preset sizes as measured in pixels. The exact size of any fonted character depends on screen resolution and display type. %@NL@% %@NL@% %@AB@%Table 15.1 %@AB@%Typefaces and Type Sizes in the QuickC Library%@AE@%%@AE@% %@TH: 19 749 02 10 09 26 31 @%Typeface Mapping Size (in pixels) Spacing%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%Courier Bit 13 x 8, 16 x 9, Fixed 20 x 12 Helv Bit 13 x 5, 16 x 7, 20 x 8, Fixed 13 x 15, 16 x 6, 19 x 8 Tms Rmn Bit 10 x 5, 12 x 6, 15 x 8, Fixed 16 x 9, 20 x 12, 26 x 16 Modern Vector Scaled ProportionalScript Vector Scaled ProportionalRoman Vector Scaled Proportional%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 19 749 02 10 09 26 31 @% QuickC's font routines can display characters 32-255, including most extended characters (ASCII 128-255). A few extended characters cannot be displayed; these are represented as either an underscore (_) or period (.) character. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00150003 @%%@AB@%Using QuickC's Font Library%@AE@%%@EH@%%@NL@% %@NL@% Data for both bit-mapped and vector-mapped fonts reside in files on disk. A .FON extension identifies the files. The names of the .FON files indicate their content. For example, the files MODERN.FON, ROMAN.FON, and SCRIPT.FON hold data for the three vector-mapped fonts. %@NL@% %@NL@% %@AU@% You can use Microsoft Windows .FON files.%@AE@% %@NL@% %@NL@% QuickC .FON files are identical to the .FON files used in the Microsoft Windows operating environment. If you have access to Windows you can use any of its .FON files with QuickC's font functions. Windows .FON files are also available for purchase separately. In addition, several vendors offer software that can create or modify .FON files, allowing you to design your own fonts. %@NL@% %@NL@% Your programs should follow these three steps to display fonted text: %@NL@% %@NL@% %@NL@% 1. Register fonts%@NL@% %@NL@% 2. Set the current font from the register%@NL@% %@NL@% 3. Display text using the current font%@NL@% %@NL@% %@NL@% The following sections describe each of the three steps in detail. An example program later in the chapter demonstrates the steps. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00150004 @%%@AB@%Register Fonts%@AE@%%@EH@%%@NL@% %@NL@% The fonts you plan to use must first be organized into a list in memory, a process called "registering." The register list contains information about the available .FON files. Register fonts by calling the function %@AB@%_registerfonts%@AE@%. This function reads header information from specified .FON files. It builds a list of file information but does not read mapping data from the files. %@NL@% %@NL@% The GRAPH.H file prototypes the %@AB@%_registerfonts%@AE@% function as: %@NL@% %@NL@% %@AS@% short far _registerfonts( unsigned char far * );%@AE@%%@NL@% %@NL@% The argument points to a string containing a file name. The file name is the name of the .FON file for the desired font. The file name can include wild cards, allowing you to register several fonts with one call to %@AB@%_registerfonts%@AE@%. %@NL@% %@NL@% If it successfully reads one or more .FON files, %@AB@%_registerfonts%@AE@% returns the number of fonts registered. If the function fails, it returns a negative error code. Refer to Appendix B, "C Library Guide," or to online help for a description of error codes. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00150005 @%%@AB@%Set Current Font%@AE@%%@EH@%%@NL@% %@NL@% Call the function %@AB@%_setfont%@AE@% to select a current font. This function checks to see if the requested font is registered, then reads the mapping data from the appropriate .FON file. A font must be registered and marked current before your program can display text of that font. %@NL@% %@NL@% The GRAPH.H file prototypes %@AB@%_setfonts%@AE@% as %@NL@% %@NL@% %@AS@% short far _setfont( unsigned char far * );%@AE@%%@NL@% %@NL@% The function's argument is a pointer to a character string. The string consists of letter codes that describe the desired font, as outlined below: %@NL@% %@NL@% %@AB@%Option Code%@AE@% %@AB@%Meaning%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%b%@AE@% Select the best fit from the registered fonts. This option instructs %@AB@%_setfont%@AE@% to accept the closest-fitting font if a font of the specified size is not registered. If at least one font is registered, the %@AB@%%@AE@% %@AB@%b%@AE@% option always sets a current font. If you do not specify the %@AB@%b%@AE@% option and an exact matching font is not registered, %@AB@%%@AE@% %@AB@%_setfont%@AE@% will fail. In this case, any existing current font remains current. Refer to online help for a description of error codes returned by %@AB@%_setfont%@AE@%. The %@AB@%_setfont%@AE@% function uses four criteria for selecting the best fit. In descending order of precedence the four criteria are pixel height, typeface, pixel width, and spacing (fixed or proportional). If you request a vector-mapped font,%@AB@%_setfont%@AE@% sizes the font to correspond with the specified pixel height and width. If you request a raster-mapped (bit-mapped) font, %@AB@%%@AE@% %@AB@%_setfont%@AE@% chooses the closest available size. If the requested type size for a raster-mapped font fits exactly between two registered fonts, the smaller size takes precedence. %@AB@%f%@AE@% Select only a fixed-spaced font. %@AB@%h%@AE@%%@AI@%y%@AE@% Character height, where %@AI@%y%@AE@% is the height in pixels. %@AB@%n%@AE@%%@AI@%x%@AE@% Select font number %@AI@%x%@AE@%, where %@AI@%x%@AE@% is less than or equal to the value returned by %@AB@%%@AE@% %@AB@%_registerfonts%@AE@%. For example, the option %@AB@%%@AE@% %@AB@%n3%@AE@% makes the third registered font current, assuming that three or more fonts are registered. %@AB@%p%@AE@% Select only a proportional-spaced font. %@AB@%r%@AE@% Select only a raster-mapped (bit-mapped) font. %@AB@%t`%@AE@%%@AI@%fontname%@AE@%%@AB@%'%@AE@% Typeface of the font in single quotes. The %@AI@%fontname%@AE@% string is one of the following: courier modern helv script tms rmn roman Notice the space in "tms rmn." Additional font files use other names for %@AI@%fontname%@AE@%. Refer to the vendor's documentation for these names. %@AB@%v%@AE@% Select only a vector-mapped font. %@AB@%w%@AE@%%@AI@%x%@AE@% Character width, where %@AI@%x%@AE@% is the width in pixels. Option codes are not case-sensitive and can be listed in any order. You can separate codes with spaces or any other character that is not a valid option code. The %@AB@%_setfont%@AE@% function ignores all invalid codes. %@NL@% %@NL@% The %@AB@%_setfont%@AE@% function updates a data area with parameters of the current font. The data area is in the form of a structure, defined in the GRAPH.H file as %@NL@% %@NL@% %@AS@% struct _fontinfo %@AS@% { %@AS@% int type; /* set = vector,clear = bit map */ %@AS@% int ascent; /* pix dist from top to base */ %@AS@% int pixwidth; /* character width in pixels */ %@AS@% int pixheight; /* character height in pixels */ %@AS@% int avgwidth; /* average character width */ %@AS@% char filename[81]; /* file name including path */ %@AS@% char faceName[32]; /* font name */ %@AS@% };%@AE@%%@NL@% %@NL@% If you wish to retrieve the parameters of the current font, call the function %@AB@%_getfontinfo%@AE@%. Refer to Appendix B, "C Library Guide," or online help for a description of this function. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00150006 @%%@AB@%Display Text%@AE@%%@EH@%%@NL@% %@NL@% The last step consists of two parts. First, select a screen position for the text with the graphics function %@AB@%_moveto%@AE@%. Then display fonted text at that position with the function %@AB@%_outgtext%@AE@%. The %@AB@%_moveto%@AE@% function takes pixel coordinates as arguments. The coordinates locate the top left of the first character in the text string. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00150007 @%%@AB@%An Example Program%@AE@%%@EH@%%@NL@% %@NL@% QuickC's font functions shine when used in conjunction with your other graphics functions. They allow you to dress up any image on the screen. Yet they can make a visual impression when used by themselves, as an example will show. %@NL@% %@NL@% The program SAMPLER.C displays sample text in all the available fonts, then exits when a key is pressed. Make sure the .FON files are in the current directory before running the program. %@NL@% %@NL@% %@AS@% /* SAMPLER.C: Display sample text in various fonts. */ %@AS@% %@AS@% #include <stdio.h> %@AS@% #include <conio.h> %@AS@% #include <stdlib.h> %@AS@% #include <graph.h> %@AS@% #include <string.h>%@AE@%%@NL@% %@NL@% %@AS@% #define NFONTS 6 %@AS@% %@AS@% main() %@AS@% %@AS@% { %@AS@% static unsigned char *text[2*NFONTS] = %@AS@% { %@AS@% "COURIER", "courier", %@AS@% "HELV", "helv", %@AS@% "TMS RMN", "tms rmn", %@AS@% "MODERN", "modern", %@AS@% "SCRIPT", "script", %@AS@% "ROMAN", "roman" %@AS@% }; %@AS@% static unsigned char *face[NFONTS] = %@AS@% { %@AS@% "t'courier'", %@AS@% "t'helv'", %@AS@% "t'tms rmn'", %@AS@% "t'modern'", %@AS@% "t'script'", %@AS@% "t'roman'" %@AS@% }; %@AS@% static unsigned char list[20]; %@AS@% struct videoconfig vc; %@AS@% int mode = _VRES16COLOR; %@AS@% register i; %@AS@% %@AS@% /* Read header info from all .FON files in %@AS@% * current directory */ %@AS@% %@AS@% if(_registerfonts( "*.FON" )<0 ) %@AS@% { %@AS@% _outtext("Error: can't register fonts"); %@AS@% exit( 0 ); %@AS@% } %@AS@% %@AS@% /* Set highest available video mode */ %@AS@% %@AS@% while( !_setvideomode( mode ) ) %@AS@% mode--; %@AS@% if( mode == _TEXTMONO ) %@AS@% exit ( 0 ); %@AS@% %@AS@% /* Copy video configuration into structure vc */ %@AS@% %@AS@% _getvideoconfig( &vc );%@AE@%%@NL@% %@NL@% %@AS@% /* Display six lines of sample text */ %@AS@% %@AS@% for( i = 0; i<NFONTS; i++ ) %@AS@% { %@AS@% strcpy( list, face[i] ); %@AS@% strcat( list, "h30w24b" ); %@AS@% %@AS@% if( !_setfont( list ) ) %@AS@% { %@AS@% _setcolor( i + 1 ); %@AS@% _moveto( 0, (i * vc.numypixels) / NFONTS ); %@AS@% _outgtext( text[i * 2] ); %@AS@% _moveto( vc.numxpixels / 2, %@AS@% (i * vc.numypixels) / NFONTS ); %@AS@% _outgtext( text[(i * 2) + 1] ); %@AS@% } %@AS@% else %@AS@% { %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% _outtext( "Error: can't set font" ); %@AS@% exit( 0 ); %@AS@% } %@AS@% } %@AS@% getch(); %@AS@% _setvideomode( _DEFAULTMODE ); %@AS@% %@AS@% /* Return memory when finished with fonts */ %@AS@% %@AS@% _unregisterfonts(); %@AS@% exit ( 0 ); %@AS@% }%@AE@%%@NL@% %@NL@% Notice that SAMPLER.C calls the graphics function %@AB@%_moveto%@AE@% to establish the starting position for each text string. Chapter 13, "Graphics," describes the %@AB@%_moveto%@AE@% function in the section "Graphics Coordinates." The function %@AB@%_setfont%@AE@% takes a character string as an argument. The string is a list of options that specifies typeface and the best fit for a character height of 30 pixels, and a width of 24 pixels. See Appendix B, "C Library Guide," and online help for complete descriptions of the QuickC font functions. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00150008 @%%@AB@%A Few Hints%@AE@%%@EH@%%@NL@% %@NL@% Fonted text is simply another form of graphics, and using fonts effectively requires little programming effort. Still, there are a few things to watch: %@NL@% %@NL@% %@NL@% ■ Remember the video should be set only once to establish a graphics mode. If you generate an image─say, with Presentation Graphics─and wish to incorporate fonted text into it, don't reset the video mode prior to calling the font routines. Doing so will blank the screen, destroying the original image.%@NL@% %@NL@% ■ The %@AB@%_setfont%@AE@% function reads specified .FON files to obtain mapping data for the current font. Each call to %@AB@%_setfont%@AE@% causes a disk access and overwrites the old font data in memory. If you wish to show text of different styles on the same screen, display all text of one font before moving on to the others. By minimizing the number of calls to %@AB@%_setfont%@AE@% you'll save time spent in disk I/O and memory reloads. %@NL@% %@NL@% ■ When your program finishes with the fonts library, you might wish to free the memory occupied by the register list. Call the function %@AB@%_unregisterfonts%@AE@% to do this. As its name implies, this function frees the memory allocated by %@AB@%_registerfonts%@AE@%. The register information for each type size of each font takes up approximately 140 bytes of memory. Thus the amount of memory returned by %@AB@%_unregisterfonts%@AE@% is significant only if you have many fonts registered.%@NL@% %@NL@% ■ As for aesthetics, the same suggestions for the printed page apply to fonted screen text. Typefaces are more effective when they are not competing with each other for attention. Restricting the number of styles per screen to one or two generally results in a more pleasing, less cluttered image.%@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A00160001 @%%@1@%%@AB@%Chapter 16 In-Line Assembly%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% QuickC has the ability to handle assembly-language instructions right in your C programs. This powerful feature is called "in-line assembly." %@NL@% %@NL@% Assembly language serves many purposes, such as improving program speed, reducing memory needs, and controlling hardware. The in-line assembler lets you embed assembly-language instructions directly in your C source programs without extra assembly and link steps. And the assembler is built into the compiler─you don't need a separate assembler such as the Microsoft Macro Assembler (MASM). %@NL@% %@NL@% This chapter assumes that you are familiar with assembly-language terms and concepts. If you have never programmed in assembly language, refer to the section "References and Books on Assembly Language," at the end of this chapter. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00160002 @%%@AB@%Advantages of In-Line Assembly%@AE@%%@EH@%%@NL@% %@NL@% Because QuickC's in-line assembler doesn't require separate assembly and link steps, it is more convenient than a separate assembler. In-line assembly code can use any C variable or function name that is visible (in scope), so it is easy to integrate it with your program's C code. And because the assembly code can be mixed in-line with C statements, it can do tasks that are cumbersome or impossible in C alone. %@NL@% %@NL@% The uses of in-line assembly include %@NL@% %@NL@% %@NL@% ■ Writing the body of a function in assembly language%@NL@% %@NL@% ■ Spot-optimizing speed-critical sections of code%@NL@% %@NL@% ■ Calling DOS and BIOS routines with the %@AB@%INT%@AE@% instruction%@NL@% %@NL@% ■ Creating TSR (terminate-and-stay-resident) code or handler routines that require knowledge of processor states%@NL@% %@NL@% %@NL@% In-line assembly is a special-purpose tool. If you plan to transport an application, you'll probably want to place machine-specific code in a separate module. And because the in-line assembler doesn't support all MASM directives, you may find it more convenient to use MASM for such modules. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00160003 @%%@AB@%The _asm Keyword%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%_asm%@AE@% keyword invokes the in-line assembler and can appear wherever a C statement is legal. It cannot appear by itself. It must be followed by an assembly instruction, a group of instructions enclosed in braces, or, at the very least, an empty pair of braces. The term "%@AB@%_asm%@AE@% block" here refers to any instruction or group of instructions, whether or not in braces. %@NL@% %@NL@% Below is a simple %@AB@%_asm%@AE@% block enclosed in braces. (The code prints the "beep" character, ASCII 7.) %@NL@% %@NL@% %@AS@% _asm %@AS@% { %@AS@% mov ah, 2 %@AS@% mov dl, 7 %@AS@% int 21h %@AS@% }%@AE@%%@NL@% %@NL@% Alternatively, you can put %@AB@%_asm%@AE@% in front of each assembly instruction: %@NL@% %@NL@% %@AS@% _asm mov ah, 2 %@AS@% _asm mov dl, 7 %@AS@% _asm int 21h%@AE@%%@NL@% %@NL@% Since the %@AB@%_asm%@AE@% keyword is a statement separator, you can also put assembly instructions on the same line: %@NL@% %@NL@% %@AS@% _asm mov ah, 2 _asm mov dl, 7 _asm int 21h%@AE@%%@NL@% %@NL@% %@AU@% Braces can prevent ambiguity and needless repetition.%@AE@% %@NL@% %@NL@% All three examples generate the same code, but the first style─enclosing the %@AB@%_asm%@AE@% block in braces─has some advantages. The braces clearly separate assembly code from C code and avoid needless repetition of the %@AB@%_asm%@AE@% keyword. Braces can also prevent ambiguities. If you want to put a C statement on the same line as an %@AB@%_asm%@AE@% block, you must enclose the block in braces. Without the braces, the compiler cannot tell where assembly code stops and C statements begin. Finally, since the text in braces has the same format as ordinary MASM text, you can easily cut and paste text from existing MASM source files. %@NL@% %@NL@% The braces enclosing an %@AB@%_asm%@AE@% block don't affect variable visibility, as do braces in C. You can also nest %@AB@%_asm%@AE@% blocks, but the nesting doesn't affect variable visibility. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00160004 @%%@AB@%Using Assembly Language in _asm Blocks%@AE@%%@EH@%%@NL@% %@NL@% The in-line assembler has much in common with other assemblers. For example, it accepts any expression that is legal in MASM, and it supports almost all 80286 and 80287 instructions. This section describes the use of assembly-language features in %@AB@%_asm%@AE@% blocks. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160005 @%%@AB@%Instruction Set%@AE@%%@EH@%%@NL@% %@NL@% The in-line assembler supports the full instruction set of the Intel(R) 80286 and 80287 processors, except for privileged instructions that control the processor's protected mode (protected mode is available in the OS/2 and XENIX(R) operating systems, but not in DOS). It does not recognize 80386- and 80387-specific instructions. To use assembly instructions specific to the 80286 and 80287 processors, you must compile your QuickC program with the /G2 switch included in the command line. For a description of the compiler /G command-line switch, refer to Chapter 4, "QCL Command Reference," in the %@AI@%Microsoft QuickC Tool Kit%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160006 @%%@AB@%Expressions%@AE@%%@EH@%%@NL@% %@NL@% In-line assembly code can use any MASM expression, that is, any combination of operands and operators that evaluates to a single value or address. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160007 @%%@AB@%Data Directives and Operators%@AE@%%@EH@%%@NL@% %@NL@% Although an %@AB@%_asm%@AE@% block can reference C data types and objects, it cannot define data objects with MASM directives or operators. Specifically, you cannot use the definition directives %@AB@%DB%@AE@%, %@AB@%DW%@AE@%, %@AB@%DD%@AE@%, %@AB@%DQ%@AE@%, %@AB@%DT%@AE@%, and %@AB@%DF%@AE@%, or the operators %@AB@%DUP%@AE@% or %@AB@%THIS%@AE@%. Nor are MASM structures and records available. The in-line assembler doesn't accept the directives %@AB@%STRUC%@AE@%, %@AB@%RECORD%@AE@%, %@AB@%WIDTH%@AE@%, or %@AB@%MASK%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160008 @%%@AB@%EVEN and ALIGN Directives%@AE@%%@EH@%%@NL@% %@NL@% While the in-line assembler doesn't support most MASM directives, it does support %@AB@%EVEN%@AE@% and %@AB@%ALIGN%@AE@%. These directives put %@AB@%NOP%@AE@% (no operation) instructions in the assembly code as needed to align labels to specific boundaries. This makes instruction-fetch operations more efficient for some processors (not including eight-bit processors such as the Intel 8088). %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160009 @%%@AB@%Macros%@AE@%%@EH@%%@NL@% %@NL@% The in-line assembler is not a macro assembler. You cannot use MASM macro directives (%@AB@%MACRO%@AE@%, %@AB@%REPT%@AE@%, %@AB@%IRC%@AE@%, %@AB@%IRP%@AE@%, and %@AB@%ENDM%@AE@%) or macro operators ( %@AB@%<>%@AE@%, %@AB@%!%@AE@%, %@AB@%&%@AE@%, %@AB@%%%@AE@%, and %@AB@%.TYPE%@AE@%). An %@AB@%_asm%@AE@% block can use C preprocessor directives, however. See the section "Using C in %@AB@%_asm%@AE@% Blocks" for more information. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160010 @%%@AB@%Segment References%@AE@%%@EH@%%@NL@% %@NL@% You must refer to segments by register rather than by name (the segment name %@AB@%_TEXT%@AE@% is invalid, for instance). Segment overrides must use the register explicitly, as in ES:[BX]. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160011 @%%@AB@%Type and Variable Sizes%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%LENGTH%@AE@%, %@AB@%SIZE%@AE@%, and %@AB@%TYPE%@AE@% operators have a limited meaning in in-line assembly. They cannot be used at all with the %@AB@%DUP%@AE@% operator (because you cannot define data with MASM directives or operators). But you can use them to find the size of C variables or types: %@NL@% %@NL@% %@NL@% ■ The %@AB@%LENGTH%@AE@% operator can return the number of elements in an array. It returns the value 1 for nonarray variables.%@NL@% %@NL@% ■ The %@AB@%SIZE%@AE@% operator can return the size of a C variable. A variable's size is the product of its %@AB@%LENGTH%@AE@% and %@AB@%TYPE%@AE@%.%@NL@% %@NL@% ■ The %@AB@%TYPE%@AE@% operator can return the size of a C type or variable. If the variable is an array, %@AB@%TYPE%@AE@% returns the size of a single element of the array.%@NL@% %@NL@% %@NL@% For instance, if your program has an eight-element %@AB@%int%@AE@% array, %@NL@% %@NL@% %@AS@% int arr[8];%@AE@%%@NL@% %@NL@% the following C and assembly expressions yield the size of %@AS@% arr %@AE@% and its elements: %@NL@% %@NL@% %@TH: 6 465 02 12 28 36 @%_asm C Size%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AS@%LENGTH arr%@AE@% %@AS@%sizeof(arr)/sizeof(arr[0])%@AE@% 8%@AS@%SIZE arr%@AE@% %@AS@%sizeof(arr)%@AE@% 16%@AS@%TYPE arr%@AE@% %@AS@%sizeof(arr[0])%@AE@% 2%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 6 465 02 12 28 36 @% %@NL@% %@4@%%@AB@%Comments%@AE@%%@EH@%%@NL@% %@NL@% Instructions in an %@AB@%_asm%@AE@% block can use assembly-language comments: %@NL@% %@NL@% %@AS@% _asm mov ax, offset buff ; Load address of buff%@AE@%%@NL@% %@NL@% Because C macros expand into a single logical line, avoid using assemblylanguage comments in macros (see the section "Defining %@AB@%_asm%@AE@% Blocks as C Macros," below). An %@AB@%_asm%@AE@% block can also contain C-style comments, as noted below. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Debugging with the CodeView(R) Debugger%@AE@%%@EH@%%@NL@% %@NL@% %@AU@% In-line assembly code can be debugged with CodeView.%@AE@% %@NL@% %@NL@% Programs containing in-line assembly code can be debugged with the CodeView debugger, assuming you compile with the /Zi option. %@NL@% %@NL@% Note that putting multiple assembly instructions or C statements on one line can hamper debugging with CodeView. In source mode, the CodeView debugger lets you set breakpoints on a single line but not on individual statements on the same line. The same principle applies to an %@AB@%_asm%@AE@% block defined as a C macro, which expands to a single logical line. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00160012 @%%@AB@%Using C in _asm Blocks%@AE@%%@EH@%%@NL@% %@NL@% Because in-line assembly instructions can be mixed with C statements, they can refer to C variables by name and use many other elements of C. An %@AB@%_asm%@AE@% block can use the following C language elements: %@NL@% %@NL@% %@NL@% ■ Symbols, including labels and variable and function names%@NL@% %@NL@% ■ Constants, including symbolic constants and %@AB@%enum%@AE@% members%@NL@% %@NL@% ■ Macros and preprocessor directives%@NL@% %@NL@% ■ Comments (%@AS@% /* */ %@AE@%)%@NL@% %@NL@% ■ Type names (wherever a MASM type would be legal)%@NL@% %@NL@% ■ %@AB@%typedef%@AE@% names, generally used with operators such as %@AB@%PTR%@AE@% and %@AB@%TYPE%@AE@% or to specify structure or union members%@NL@% %@NL@% %@NL@% Within an %@AB@%_asm%@AE@% block, you can specify integer constants with either C notation or assembler radix notation (0x100 and 100h are equivalent, for instance). This allows you to define (using %@AB@%#define%@AE@%) a constant in C, and use it in both C and assembly portions of the program. You can also specify constants in octal by preceding them with a 0. For example, 0777 specifies an octal constant. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160013 @%%@AB@%Using Operators%@AE@%%@EH@%%@NL@% %@NL@% An %@AB@%_asm%@AE@% block cannot use C-specific operators, such as the %@AB@%%@AE@% operator. However, operators shared by QuickC and MASM, such as the %@AB@%*%@AE@% operator, are interpreted as assembly-language operators. For instance, outside an %@AB@%_asm%@AE@% block, square brackets (%@AB@% [] %@AE@%) are interpreted as enclosing array subscripts, which C automatically scales to the size of an element in the array. Inside an %@AB@%_asm%@AE@% block, they are seen as the MASM index operator, which yields an unscaled byte offset from any data object or label (not just an array). The following code illustrates the difference: %@NL@% %@NL@% %@AS@% int array[10]; %@AS@% %@AS@% _asm mov array[6], bx ; Store BX at array+6 (not scaled) %@AS@% %@AS@% array[6] = 0; /* Store 0 at array+12 (scaled) */%@AE@%%@NL@% %@NL@% The first reference to %@AS@% array %@AE@% is not scaled, but the second is. Note that you can use the %@AB@%TYPE%@AE@% operator to achieve scaling based on a constant. For instance, the following statements are equivalent: %@NL@% %@NL@% %@AS@% _asm mov array[6 * TYPE int], 0 ; Store 0 at array + 12 %@AS@% %@AS@% array[6] = 0; /* Store 0 at array + 12 */%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160014 @%%@AB@%Using C Symbols%@AE@%%@EH@%%@NL@% %@NL@% An %@AB@%_asm%@AE@% block can refer to any C symbol that is visible (in scope) where the block appears. (C symbols are variable names, function names, and labels─in other words, names that aren't symbolic constants or %@AB@%enum%@AE@% members.) %@NL@% %@NL@% A few restrictions apply to the use of C symbols: %@NL@% %@NL@% %@NL@% ■ Each assembly-language statement can contain only one C symbol. Multiple symbols can appear in the same assembly instruction only with %@AB@%OFFSET%@AE@%,%@AB@% LENGTH%@AE@%,%@AB@% TYPE%@AE@%, and %@AB@%SIZE%@AE@% expressions.%@NL@% %@NL@% ■ Functions referenced in an %@AB@%_asm%@AE@% block must be declared (prototyped) earlier in the program. Otherwise, the compiler cannot distinguish between function names and labels in the %@AB@%_asm%@AE@% block.%@NL@% %@NL@% ■ An %@AB@%_asm%@AE@% block cannot use any C symbols with the same spelling as MASM reserved words (regardless of case). MASM reserved words include instruction names such as %@AB@%PUSH%@AE@% and register names such as SI.%@NL@% %@NL@% ■ Structure and union tags are not recognized in %@AB@%_asm%@AE@% blocks.%@NL@% %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160015 @%%@AB@%Accessing C Data%@AE@%%@EH@%%@NL@% %@NL@% A great convenience of in-line assembly is the ability to refer to C variables by name. An %@AB@%_asm%@AE@% block can refer to any symbols─including variable names─that are visible where the block appears. For instance, if the C variable %@AS@% var %@AE@% is visible, the instruction %@NL@% %@NL@% %@AS@% _asm mov ax, var%@AE@%%@NL@% %@NL@% stores the value of %@AS@% var %@AE@% in AX. %@NL@% %@NL@% If a structure or union member has a unique name, an %@AB@%_asm%@AE@% block can refer to it using only the member name, without specifying the C variable or %@AB@%typedef%@AE@% name before the period (%@AB@%.%@AE@%) operator. If the member name is not unique, however, you must place a variable or %@AB@%typedef%@AE@% name immediately before the period (%@AB@%.%@AE@%) operator. For instance, the following structure types share %@AS@% %@AS@%same_name %@AE@% as their member name: %@NL@% %@NL@% %@AS@% struct first_type %@AS@% { %@AS@% char *weasel; %@AS@% int same_name; %@AS@% }; %@AS@% %@AS@% struct second_type %@AS@% { %@AS@% int wonton; %@AS@% long same_name; %@AS@% };%@AE@%%@NL@% %@NL@% If you declare variables with the types %@NL@% %@NL@% %@AS@% struct first_type hal; %@AS@% struct second_type oat;%@AE@%%@NL@% %@NL@% all references to the member %@AS@% same_name %@AE@% must use the variable name, because %@AS@%same_name %@AE@% is not unique. But the member %@AS@% weasel %@AE@% has a unique name, so you can refer to it using only its member name: %@NL@% %@NL@% %@AS@% _asm %@AS@% { %@AS@% mov bx, OFFSET hal %@AS@% mov cx, [bx]hal.same_name ; Must use 'hal' %@AS@% mov si, [bx].weasel ; Can omit 'hal' %@AS@% }%@AE@%%@NL@% %@NL@% Note that omitting the variable name is merely a coding convenience. The same assembly instructions are generated whether or not it is present. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A00160016 @%%@AB@%Writing Functions%@AE@%%@EH@%%@NL@% %@NL@% If you write a function with in-line assembly code, it's a simple matter to pass arguments to the function and return a value from it. The following examples compare a function first written for a separate assembler and then rewritten for the in-line assembler. The function, called %@AS@% power2%@AE@%, receives two parameters, multiplying the first parameter by 2 to the power of the second parameter. Written for a separate assembler, the function might look like this: %@NL@% %@NL@% %@AS@% ; POWER.ASM %@AS@% ; Compute the power of an integer %@AS@% ; %@AS@% PUBLIC _power2 %@AS@% _TEXT SEGMENT WORD PUBLIC 'CODE' %@AS@% _power2 PROC %@AS@% %@AS@% push bp ; Save BP %@AS@% mov bp, sp ; Move SP into BP so we can refer %@AS@% ; to arguments on the stack %@AS@% mov ax, [bp+4] ; Get first argument %@AS@% mov cx, [bp+6] ; Get second argument %@AS@% shl ax, cl ; AX = AX * ( 2 ^ CL ) %@AS@% pop bp ; Restore BP %@AS@% ret ; Return with sum in AX %@AS@% %@AS@% _power2 ENDP %@AS@% _TEXT ENDS %@AS@% END%@AE@%%@NL@% %@NL@% %@AU@% Function arguments are usually passed on the stack.%@AE@% %@NL@% %@NL@% Since it's written for a separate assembler, the function requires a separate source file and assembly and link steps. C function arguments usually are passed on the stack, so this version of the %@AS@% power2 %@AE@% function accesses its arguments by their positions on the stack. (Note that the %@AB@%MODEL%@AE@% directive, available in MASM and some other assemblers, also allows you to access stack arguments and local stack variables by name.) %@NL@% %@NL@% The POWER2.C program below writes the %@AS@% power2 %@AE@% function with in-line assembly code: %@NL@% %@NL@% %@AS@% /* POWER2.C */ %@AS@% #include <stdio.h> %@AS@% %@AS@% int power2( int num, int power ); %@AS@% %@AS@% void main( void ) %@AS@% { %@AS@% printf( "3 times 2 to the power of 5 is %d\n", \ %@AS@% power2( 3, 5) ); %@AS@% } %@AS@% %@AS@% int power2( int num, int power ) %@AS@% { %@AS@% _asm %@AS@% { %@AS@% mov ax, num ; Get first argument %@AS@% mov cx, power ; Get second argument %@AS@% shl ax, cl ; AX = AX * ( 2 to the power of CL ) %@AS@% } %@AS@% /* Return with result in AX */ %@AS@% }%@AE@%%@NL@% %@NL@% The in-line version of the %@AS@% power2 %@AE@% function refers to its arguments by name and appears in the same source file as the rest of the program. This version also requires fewer assembly instructions. Since C automatically preserves BP, the %@AB@%_asm%@AE@% block doesn't need to do so. It can also dispense with the %@AB@%RET%@AE@% instruction, since the C part of the function performs the return. %@NL@% %@NL@% Because the in-line version of %@AS@% power2 %@AE@% doesn't execute a C %@AB@%return%@AE@% statement, it causes a harmless warning if you compile at warning levels 2 or higher: %@NL@% %@NL@% %@AS@% warning C4035: 'power2' : no return value%@AE@%%@NL@% %@NL@% The function does return a value, but QuickC cannot tell that in the absence of a %@AB@%return%@AE@% statement. Simply ignore the warning in this context. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00160017 @%%@AB@%Using and Preserving Registers%@AE@%%@EH@%%@NL@% %@NL@% In general, you should not assume that a register will have a given value when an %@AB@%_asm%@AE@% block begins. An %@AB@%_asm%@AE@% block inherits whatever register values happen to result from the normal flow of control. %@NL@% %@NL@% As you may have noticed in the POWER2.C example in the previous section, the %@AS@%power2 %@AE@% function doesn't preserve the value in the AX register. When you write a function in assembly language, you don't need to preserve the AX, BX, CX, DX, ES, and flags registers. However, you should preserve any other registers you use (DI, SI, DS, SS, SP, and BP). %@NL@% %@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@AU@%WARNING%@AE@%%@NL@% %@NL@% If your in-line assembly code changes the direction flag using the STD or CLD instructions, you must restore the flag to its original value.%@NL@% ────────────────────────────────────────────────────────────────────────────%@NL@% %@NL@% The POWER2.C example in the previous section also shows that functions return values in registers. This is true whether the function is written in assembly language or in C. %@NL@% %@NL@% %@AU@% Functions return values in the AX and DX registers.%@AE@% %@NL@% %@NL@% If the return value is short (a %@AB@%char%@AE@%, %@AB@%int%@AE@%, or %@AB@%near%@AE@% pointer), it is stored in AX. The POWER2.C example returned a value by terminating with the desired value in AX. %@NL@% %@NL@% If the return value is long, store the high word in DX and the low word in AX. To return a longer value (such as a floating-point value), store the value in memory and return a pointer to the value (in AX if %@AB@%near%@AE@% or in DX:AX if %@AB@%far%@AE@%). %@NL@% %@NL@% Assembly instructions that appear in-line with C statements are free to alter the AX, BX, CX, and DX registers. C doesn't expect these registers to be maintained between statements, so you don't need to preserve them. The same is true of the SI and DI registers, with some exceptions (see the section "Optimizing," below). You should preserve the SP and BP registers unless you have some reason to change them─to switch stacks, for instance. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00160018 @%%@AB@%Jumping to Labels%@AE@%%@EH@%%@NL@% %@NL@% Like an ordinary C label, a label in an %@AB@%_asm%@AE@% block is visible (has scope) throughout the function in which it is defined (not only in the block). Both assembly instructions and C %@AB@%goto%@AE@% statements can jump to labels inside or outside the %@AB@%_asm%@AE@% block. %@NL@% %@NL@% %@AU@% Labels in _asm blocks have function scope and are not case sensitive.%@AE@% %@NL@% %@NL@% Unlike C labels, labels defined in %@AB@%_asm%@AE@% blocks are not case sensitive, even when used in C statements. C labels are not case sensitive in an %@AB@%_asm%@AE@% block, either. (Outside an %@AB@%_asm%@AE@% block, a C label is case sensitive as usual.) The following do-nothing code shows all the permutations. %@NL@% %@NL@% %@AS@% void func( void ) %@AS@% { %@AS@% goto C_Dest; /* legal */ %@AS@% goto c_dest; /* error */ %@AS@% %@AS@% goto A_Dest; /* legal */ %@AS@% goto a_dest; /* legal */ %@AS@% %@AS@% _asm %@AS@% { %@AS@% jmp C_Dest ; legal %@AS@% jmp c_dest ; legal %@AS@% %@AS@% jmp A_Dest ; legal %@AS@% jmp a_dest ; legal %@AS@% %@AS@% a_dest: ; _asm label %@AS@% } %@AS@% %@AS@% C_Dest: /* C label */ %@AS@% return; %@AS@% }%@AE@%%@NL@% %@NL@% Don't use C library function names as labels in %@AB@%_asm%@AE@% blocks. For instance, you might be tempted to use %@AS@% exit %@AE@% as a label, %@NL@% %@NL@% %@AS@% jne exit %@AS@% . %@AS@% . %@AS@% . %@AS@% exit: %@AS@% ; More _asm code follows%@AE@%%@NL@% %@NL@% forgetting that %@AB@%exit%@AE@% is the name of a C library function. The code doesn't cause a compiler error, but it might cause a jump to the %@AB@%exit%@AE@% function instead of the desired location. %@NL@% %@NL@% As in MASM programs, the dollar symbol (%@AB@%$%@AE@%) serves as the current location counter─a label for the instruction currently being assembled. In %@AB@%_asm%@AE@% blocks, its main use is to make long conditional jumps: %@NL@% %@NL@% %@AS@% jne $+5 ; next instruction is 5 bytes long %@AS@% jmp farlabel %@AS@% ; $+5 %@AS@% . %@AS@% . %@AS@% . %@AS@% farlabel:%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00160019 @%%@AB@%Calling C Functions%@AE@%%@EH@%%@NL@% %@NL@% An %@AB@%_asm%@AE@% block can call C functions, including C library routines. The following example calls the %@AB@%printf%@AE@% library routine: %@NL@% %@NL@% %@AS@% #include <stdio.h> %@AS@% %@AS@% char format[] = "%s %s\n"; %@AS@% char hello[] = "Hello"; %@AS@% char world[] = "world"; %@AS@% %@AS@% void main( void ) %@AS@% { %@AS@% _asm %@AS@% { %@AS@% mov ax, offset world %@AS@% push ax %@AS@% mov ax, offset hello %@AS@% push ax %@AS@% mov ax, offset format %@AS@% push ax %@AS@% call printf %@AS@% add sp, 6 %@AS@% } %@AS@% }%@AE@%%@NL@% %@NL@% Since function arguments are passed on the stack, you simply push the needed arguments─string pointers, in the example above─before calling the function. The arguments are pushed in reverse order, so they come off the stack in the desired order. To emulate the C statement %@NL@% %@NL@% %@AS@% printf( format, hello, world );%@AE@%%@NL@% %@NL@% the example pushes pointers to %@AS@% world%@AE@%, %@AS@% hello%@AE@%, and %@AS@% format%@AE@%, in that order, then calls %@AB@%printf%@AE@%. The last instruction in the %@AB@%_asm%@AE@% block adjusts the stack to account for the arguments previously pushed onto it. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00160020 @%%@AB@%Defining _asm Blocks as C Macros%@AE@%%@EH@%%@NL@% %@NL@% C macros offer a convenient way to insert assembly code into C code, but they demand extra care because a macro expands into a single logical line. To create trouble-free macros, follow these rules: %@NL@% %@NL@% %@NL@% ■ Enclose the %@AB@%_asm%@AE@% block in braces%@NL@% %@NL@% ■ Put the %@AB@%_asm%@AE@% keyword in front of each assembly instruction%@NL@% %@NL@% ■ Use old-style C comments (%@AS@% /* comment */ %@AE@%) instead of assembly-style comments (%@AS@% ; comment %@AE@%)%@NL@% %@NL@% %@NL@% To illustrate, the following example defines a simple macro: %@NL@% %@NL@% %@AS@% #define BEEP _asm \ %@AS@% /* Beep sound */ \ %@AS@% { \ %@AS@% _asm mov ah, 2 \ %@AS@% _asm mov dl, 7 \ %@AS@% _asm int 21h \ %@AS@% }%@AE@%%@NL@% %@NL@% At first glance, the last three %@AB@%_asm%@AE@% keywords seem superfluous. They are needed, however, because the macro expands into a single line: %@NL@% %@NL@% %@AS@% _asm /* Beep sound */ { _asm mov ah, 2 _asm mov dl, 7 _asm int 21h }%@AE@%%@NL@% %@NL@% The third and fourth %@AB@%_asm%@AE@% keywords are needed as statement separators. The only statement separators recognized in %@AB@%_asm%@AE@% blocks are the newline character and %@AB@%_asm%@AE@% keyword. And since a block defined as a macro is one logical line, you must separate each instruction with %@AB@%_asm%@AE@%. %@NL@% %@NL@% The braces are essential as well. If you omit them, the compiler can be confused by C statements on the same line to the right of the macro invocation. Without the closing brace, QuickC cannot tell where assembly code stops, and it sees C statements after the %@AB@%_asm%@AE@% block as assembly instructions. %@NL@% %@NL@% %@AU@% Use C comments in _asm blocks written as macros.%@AE@% %@NL@% %@NL@% Assembly-style comments that start with a semicolon (;) continue to the end of the line. This causes problems in macros because QuickC ignores everything after the comment, all the way to the end of the logical line. To prevent errors, use C comments (%@AS@% /* comment */ %@AE@%) in %@AB@%_asm%@AE@% blocks defined as macros. %@NL@% %@NL@% An %@AB@%_asm%@AE@% block written as a C macro can take arguments. Unlike an ordinary C macro, however, an %@AB@%_asm%@AE@% macro cannot return a value. So you cannot use such macros in C expressions. %@NL@% %@NL@% %@AU@% You can convert MASM macros to C macros.%@AE@% %@NL@% %@NL@% Note that some MASM-style macros can be written as C macros. Below is a MASM macro that sets the video page to the value specified in the %@AS@% page %@AE@% argument: %@NL@% %@NL@% %@AS@% setpage MACRO page %@AS@% mov ah, 5 %@AS@% mov al, page %@AS@% int 10h %@AS@% ENDM%@AE@%%@NL@% %@NL@% The following code defines %@AS@% setpage %@AE@% as a C macro: %@NL@% %@NL@% %@AS@% #define setpage( page ) _asm \ %@AS@% { \ %@AS@% _asm mov ah, 5 \ %@AS@% _asm mov al, page \ %@AS@% _asm int 10h \ %@AS@% }%@AE@%%@NL@% %@NL@% Both macros do the same job. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00160021 @%%@AB@%Optimizing%@AE@%%@EH@%%@NL@% %@NL@% The presence of an %@AB@%_asm%@AE@% block in a function affects optimization in a few different ways. First, as you might expect, QuickC doesn't try to optimize the %@AB@%_asm%@AE@% block itself. What you write in assembly language is exactly what you get. %@NL@% %@NL@% Second, the presence of an %@AB@%_asm%@AE@% block affects register variable storage. (See the section "Register Variables" in Chapter 5, "Advanced Data Types," for a discussion of register variables.) Under normal circumstances, QuickC automatically stores variables in registers. This is not done, however, in any function that contains an %@AB@%_asm%@AE@% block. To get register variable storage in such a function, you must request it with the %@AB@%register%@AE@% keyword. %@NL@% %@NL@% Since the compiler stores register variables in the SI and DI registers, these registers represent variables in functions that request register storage. The first eligible variable is stored in SI and the second in DI. Preserve SI and DI in such functions unless you want to change the register variables. %@NL@% %@NL@% Keep in mind that the name of a variable declared with %@AB@%register%@AE@% translates directly into a register reference (assuming a register is available for such use). For instance, if you declare %@NL@% %@NL@% %@AS@% register int sample;%@AE@%%@NL@% %@NL@% and the variable %@AS@% sample %@AE@% happens to be stored in SI, then the %@AB@%_asm%@AE@% instruction %@NL@% %@NL@% %@AS@% _asm mov ax, sample%@AE@%%@NL@% %@NL@% is equivalent to %@NL@% %@NL@% %@AS@% _asm mov ax, si%@AE@%%@NL@% %@NL@% If you declare a variable with %@AB@%register%@AE@% and the compiler cannot store the variable in a register, QuickC issues a compiler error if you reference the variable in an %@AB@%_asm%@AE@% block. The solution is to remove the %@AB@%register%@AE@% declaration from that variable. %@NL@% %@NL@% Register variables form a slight exception to the general rule that an assembly-language statement can contain no more than one C symbol. If one of the symbols is a register variable, for example, %@NL@% %@NL@% %@AS@% register int v1; %@AS@% int v2;%@AE@%%@NL@% %@NL@% then an instruction can use two C symbols, as in %@NL@% %@NL@% %@AS@% mov v1, v2%@AE@%%@NL@% %@NL@% Finally, the presence of in-line assembly code inhibits loop optimization for the entire function in which the code appears. (Loop optimization can be selected with the /Ol command-line switch; see Chapter 4, "QCL Command Reference," in %@AI@%Microsoft QuickC Tool Kit%@AE@%.) This optimization is suppressed no matter which compiler options you use. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A00160022 @%%@AB@%References and Books on Assembly Language%@AE@%%@EH@%%@NL@% %@NL@% Assembly language varies widely for different computer processors. In selecting a reference on assembly language, make sure it describes assembly for the Intel 8086 family of processors or compatibles. These are the microprocessors used in the IBM and IBM-compatible computers able to run QuickC. %@NL@% %@NL@% The following books and articles may be useful in learning to program in assembly language: %@NL@% %@NL@% Chesley, Harry R. and Mitchell Waite. %@AI@%Supercharging C with Assembly %@AI@%Language%@AE@%. Reading, Massachusetts: Addison-Wesley Publishing Company, Inc., 1987.%@NL@% %@NL@% Duncan, Ray. %@AI@%Advanced MS-DOS Programming, %@AE@%2nd ed. Redmond, Washington: Microsoft Press, 1988.%@NL@% %@NL@% Lafore, Robert. %@AI@%Assembly Language Primer for the IBM PC & XT%@AE@%. New York, New York: Plume/Waite, 1984.%@NL@% %@NL@% Metcalf, Christopher D. and Marc B. Sugiyama. %@AI@%COMPUTE!'s Beginner's Guide to %@AI@%Machine Language on the IBM PC & PCjr%@AE@%. Greensboro, North Carolina: COMPUTE! Publications, Inc., 1985.%@NL@% %@NL@% Microsoft. %@AI@%Microsoft Macro Assembler 5.1 Programmer's Guide%@AE@%. Redmond, Washington, 1987. (Included with Microsoft Macro Assembler.)%@NL@% %@NL@% Microsoft. %@AI@%Microsoft Macro Assembler 5.1 Reference%@AE@%. Redmond, Washington, 1987. (Included with Microsoft Macro Assembler.)%@NL@% %@NL@% Sargent, Murray and Richard L. Shoemaker. %@AI@%The IBM Personal Computer from the %@AI@%Inside Out%@AE@%. Reading, Massachusetts: Addison-Wesley Publishing Company, Inc., 1986.%@NL@% %@NL@% The above references are listed for your convenience only. With the exception of those published by Microsoft, Microsoft Corporation does not endorse these books or recommend them over others on the same subject. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A-A0001 @%%@1@%%@AB@%Appendix A C Language Guide%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% This appendix provides a quick summary of C language fundamentals. It does not attempt to teach you the C language (Part 1 of this book does that) or document all the details of C. Use it as a refresher or ready reference after you have read all the material in Chapters 1 through 10. %@NL@% %@NL@% To simplify reference, this appendix has the same general organization as the chapters in Part 1. Each major section lists the chapter(s) where you may find more detailed information on a given topic. %@NL@% %@NL@% You can also use QuickC's online help to get instant information on any topic. The online help index and table of contents provide alternate ways to access information. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-A0002 @%%@AB@%General Syntax%@AE@%%@EH@%%@NL@% %@NL@% Basic C-language syntax is explained in Chapter 1, "Anatomy of a C Program." %@NL@% %@NL@% A C statement consists of keywords, expressions, and function calls. A statement always ends with a semicolon. A statement block is a collection of statements enclosed by braces (%@AB@%{%@AE@% %@AB@%}%@AE@%). A statement block can appear anywhere a simple C statement appears. No semicolon occurs after the closing brace. %@NL@% %@NL@% C is a free-format programming language. You can insert "whitespace" characters (spaces, tabs, carriage returns, and form feeds) almost anywhere, to indent statement blocks and otherwise make your code more readable. %@NL@% %@NL@% Comments begin with the slash-asterisk sequence (%@AB@%/*%@AE@%) and end with the asterisk-slash sequence (%@AB@%*/%@AE@%). Comments are legal anywhere a space is legal, but they cannot be nested. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0003 @%%@AB@%User-Defined Names%@AE@%%@EH@%%@NL@% %@NL@% The rules governing user-defined names are explained in Chapter 1, "Anatomy of a C Program," and Chapter 4, "Basic Data Types." %@NL@% %@NL@% You can define your own names ("identifiers") for variables, functions, and user-defined types. Identifiers are case sensitive. For instance, the identifier %@AS@%myVariable %@AE@% is not the same as the identifier %@AS@% Myvariable%@AE@%. You cannot use a C keyword (see the list below) as an identifier. %@NL@% %@NL@% An identifier can contain only the following characters: %@NL@% %@NL@% %@NL@% ■ abcdefghijklmnopqrstuvwxyz%@NL@% %@NL@% ■ ABCDEFGHIJKLMNOPQRSTUVWXYZ%@NL@% %@NL@% ■ 0123456789%@NL@% %@NL@% ■ _ (underscore)%@NL@% %@NL@% %@NL@% The first character of an identifier must be a letter or the underscore character. The first 31 characters of local identifiers are significant. The name can contain more than 31 characters, but QuickC ignores everything beyond the thirty-first character. Global identifiers are normally significant to 30 characters. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0004 @%%@AB@%Keywords%@AE@%%@EH@%%@NL@% %@NL@% A keyword has a special meaning in the C language. You must spell keywords as shown in the following list, and you cannot use them as user-defined names (see above). %@NL@% %@NL@% %@AB@%_asm _emit _interrupt signed%@AE@% %@AB@% auto enum _loadds sizeof%@AE@% %@AB@%_based _export long static%@AE@% %@AB@% break extern _near struct%@AE@% %@AB@% case _far _pascal switch%@AE@% %@AB@%_cdecl _fastcall register typedef%@AE@% %@AB@% char float return union%@AE@% %@AB@% const for _saveregs unsigned%@AE@% %@AB@% continue _fortran _segname void%@AE@% %@AB@% default goto _segment volatile%@AE@% %@AB@% do _huge _self while%@AE@% %@AB@% double if short %@AE@% %@AB@% else int A few other words, such as %@AB@%main%@AE@%, have a special meaning but are not keywords in the strict sense. Use online help to get details on all such words. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-A0005 @%%@AB@%Functions%@AE@%%@EH@%%@NL@% %@NL@% The rules governing C functions are explained in Chapter 2, "Functions." %@NL@% %@NL@% Every C program must have at least one function, named %@AB@%main%@AE@%, which marks the beginning and end of the program's execution. Every executable statement in a C program must occur within a function. %@NL@% %@NL@% Variables can be declared inside or outside functions. Variables declared inside a function are "local" and can only be accessed in that function. Variables declared outside all functions are "global" and can be accessed from any function in your program. %@NL@% %@NL@% You call a C function by stating its name. If the function requires "arguments" (data), you list the arguments in the parentheses that follow the function name. Arguments that you pass to a function become local variables in the function. %@NL@% %@NL@% A function can return a value (using the %@AB@%return%@AE@% keyword) or return nothing. If the function contains no %@AB@%return%@AE@% statement, it ends automatically when execution reaches the closing brace of the function definition. %@NL@% %@NL@% A function "prototype" (declaration) tells QuickC the function's name, the type of value it returns, and the number and type of arguments it requires. Function prototypes normally appear near the beginning of the program. They allow QuickC to check the accuracy of every reference to the function. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-A0006 @%%@AB@%Flow Control%@AE@%%@EH@%%@NL@% %@NL@% Flow-control statements are explained in Chapter 3, "Flow Control." %@NL@% %@NL@% The C language provides several kinds of flow-control statements. The %@AB@%for%@AE@%, %@AB@%while%@AE@%, and %@AB@%do%@AE@% statements create loops. The %@AB@%if%@AE@% and %@AB@%switch%@AE@% statements perform a branch. The %@AB@%break%@AE@%, %@AB@%continue%@AE@%, %@AB@%return%@AE@%, and %@AB@%goto%@AE@% statements perform an unconditional "jump" to another location in your program. %@NL@% %@NL@% The following sections describe the C flow-control statements in alphabetical order. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0007 @%%@AB@%The break Statement%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%break%@AE@% statement terminates the smallest enclosing %@AB@%do%@AE@%, %@AB@%for%@AE@%, %@AB@%switch%@AE@%, or %@AB@%while%@AE@% statement in which it appears. It passes control to the statement following the terminated statement. %@NL@% %@NL@% This statement is often used to exit from a loop or %@AB@%switch%@AE@% statement (see below). The following example illustrates %@AB@%break%@AE@%: %@NL@% %@NL@% %@AS@% while( c != 'Q' ) %@AS@% { %@AS@% /* Some C statements here */ %@AS@% if( number_of_characters > 80 ) %@AS@% break; /* Break out of while loop */ %@AS@% /* More C statements here */ %@AS@% } %@AS@% /* Execution continues here after break statement */%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0008 @%%@AB@%The continue Statement%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%continue%@AE@% statement is the opposite of the %@AB@%break%@AE@% statement. It passes control to the next iteration of the smallest enclosing %@AB@%do%@AE@%, %@AB@%for%@AE@%, or %@AB@%while%@AE@% statement in which it appears. %@NL@% %@NL@% This statement is often used to return to the start of a loop from within a deeply nested loop. %@NL@% %@NL@% The following example illustrates %@AB@%continue%@AE@%: %@NL@% %@NL@% %@AS@% while( c != 'Q' ) %@AS@% { %@AS@% /* Some C statements here*/ %@AS@% if( c == 0x20 ) %@AS@% continue; /* Skip rest of loop */ %@AS@% /* More C statements here */ %@AS@% }%@AE@%%@NL@% %@NL@% In the example, the %@AB@%continue%@AE@% statement skips to the next iteration of the loop whenever %@AS@% c %@AE@% equals 0x20, the ASCII value for a space character. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0009 @%%@AB@%The do Statement%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%do%@AE@% statement repeats a statement until a specified expression becomes false. The test expression in the loop is evaluated after the body of the loop executes. Thus, the body of a %@AB@%do%@AE@% loop always executes at least once. %@NL@% %@NL@% Use a %@AB@%break%@AE@%, %@AB@%goto%@AE@%, or %@AB@%return%@AE@% statement when you need to exit a %@AB@%do%@AE@% loop early. Use the %@AB@%continue%@AE@% statement to terminate an iteration without exiting the loop. The %@AB@%continue%@AE@% statement passes control to the next iteration of the loop. %@NL@% %@NL@% The following example illustrates %@AB@%do%@AE@%: %@NL@% %@NL@% %@AS@% sample = 1; %@AS@% do %@AS@% printf( "%d\t%d\n", sample, sample * sample ); %@AS@% while( ++x <= 7 );%@AE@%%@NL@% %@NL@% The %@AB@%printf%@AE@% statement in the example always executes at least once, no matter what value %@AS@% x %@AE@% has when the loop begins. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0010 @%%@AB@%The for Statement%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%for%@AE@% statement lets you repeat a statement a specified number of times. It consists of three expressions: %@NL@% %@NL@% %@NL@% ■ An initializing expression, which is evaluated when the loop begins%@NL@% %@NL@% ■ A test expression, which is evaluated before each iteration of the loop%@NL@% %@NL@% ■ A modifying expression, which is evaluated at the end of each iteration of the loop%@NL@% %@NL@% %@NL@% These expressions are enclosed in parentheses and followed by the loop body─the statement the loop is to execute. Each expression in the parentheses can be any legal C statement. %@NL@% %@NL@% The %@AB@%for%@AE@% statement works as follows: %@NL@% %@NL@% %@NL@% 1. The initializing expression is evaluated.%@NL@% %@NL@% 2. As long as the test expression evaluates to a nonzero value, the loop body is executed. When the test expression becomes 0, control passes to the statement following the loop body.%@NL@% %@NL@% 3. At the end of each iteration of the loop, the modifying expression is evaluated.%@NL@% %@NL@% %@NL@% You can use a %@AB@%break%@AE@%, %@AB@%goto%@AE@%, or %@AB@%return%@AE@% statement to exit a %@AB@%for%@AE@% loop early. Use the %@AB@%continue%@AE@% statement to terminate an iteration without exiting the %@AB@%for%@AE@% loop. The %@AB@%continue%@AE@% statement passes control to the next iteration of the loop. %@NL@% %@NL@% The following example illustrates %@AB@%for%@AE@%: %@NL@% %@NL@% %@AS@% for( counter = 0; counter < 100; counter++ ) %@AS@% { %@AS@% x[counter] = 0; /* Set every array element to zero */ %@AS@% }%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0011 @%%@AB@%The goto Statement%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%goto%@AE@% statement performs a jump to the statement following the specified label. A %@AB@%goto%@AE@% statement can jump anywhere within the current function. %@NL@% %@NL@% A common use of %@AB@%goto%@AE@% is to exit immediately from a deeply nested loop. For instance: %@NL@% %@NL@% %@AS@% for( ... ) %@AS@% { %@AS@% for( ... ) %@AS@% { %@AS@% /* Do something here */ %@AS@% if(c == CTRL_C) %@AS@% goto myplace; %@AS@% } %@AS@% /* Do something else here */ %@AS@% } %@AS@% %@AS@% /* The goto label is named myplace */ %@AS@% myplace: %@AS@% /* The goto statement transfers control here */%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0012 @%%@AB@%The if Statement%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%if%@AE@% statement performs a branch based on the outcome of a conditional test. If the test expression is true, the body of the %@AB@%if%@AE@% statement executes. If it is false, the statement body is skipped. %@NL@% %@NL@% The %@AB@%else%@AE@% keyword is used with %@AB@%if%@AE@% to form an either-or construct that executes one statement when the test expression is true and another when it's false. C does not offer an "else-if" keyword. You can combine %@AB@%if%@AE@% and %@AB@%else%@AE@% statements to achieve the same effect. C pairs each %@AB@%else%@AE@% with the most recent %@AB@%if%@AE@% that lacks an %@AB@%else%@AE@%. %@NL@% %@NL@% Below is a simple %@AB@%if%@AE@% statement: %@NL@% %@NL@% %@AS@% if( score < 70 ) %@AS@% grade = 'F'; %@AS@% else %@AS@% grade = 'P';%@AE@%%@NL@% %@NL@% If the value of the variable %@AS@% score %@AE@% is less than 70, the variable %@AS@% grade %@AE@% is set to the constant %@AS@% F%@AE@%. Otherwise, %@AS@% score %@AE@% is set to %@AS@% P%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0013 @%%@AB@%The return Statement%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%return%@AE@% statement ends the execution of the function in which it appears. It can also return a value to the calling function. For example: %@NL@% %@NL@% %@AS@% return; /* End function and return no value */ %@AS@% %@AS@% return myvariable; /* End function and return value of myvariable */%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0014 @%%@AB@%The switch Statement%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%switch%@AE@% statement allows you to branch to various sections of code based on the value of a single variable. This variable must evaluate to a %@AB@%char%@AE@%, %@AB@%int%@AE@%, or %@AB@%long%@AE@% constant. %@NL@% %@NL@% Each section of code in the %@AB@%switch%@AE@% statement is marked with a case label─the keyword %@AB@%case%@AE@% followed by a constant or constant expression. The value of the %@AB@%switch%@AE@% test expression is compared to the constant in each case label. If a match is found, control transfers to the statement after the matching label and continues until you reach a %@AB@%break%@AE@% statement or the end of the %@AB@%switch%@AE@% statement. %@NL@% %@NL@% For example: %@NL@% %@NL@% %@AS@% switch( answer ) %@AS@% { %@AS@% case 'y': /* First case */ %@AS@% printf( "lowercase y\n" ); %@AS@% break; %@AS@% %@AS@% case 'n': /* Another case */ %@AS@% printf( "lowercase n\n" ); %@AS@% break; %@AS@% %@AS@% default: /* Default case */ %@AS@% printf( "not a lowercase y or n\n" ); %@AS@% break; %@AS@% }%@AE@%%@NL@% %@NL@% The example tests the value of the variable %@AS@% answer%@AE@%. If %@AS@% answer %@AE@% evaluates to the constant %@AS@% 'y'%@AE@%, control transfers to the first case in the %@AB@%switch%@AE@% statement. If it equals %@AS@% 'n'%@AE@%, control transfers to the second case. %@NL@% %@NL@% A case labelled with the %@AB@%default%@AE@% keyword executes when none of the other case constants matches the value of the %@AB@%switch%@AE@% test expression. In the example, the %@AB@%default%@AE@% case executes when %@AS@% answer %@AE@% equals any value other than %@AS@% 'y' %@AE@% or %@AS@% 'n'%@AE@%. %@NL@% %@NL@% If you omit the %@AB@%break%@AE@% statement at the end of a case, execution falls through to the next case. %@NL@% %@NL@% If you omit the %@AB@%default%@AE@% case and no matching case is found, nothing in the %@AB@%switch%@AE@% statement executes. %@NL@% %@NL@% No two %@AB@%case%@AE@% constants in the same %@AB@%switch%@AE@% statement can have the same value. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0015 @%%@AB@%The while Statement%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%while%@AE@% statement repeats a statement until its test expression becomes false. A %@AB@%while%@AE@% loop evaluates its test expression before executing its loop body. If the test expression is false when the loop begins, the loop body never executes. (Contrast this behavior with the %@AB@%do%@AE@% loop, which always executes its loop body at least once.) %@NL@% %@NL@% For example: %@NL@% %@NL@% %@AS@% while( !sample ) /* Repeat until sample equals 1 */ %@AS@% { %@AS@% printf( "%d\t%d\n", x, x*x ); %@AS@% x += 6; %@AS@% if( x > 20 ) %@AS@% sample = 1; %@AS@% }%@AE@%%@NL@% %@NL@% You can exit a %@AB@%while%@AE@% loop early with a %@AB@%break%@AE@% or %@AB@%goto%@AE@% statement. The %@AB@%continue%@AE@% statement skips to the next iteration of the loop. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-A0016 @%%@AB@%Data Types%@AE@%%@EH@%%@NL@% %@NL@% Data types are explained in Chapter 4, "Data Types," and Chapter 5, "Advanced Data Types." A brief description is given here. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0017 @%%@AB@%Basic Data Types%@AE@%%@EH@%%@NL@% %@NL@% The basic data types in C are character (%@AB@%char%@AE@%), integer (%@AB@%int%@AE@%), and floating point (%@AB@%float%@AE@% and %@AB@%double%@AE@%). All other data types are derived from these basic types. For example, a string is an array of %@AB@%char%@AE@% values. %@NL@% %@NL@% Table A.1 lists the range of values for each data type. %@NL@% %@NL@% %@AB@%Table A.1 %@AB@%Basic Data Types%@AE@%%@AE@% %@TH: 38 1806 02 17 29 30 @%Type Name Other Names Range of Values%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%char%@AE@% %@AB@%signed char%@AE@% -128 to 127%@AB@%unsigned char%@AE@% none 0 to 255%@AB@%int%@AE@% %@AB@%signed%@AE@%, %@AB@%signed int%@AE@% -32,768 to 32,767%@AB@%unsigned%@AE@% %@AB@%unsigned int%@AE@% 0 to 65,535%@AB@%unsigned short%@AE@% %@AB@%unsigned short int%@AE@% 0 to 65,535%@AB@%short%@AE@% %@AB@%short int%@AE@%, %@AB@%signed short%@AE@% -32,768 to %@AB@%signed short int%@AE@% 32,767%@AB@%long%@AE@% %@AB@%long int%@AE@%, %@AB@%signed long%@AE@% -2,147,483,647 to %@AB@%signed long int%@AE@% 2,147,483,648%@AB@%unsigned long%@AE@% %@AB@%unsigned long int%@AE@% 0 to 4,294,967,295%@AB@%_segment%@AE@% none 0 to 65,535%@AB@%enum%@AE@% none -32,768 to 32,767%@AB@%float%@AE@% none Approximately 1.2E-38 to 3.4E+38 (7-digit precision)%@AB@%double%@AE@% none Approximately 2.2E-308 to 1.8E+308 (15-digit precision)%@AB@%long double%@AE@% none Approximately 3.4E-4932 to 1.2E+4932 (19-digit precision)%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 38 1806 02 17 29 30 @% %@NL@% %@4@%%@AB@%Character Type%@AE@%%@EH@%%@NL@% %@NL@% The character type (%@AB@%char%@AE@%) occupies one byte of storage and can express a whole number in the range of -128 to 127. Unsigned characters have a range of 0 to 255. You can represent any ASCII character as an %@AB@%unsigned char%@AE@% value. %@NL@% %@NL@% Typical declarations of character types are shown below: %@NL@% %@NL@% %@AS@% char answer; /* Declare a character variable answer */ %@AS@% %@AS@% char alpha = 'a'; /* Declare character variable alpha %@AS@% and initialize it */%@AE@%%@NL@% %@NL@% A character constant represents a single ASCII character. Typical character constants are shown below: %@NL@% %@NL@% %@AS@% char alpha = 'a'; /* Declare and initialize */ %@AS@% %@AS@% char c2 = 0x61; /* Declare and initialize with %@AS@% hexadecimal value for 'a' */%@AE@%%@NL@% %@NL@% %@AB@%Escape Sequences%@AE@% - Escape sequences represent special characters, such as the carriage return. An escape sequence consists of a backslash character plus a letter or punctuation mark. Table A.2 lists the C escape sequences; they are also listed in online help.%@NL@% %@NL@% %@AB@%Table A.2 %@AB@%C Escape Sequences%@AE@%%@AE@% %@TH: 14 834 02 11 22 43 @%Character Meaning Hexadecimal Value%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%\a%@AE@% Alert (bell) 0x07%@AB@%\n%@AE@% New line (linefeed) 0x0A%@AB@%\b%@AE@% Backspace 0x08%@AB@%\r%@AE@% Carriage return 0x0D%@AB@%\f%@AE@% Formfeed 0x0C%@AB@%\t%@AE@% Tab 0x09%@AB@%\v%@AE@% Vertical tab 0x0B%@AB@%\\%@AE@% Backslash 0x5C%@AB@%\%@AS@%'%@AE@%%@AE@% Single quote 0x27%@AB@%\"%@AE@% Double quote 0x22%@AB@%\0%@AE@% Null 0x00%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 14 834 02 11 22 43 @% %@NL@% %@4@%%@AB@%Integer Type%@AE@%%@EH@%%@NL@% %@NL@% The integer (%@AB@%int%@AE@%) type occupies two bytes of storage and can express a whole number in the range -32,768 to 32,767. Unsigned integers (%@AB@%unsigned%@AE@% or %@AB@%unsigned int%@AE@%) have a range of 0 to 65,535. %@NL@% %@NL@% In QuickC, short integers (%@AB@%short%@AE@% or %@AB@%short int%@AE@%) are the same as integers (%@AB@%int%@AE@%). Note that the %@AB@%short%@AE@% and %@AB@%int%@AE@% types are not the same in some operating systems other than DOS. %@NL@% %@NL@% Signed long integers (%@AB@%long%@AE@%) occupy four bytes and have a range of -2,147,483,648 to 2,147,483,647. Unsigned long integers have a range of 0 to 4,294,967,295. %@NL@% %@NL@% Integer variables are declared with the keywords %@AB@%int%@AE@%, %@AB@%short%@AE@%, %@AB@%unsigned%@AE@%, or %@AB@%long%@AE@%. Typical declarations of integer types are shown below: %@NL@% %@NL@% %@AS@% int z; /* Declare an int variable z */ %@AS@% %@AS@% int ten = 10; /* Declare int variable and %@AS@% assign it the value 10 */ %@AS@% %@AS@% unsigned int a; /* Declare unsigned int variable */ %@AS@% %@AS@% unsigned long BigInt = 2000000001UL; /* Declare and %@AS@% initialize */%@AE@%%@NL@% %@NL@% Integer constants are used to represent decimal, octal, and hexadecimal numbers. There are three types of integer constants: %@NL@% %@NL@% %@NL@% 1. Decimal constants can only contain the digits 0-9. The first digit must not be 0.%@NL@% %@NL@% 2. Octal constants can only contain the digits 0-7. The first digit must be 0.%@NL@% %@NL@% 3. Hexadecimal constants can only contain the digits 0-9, plus the letters a-f or A-F. The constant must begin with either 0x or 0X.%@NL@% %@NL@% %@NL@% You can specify that an integer constant is long by adding the suffix %@AB@%l%@AE@% or %@AB@%L%@AE@%. The suffix can be used with decimal, hexadecimal, or octal notation. %@NL@% %@NL@% To specify that an integer constant is short, add the suffix %@AB@%u%@AE@% or %@AB@%U%@AE@%. This suffix can also be used with decimal, hexadecimal, or octal notation. %@NL@% %@NL@% Typical integer constants are shown below: %@NL@% %@NL@% %@AS@% 42 /* Decimal constant */ %@AS@% %@AS@% 0x34 /* Hexadecimal constant */ %@AS@% %@AS@% 0x3cL /* Long hexadecimal constant */%@AE@%%@NL@% %@NL@% %@AS@% 052 /* Octal constant */%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Floating-Point Types%@AE@%%@EH@%%@NL@% %@NL@% You can declare floating-point variables using the keywords %@AB@%float%@AE@% or %@AB@%double%@AE@%. The %@AB@%float%@AE@% type occupies four bytes of storage and can express a floating-point value in the range 1.2E-38 to 3.4E+38. This type has seven-digit precision. %@NL@% %@NL@% The %@AB@%double%@AE@% type occupies eight bytes of storage and can express a floating-point value in the range 2.2E-308 to 1.8E+308. This type has fifteen-digit precision. %@NL@% %@NL@% The %@AB@%long double%@AE@% type occupies ten bytes of storage and can express a floating-point value in the range 3.4E-4932 to 1.2E+4932. This type has nineteen-digit precision. %@NL@% %@NL@% Typical declarations of floating-point types are shown below: %@NL@% %@NL@% %@AS@% float SmallPi = 3.14; /* Declare floating-point variable */ %@AS@% %@AS@% double AccuratePi = 3.141592653596 /* Declare %@AS@% double-precision */%@AE@%%@NL@% %@NL@% Floating-point constants can represent decimal numbers in either single or double precision. A floating-point constant must either contain a decimal point or end with the suffix %@AB@%e%@AE@% or %@AB@%E%@AE@%. Typical floating-point constants are shown below: %@NL@% %@NL@% %@AS@% 2.78 /* Floating-point constant */ %@AS@% %@AS@% 3E /* Floating-point constant */%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0018 @%%@AB@%Aggregate Data Types%@AE@%%@EH@%%@NL@% %@NL@% Aggregate data types are built from one or more of the basic data types. These include the following: %@NL@% %@NL@% %@NL@% ■ Arrays (including strings)%@NL@% %@NL@% ■ Structures%@NL@% %@NL@% ■ Unions%@NL@% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Arrays and Strings%@AE@%%@EH@%%@NL@% %@NL@% An "array" is a collection of data elements of a single type. An array can contain any data type. You can access an element of an array by using the array name and a numeric subscript. %@NL@% %@NL@% A "string" is an array of characters that terminates with the null character (%@AB@%\0%@AE@%). Arrays that contain strings must allow space for the final null character. %@NL@% %@NL@% Typical arrays and strings are shown below: %@NL@% %@NL@% %@AS@% int id_number[10]; /* One-dimensional; %@AS@% 10 elements; integer */ %@AS@% %@AS@% char name[30]; /* String */ %@AS@% %@AS@% float matrix[5][3]; /* Two-dimensional array, %@AS@% 5 rows, 3 columns */ %@AS@% %@AS@% char baby[30] = "Peter Roddy"; /* String initialization */%@AE@%%@NL@% %@NL@% %@NL@% %@4@%%@AB@%Structures%@AE@%%@EH@%%@NL@% %@NL@% A "structure" is a collection of data items of different types. Once you have defined a structure type, you can declare a structure variable using that type. %@NL@% %@NL@% The following example illustrates a simple structure: %@NL@% %@NL@% %@AS@% struct date %@AS@% { %@AS@% int month; %@AS@% int day; %@AS@% int year; %@AS@% } %@AS@% %@AS@% struct date today;%@AE@%%@NL@% %@NL@% The example defines a structure type named %@AS@% date %@AE@% and declares a structure variable %@AS@% today %@AE@% to be of type %@AS@% date%@AE@%. %@NL@% %@NL@% Use the structure-member operator ( . ) to access the "elements" (members) of a structure. The name %@NL@% %@NL@% %@AS@% today.month%@AE@%%@NL@% %@NL@% refers to the %@AS@% month %@AE@% member of the %@AS@% today %@AE@% structure in the example. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Unions%@AE@%%@EH@%%@NL@% %@NL@% A "union" is a set of data items of different types sharing the same storage space in memory. One use of unions is accessing the computer's DOS registers. For instance, QuickC defines the union %@AB@%REGS%@AE@% as the following: %@NL@% %@NL@% %@AS@% union REGS %@AS@% { %@AS@% struct WORDREGS x; %@AS@% struct BYTEREGS h; %@AS@% };%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-A0019 @%%@AB@%Advanced Data Types%@AE@%%@EH@%%@NL@% %@NL@% Advanced data topics are explained in Chapter 5, "Advanced Data Types." A brief description of each topic is given here. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0020 @%%@AB@%Visibility%@AE@%%@EH@%%@NL@% %@NL@% Variables declared outside all functions are global and can be accessed anywhere in the current source file. Variables declared inside a function are local and can be accessed only in that function. Use the %@AB@%extern%@AE@% keyword to make a variable declared in another source file visible in the current source file. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0021 @%%@AB@%Lifetime%@AE@%%@EH@%%@NL@% %@NL@% Global variables, and local variables declared with the %@AB@%static%@AE@% keyword, exist for the lifetime of the program. Other local variables are "automatic;" they come into being when the function starts and evaporate when it ends. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0022 @%%@AB@%Type Conversions%@AE@%%@EH@%%@NL@% %@NL@% A type conversion occurs automatically when an expression mixes two different data types. QuickC converts the lower-ranking type to the higher-ranking type before it performs the specified operation. %@NL@% %@NL@% You can also "cast" (manually convert) a value to any type by placing the desired type name in parentheses in front of the value. The example below casts the value of %@AS@% sample %@AE@% to type %@AB@%float%@AE@% and assigns the value to %@AS@% x%@AE@%: %@NL@% %@NL@% %@AS@% int sample; %@AS@% float x; %@AS@% x = (float)sample;%@AE@%%@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0023 @%%@AB@%User-Defined Types%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%typedef%@AE@% keyword allows you to create user-defined types, which are synonyms for existing data types. User-defined types can make your program more readable. For example, a type called %@AS@% string %@AE@% may be easier to understand than a type called %@AB@%char *%@AE@%. %@NL@% %@NL@% A simple %@AB@%typedef%@AE@% declaration is shown below. The name of an existing type (%@AB@%long int%@AE@%) is followed by the synonym %@AS@% income%@AE@%. %@NL@% %@NL@% %@AS@% typedef long int income;%@AE@%%@NL@% %@NL@% Once you have created a new type name, you can use it wherever the original type name could be used: %@NL@% %@NL@% %@AS@% income net_income, gross_income;%@AE@%%@NL@% %@NL@% In the example above, the variables %@AS@% net_income %@AE@% and %@AS@% gross_income %@AE@% are of type %@AS@% income%@AE@%, which is the same as %@AB@%long int%@AE@%. %@NL@% %@NL@% %@NL@% %@3@%%@CR:C6A-A0024 @%%@AB@%Enumerated Types%@AE@%%@EH@%%@NL@% %@NL@% An enumerated type (declared with %@AB@%enum%@AE@%) has values limited to a specified set. If the %@AB@%enum%@AE@% declaration does not specify any values, QuickC assigns sequential integers to the enumeration identifiers beginning at zero. %@NL@% %@NL@% The example below assigns the values of 0, 1, and 2 to the enumeration identifiers %@AS@% zero%@AE@%, %@AS@% one%@AE@%, and %@AS@% two%@AE@%, respectively. It also creates an enumerated type %@AS@% small_numbers %@AE@% that can be used to declare other variables. %@NL@% %@NL@% %@AS@% /* Enumerated data type */ %@AS@% enum small_numbers {zero, one, two}; %@AS@% %@AS@% /* Variable my_numbers is of type small_numbers */ %@AS@% enum small_numbers my_numbers;%@AE@%%@NL@% %@NL@% The following example explicitly assigns values to the enumeration identifiers: %@NL@% %@NL@% %@AS@% /* Enumerated data type */ %@AS@% enum even_numbers { two = 2, four = 4, six = 6 };%@AE@%%@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-A0025 @%%@AB@%Operators%@AE@%%@EH@%%@NL@% %@NL@% C-language operators are explained in Chapter 6, "Operators." %@NL@% %@NL@% An "operand" is a constant or variable manipulated by an operator in an expression. An "operator" specifies how the operands in an expression are to be evaluated. Operators also produce a result that can be nested within a larger expression. %@NL@% %@NL@% C provides a rich set of operators covering everything from basic arithmetic operations to logical and bitwise operations. You can also combine the assignment operator (%@AB@%=%@AE@%) with any arithmetic or bitwise operator to form a combined assignment operator. %@NL@% %@NL@% C operators have two properties, precedence and associativity. You can change the normal order of evaluation by enclosing expressions in parentheses. %@NL@% %@NL@% Table A.3 lists the C operators and their precedence and associativity values. The lines in the table separate precedence levels. The highest precedence level is at the top of the table. %@NL@% %@NL@% %@AB@%Table A.3 %@AB@%C Operators%@AE@%%@AE@% %@TH: 114 4500 02 24 37 15 @%Symbol Name or Meaning Associativity%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%( ) Function call Left to right[ ] Array element %@AB@%.%@AE@% Structure or union member %@AB@%->%@AE@% Pointer to structure member %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%- -%@AE@% Decrement Right to left%@AB@%++%@AE@% Increment %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%:> Base operator Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%!%@AE@% Logical NOT Right to left%@AB@%~ %@AE@% One's complement%@AB@% %@AE@%%@AB@%-%@AE@% Unary minus %@AB@%+%@AE@% Unary plus %@AB@%&%@AE@% Address %@AB@%*%@AE@% Indirection %@AB@%sizeof%@AE@% Size in bytes %@AB@%(%@AE@%type%@AB@%)%@AE@% Type cast [for example, (%@AB@%float%@AE@%) i] %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%*%@AE@% Multiply Left to right%@AB@%/%@AE@% Divide %@AB@%%%@AE@% Modulus (remainder)%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%+%@AE@% Add Left to right%@AB@%-%@AE@% Subtract %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%<<%@AE@% Left shift Left to right%@AB@%>>%@AE@% Right shift %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%<%@AE@% Less than Left to right%@AB@%<=%@AE@% Less than or equal to %@AB@%>%@AE@% Greater than %@AB@%>=%@AE@% Greater than or equal to %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%==%@AE@% Equal Left to right%@AB@%!=%@AE@% Not equal %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%&%@AE@% Bitwise AND Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%^%@AE@% Bitwise exclusive OR Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%|%@AE@% Bitwise OR Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%&&%@AE@% Logical AND Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%||%@AE@% Logical OR Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%? : %@AE@% Conditional Right to left%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%=%@AE@% Assignment Right to left%@AB@%*=, /=, %=, +=, -=%@AE@% Compound assignment%@AB@%<<=, >>=, &=, ^=, |=%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%,%@AE@% Comma Left to right%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 114 4500 02 24 37 15 @% %@NL@% %@2@%%@CR:C6A-A0026 @%%@AB@%Preprocessor Directives%@AE@%%@EH@%%@NL@% %@NL@% Preprocessor directives are explained in Chapter 7, "Preprocessor Directives." %@NL@% %@NL@% A "preprocessor directive" is a command to the QuickC compiler, which processes all such commands before it compiles your source program. A preprocessor directive begins with the %@AB@%#%@AE@% symbol, followed by the directive and any arguments the directive needs. Since a preprocessor directive is not a C language statement, it doesn't end in a semicolon. %@NL@% %@NL@% The two most commonly used directives are %@AB@%#define%@AE@% and %@AB@%#include%@AE@%. Use the %@AB@%#define%@AE@% directive to give a meaningful name to some constant in your program. The following directive tells QuickC to replace %@AS@% PI %@AE@% with %@AS@% 3.14159 %@AE@% everywhere in the source program: %@NL@% %@NL@% %@AS@% #define PI 3.14159%@AE@%%@NL@% %@NL@% The %@AB@%#include%@AE@% directive below tells QuickC to insert the contents of a specified file at the current location in your source program. %@NL@% %@NL@% %@AS@% #include <stdio.h> /* Standard header file */%@AE@%%@NL@% %@NL@% Such files are called "include files" or "header files." Standard header files, such as STDIO.H, end with the .H extension and contain function prototypes and other definitions needed for QuickC library routines. %@NL@% %@NL@% Table A.4 lists and describes the QuickC standard header files. Consult online help for information on the header files needed by individual library functions. %@NL@% %@NL@% %@AB@%Table A.4 %@AB@%QuickC Header Files%@AE@%%@AE@% %@TH: 73 2606 02 34 42 @%File Name Major Contents%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%ASSERT.H %@AB@%assert%@AE@% debugging macroBIOS.H BIOS service functionsCONIO.H Console and port I/O routinesCTYPE.H Character classificationDIRECT.H Directory controlDOS.H MS-DOS interface functionsERRNO.H System-wide error numbersFCNTL.H Flags used in %@AB@%open%@AE@% and %@AB@%sopen%@AE@% functionsFLOAT.H Constants needed by math functionsGRAPH.H Low-level graphics and font routinesIO.H File-handling and low-level I/OLIMITS.H Ranges of integers and character typesLOCALE.H Internationalization functionsMALLOC.H Memory-allocation functionsMATH.H Floating-point math routinesMEMORY.H Buffer-manipulation routinesPGCHART.H Presentation graphicsPROCESS.H Process-control routinesSEARCH.H Searching and sorting functionsSETJMP.H %@AB@%setjmp%@AE@% and %@AB@%longjmp%@AE@% functionsSHARE.H Flags used in %@AB@%sopen%@AE@%SIGNAL.H Constants used by signal functionSTDARG.H Macros used to access variable-length argument-list functionsSTDDEF.H Commonly used data types and valuesSTDIO.H Standard I/O header fileSTDLIB.H Commonly used library functionsSTRING.H String-manipulation functionsTIME.H General time functionsVARARGS.H Variable-length argument-list functionsSYS\LOCKING.H Flags used by %@AB@%locking%@AE@% functionSYS\STAT.H File-status structures and functionsSYS\TIMEB.H %@AB@%time%@AE@% functionSYS\TYPES.H File-status and time typesSYS\UTIME.H %@AB@%utime%@AE@% function%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 73 2606 02 34 42 @% %@NL@% %@2@%%@CR:C6A-A0027 @%%@AB@%Pointers%@AE@%%@EH@%%@NL@% %@NL@% Pointers are described in Chapter 8, "Pointers," and Chapter 9, "Advanced Pointers." %@NL@% %@NL@% A "pointer" is a variable that contains the memory address of an item rather than its value. A pointer can point to any type of data item or to a function. The following code illustrates pointer declarations: %@NL@% %@NL@% %@AS@% int *intptr; /* Pointer to an integer */ %@AS@% char *name; /* Pointer to char */%@AE@%%@NL@% %@NL@% The following operators are used with pointers: %@NL@% %@NL@% %@NL@% ■ The indirection operator (%@AB@%*%@AE@%) has two uses. In a declaration, it means that the declared item is a pointer. In an expression, it denotes the data being pointed to.%@NL@% %@NL@% ■ The address-of operator (%@AB@%&%@AE@%) yields the memory address at which an item is stored.%@NL@% %@NL@% %@NL@% You can perform four arithmetic operations on pointers: %@NL@% %@NL@% %@NL@% 1. Adding a pointer and an integer%@NL@% %@NL@% 2. Subtracting an integer from a pointer%@NL@% %@NL@% 3. Subtracting two pointers%@NL@% %@NL@% 4. Comparing two pointers%@NL@% %@NL@% %@NL@% Pointer arithmetic operations are automatically scaled by the size of the object pointed to. For instance, adding 1 to a pointer to a %@AB@%float%@AE@% item causes the address stored in the pointer to be incremented four bytes, the size of one %@AB@%float%@AE@% item. %@NL@% %@NL@% QuickC 2.5 also supports based pointers, a highly advanced feature, that are compatible with Microsoft C version 6.0. Please refer to your C 6.0 documentation for more information about based pointers and objects. %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A-B0001 @%%@1@%%@AB@%Appendix B C Library Guide%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@NL@% This appendix outlines the features of the C run-time library provided with QuickC. It does not intend to be a complete presentation of the complete C run-time library. Instead, this appendix presents the most fundamental routines, grouped by category so you can begin experimenting with C and with QuickC. %@NL@% %@NL@% Remember, use online help to get instant help on any topic of interest. The online help system provided with QuickC provides complete reference information for all C library functions, keywords, and preprocessor directives. %@NL@% %@NL@% %@NL@% %@2@%%@CR:C6A-B0002 @%%@AB@%Overview of the C Run-Time Library%@AE@%%@EH@%%@NL@% %@NL@% At last count, the C run-time library contained over 400 functions to use in C programs. This appendix describes the major categories of functions included in the library and, within those categories, the fundamental routines every C programmer should know. %@NL@% %@NL@% The discussions of these categories give only a brief overview of the capabilities of the run-time library. You can find a complete description of the syntax and use of each routine in online help. %@NL@% %@NL@% The routines in the C run-time library are divided into the following categories: %@NL@% %@NL@% %@AB@%Table B.1 %@AB@%C Run-Time Library Routines%@AE@%%@AE@% %@TH: 131 7080 02 32 35 09 @%Category Function Routines Page%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%Buffer Manipulation%@AE@% memchr, memcmp, memcpy, memmove, 345 memset %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%Character Classification%@AE@% isalnum, isalpha, isascii, 346%@AB@%and Conversion%@AE@% iscntrl, isdigit, isgraph, islower, isprint, ispunct, isspace, isupper, isxdigit, tolower, toupper %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%Data Conversion%@AE@% atof, atoi, atol, itoa, ltoa, 348 ultoa, strtod, strtol, strtoul %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%Error Message%@AE@% assert, perror, strerror, 349 _strerror %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%Graphics 1: Low-Level%@AE@% 350%@AB@% Graphics%@AE@% Configure Mode and _displaycursor, _getvideoconfig, 351 Environment _setvideomode Set Coordinates _getcurrentposition, 352 _getphyscoord,_getviewcoord, _getwindowcoord, _setcliprgn,_setvieworg, _setviewport, _setwindow Set Palette _remapallpalette, remappallette, 354 _selectpalette Set Attributes _getbkcolor, _getcolor, 355 _setbkcolor, _setcolor Output Images _arc, _clearscreen, _ellipse, 356 _floodfill, _getpixel, _lineto, _moveto, _pie, _rectangle, _setpixel Output Text _displaycursor, _gettextcolor, 359 _gettextcursor, _gettextposition, _outtext, _settextposition, _settextcolor, _settextwindow Transfer Images _getimage, _imagesize, _putimage 361%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%Graphics 2: Presentation%@AE@% _pg_chart, _pg_chartms, 362%@AB@% Graphics%@AE@% _pg_chartpie, _pg_chartscatter, _pg_chartscatterms, _pg_defaultchart, _pg_initchart %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%Graphics 3: Font Display%@AE@% _getfontinfo, _getgtextextent, 365 _outgtext, _registerfonts, _setfont, _unregisterfonts %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%Input and Output%@AE@% 367Stream Routines clearerr, fclose, feof, ferror, 367 fflush, fgetc, fgetpos, fgets, fopen, fprintf, fputc, fputs, fread, freopen, fscanf, fseek, fsetpos, ftell, fwrite, getc, getchar, gets, printf, putc, putchar, puts, rewind, scanf, sprintf, sscanf, tmpfile, tmpnam, ungetc Low-Level Routines close, creat, eof, lseek, open, 373 read, tell, write Console and Port cgets, cprintf, cputs, cscanf, 375 I/O Routines getch, getche, kbhit, putch, ungetch %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%Math%@AE@% abs, fabs, labs, acos, asin, atan, 377 atan2, ceil, cos, cosh, exp, floor, fmod, frexp, ldexp, log, log10, modf, pow, rand, srand, sin, sinh, sqrt, tan, tanh %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%Memory Allocation%@AE@% calloc, free, _ffree, hfree, 381 _nfree, malloc, _fmalloc, _nmalloc, realloc %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%Process Control%@AE@% abort, atexit, exit, _exit, 383 system %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%Searching and Sorting%@AE@% bsearch, lfind, lsearch, qsort 384%@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%String Manipulation%@AE@% strcat, strcpy, strdup, strncat, 385 strncpy, strchr, strcspn, strpbrk, strrchr, strspn, strstr, strcmp, strcmpi, stricmp, strncmp, strnicmp, strlen, strlwr, strupr, strnset, strset, strtok %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@AB@%Time%@AE@% asctime, clock, ctime, difftime, 389 ftime, gmtime, mktime, time %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@TE: 131 7080 02 32 35 09 @% %@NL@% %@2@%%@CR:C6A-B0003 @%%@AB@%Buffer-Manipulation Routines%@AE@%%@EH@%%@NL@% %@NL@% Buffer manipulation routines are used with areas of memory on a character-by-character basis. Buffers are arrays of characters (bytes). Unlike strings, however, they are not usually terminated with a null character (%@AB@%\0%@AE@%). %@NL@% %@NL@% %@AB@%memchr%@AE@% - Returns a pointer to the first occurrence, within a specified number of characters, of a given character in the buffer.%@NL@% %@NL@% %@AB@%Include%@AE@% STRING.H %@AB@%Prototype%@AE@% %@AB@%void *memchr( const void *%@AE@%%@AI@%buf%@AE@%%@AB@%, int%@AE@% %@AI@%c%@AE@%%@AB@%, %@AE@% %@AB@%size_t%@AE@% %@AI@%count %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%buf%@AE@% Pointer to buffer %@AI@%c%@AE@% Character to copy %@AI@%count%@AE@% Number of characters %@AB@%Returns%@AE@% A pointer to the location of %@AI@%c%@AE@% in %@AI@%buf%@AE@% if successful; %@AB@%NULL%@AE@% if %@AI@%c%@AE@% is not within first %@AI@%count%@AE@% bytes of %@AI@%buf%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%memcmp%@AE@% - Compares a specified number of characters from two buffers.%@NL@% %@NL@% %@AB@%Include%@AE@% STRING.H %@AB@%Prototype%@AE@% %@AB@%int memcmp( const void *%@AE@%%@AI@%buf1%@AE@%%@AB@%,%@AE@% %@AB@%const %@AE@% %@AB@%void%@AE@% *%@AI@%buf2%@AE@%%@AB@%, size_t %@AE@%%@AI@%count %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%buf1%@AE@% First buffer %@AI@%buf2%@AE@% Second buffer %@AI@%count%@AE@% Number of characters %@AB@%Returns%@AE@% A negative value if %@AI@%buf1%@AE@% < %@AI@%buf2%@AE@%, 0 if %@AI@%%@AE@% %@AI@%buf1%@AE@% = %@AI@%buf2%@AE@%, a positive value if %@AI@%buf1%@AE@% > %@AI@%buf2%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%memcpy%@AE@% - Copies a specified number of characters from one buffer to another.%@NL@% %@NL@% %@AB@%Include%@AE@% STRING.H %@AB@%Prototype%@AE@% %@AB@%void%@AE@% %@AB@%*memcpy( void *%@AE@%%@AI@%dest%@AE@%%@AB@%, const void *%@AE@%%@AI@%%@AE@% %@AI@%src%@AE@%%@AB@%, size_t %@AE@%%@AI@%count %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%dest%@AE@% New buffer %@AI@%src%@AE@% Buffer to copy from %@AI@%count%@AE@% Number of characters to copy %@AB@%Returns%@AE@% A pointer to %@AI@%dest%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%memmove%@AE@% - Copies a specified number of characters from one buffer to another. When the source and target areas overlap, the %@AB@%memmove%@AE@% function is guaranteed to properly copy the full source. %@NL@% %@NL@% %@AB@%Include%@AE@% STRING.H %@AB@%Prototype%@AE@% %@AB@%void *memmove( void *%@AE@%%@AI@%dest%@AE@%%@AB@%, const void *%@AE@% %@AI@%src%@AE@%%@AB@%, size_t %@AE@%%@AI@%count %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%dest%@AE@% Target object %@AI@%src%@AE@% Source object %@AI@%count%@AE@% Number of characters to copy %@AB@%Returns%@AE@% The value of %@AI@%dest%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%memset%@AE@% - Uses a given character to initialize a specified number of bytes in the buffer.%@NL@% %@NL@% %@AB@%Include%@AE@% STRING.H %@AB@%Prototype%@AE@% %@AB@%void *memset( void *%@AE@%%@AI@%dest%@AE@%%@AB@%, int %@AE@%%@AI@%c%@AE@%%@AB@%, size_t%@AE@% %@AB@%%@AE@%%@AI@%count %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%dest%@AE@% Pointer to destination %@AI@%c%@AE@% Character to set %@AI@%count%@AE@% Number of characters %@AB@%Returns%@AE@% A pointer to%@AI@% dest%@AE@% %@NL@% %@2@%%@CR:C6A-B0004 @%%@AB@%Character Classification and Conversion Routines%@AE@%%@EH@%%@NL@% %@NL@% The classification routines (%@AB@%is...%@AE@%) test a character and return a one (1) if the character is in the set that the routine is testing for. The conversion routines (%@AB@%to...%@AE@%) convert characters between uppercase and lowercase. These routines are generally faster than writing a test expression such as the following: %@NL@% %@NL@% %@AS@% if ((c >= 0) || c <= 0x7f))%@AE@%%@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%isalnum, isalpha, isascii, iscntrl, isdigit, isgraph, islower, isprint, %@AB@%ispunct, isspace, isupper, isxdigit%@AE@% These routines test a character for a specified condition and return a nonzero value if the condition is true. - %@NL@% %@NL@% %@AB@%Include%@AE@% CTYPE.H %@AB@%Prototypes%@AE@% %@AB@%int isalnum( int %@AE@%%@AI@%c %@AE@%%@AB@%);%@AE@% (alphanumeric character: A-Z, a-z, 0-9) %@AB@%%@AE@% int isalpha( int %@AI@%c %@AE@%%@AB@%);%@AE@% (alphabetic character: A-Z%@AB@%,%@AE@% a-z)%@AB@%%@AE@% int isascii( int %@AI@%c %@AE@%%@AB@%);%@AE@% (ASCII character: 0x00-0x7F)%@AB@%%@AE@% int iscntrl( int %@AI@%c%@AE@%%@AB@% );%@AE@% (control character: 0x00-0x1F, 0x7F)%@AB@%%@AE@% int isdigit( int %@AI@%c %@AE@%%@AB@%); %@AE@% (decimal digit: 0-9) %@AB@%%@AE@% int isgraph( int %@AI@%c%@AE@%%@AB@% );%@AE@% (printable character, not space: 0x21-0x7E) %@AB@%%@AE@% int islower( int %@AI@%c %@AE@%%@AB@%); %@AE@% (lowercase letter: a-z)%@AB@%%@AE@% int isprint( int %@AI@%c %@AE@%%@AB@%);%@AE@% (printable character: 0x20-0x7E)%@AB@%%@AE@% int ispunct( int %@AI@%c %@AE@%%@AB@%);%@AE@% (punctuation character)%@AB@%%@AE@% int isspace( int %@AI@%c %@AE@%%@AB@%);%@AE@% (white-space character: 0x09-0x0D, 0x20) %@AB@%int isupper( int %@AE@%%@AI@%c %@AE@%%@AB@%);%@AE@% (uppercase letter: A-Z)%@AB@%%@AE@% int isxdigit( int %@AI@%c %@AE@%%@AB@%);%@AE@% (hexadecimal digit: A-F, a-f, 0-9) %@AB@%Argument%@AE@% %@AI@%c%@AE@% Character to be tested %@AB@%Returns%@AE@% A nonzero value if the condition is true ──────────────────────────────────────────────────────────────────────────── %@AB@%tolower, toupper%@AE@% - These routines accept a character argument and return a converted character. The %@AB@%tolower%@AE@% and %@AB@%toupper%@AE@% routines are also implemented as functions. To use the function versions, you must do the following:%@NL@% %@NL@% %@NL@% ■ Include CTYPE.H if necessary for other macro definitions%@NL@% %@NL@% ■ If CTYPE.H is included, give %@AB@%#undef%@AE@% directives for %@AB@%tolower%@AE@% and %@AB@%toupper%@AE@%%@NL@% %@NL@% ■ Include STDLIB.H (which contains the function prototypes)%@NL@% %@NL@% %@NL@% %@AB@%Include%@AE@% CTYPE.H %@AB@%Prototypes%@AE@% %@AB@%int tolower( int %@AE@%%@AI@%c %@AE@%%@AB@%);%@AE@% int toupper( int %@AI@%c %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%c%@AE@% Character to be converted %@AB@%Returns%@AE@% tolower: the lowercase equivalent of %@AI@%c%@AE@% only if %@AI@%c%@AE@% is an uppercase letter %@AB@%toupper%@AE@%: the uppercase equivalent of %@AI@%c%@AE@% only if %@AI@%c%@AE@% is a lowercase letter %@NL@% %@2@%%@CR:C6A-B0005 @%%@AB@%Data Conversion Routines%@AE@%%@EH@%%@NL@% %@NL@% The data conversion routines convert numbers to strings of ASCII characters and vice versa. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%atof, atoi, atol%@AE@% - These ASCII-to-number routines convert an ASCII string to a %@AB@%float%@AE@%, an %@AB@%integer%@AE@%, and a %@AB@%long%@AE@%, respectively.%@NL@% %@NL@% %@AB@%Include%@AE@% STDLIB.H or MATH.H (%@AB@%atof%@AE@%) STDLIB.H (%@AB@%atoi%@AE@%, %@AB@%atol%@AE@%) %@AB@%Prototypes%@AE@% %@AB@%double atof( const char *%@AE@%%@AI@%string%@AE@%%@AB@% );%@AE@% %@AB@%int atoi( const char%@AE@% %@AB@%*%@AE@%%@AI@%string %@AE@%%@AB@%);%@AE@% long atol( const char *%@AI@%string %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%string%@AE@% String to be converted %@AB@%Returns%@AE@% The converted string, or 0 if %@AI@%string%@AE@% cannot be converted ──────────────────────────────────────────────────────────────────────────── %@AB@%itoa, ltoa, ultoa%@AE@% - These number-to-ASCII routines convert an integer, a long value, or an unsigned long value to an ASCII string.%@NL@% %@NL@% %@AB@%Include%@AE@% STDLIB.H %@AB@%Prototypes%@AE@% %@AB@%char * itoa( int %@AE@%%@AI@%value%@AE@%%@AB@%, char *%@AE@%%@AI@%string%@AE@%%@AB@%, %@AE@% %@AB@%int %@AE@%%@AI@%radix %@AE@%%@AB@%);%@AE@% char * ltoa( long %@AI@%value%@AE@%%@AB@%, char *%@AE@%%@AI@%string%@AE@%%@AB@%, %@AE@% %@AB@%int %@AE@%%@AI@%radix %@AE@%%@AB@%);%@AE@% char * ultoa( unsigned long %@AI@%value%@AE@%%@AB@%, char %@AE@% %@AB@%*%@AE@%%@AI@%string%@AE@%%@AB@%, int %@AE@%%@AI@%radix%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%value%@AE@% Number to be converted %@AI@%string%@AE@% String result %@AI@%radix%@AE@% Number base of value %@AB@%Returns%@AE@% A pointer to %@AI@%string%@AE@%; there is no error return ──────────────────────────────────────────────────────────────────────────── %@AB@%strtod, strtol, strtoul%@AE@% - These routines convert a string to a %@AB@%double%@AE@%, a %@AB@%long%@AE@%, and an %@AB@%unsigned long%@AE@%, respectively.%@NL@% %@NL@% %@AB@%Include%@AE@% STDLIB.H %@AB@%Prototypes%@AE@% %@AB@%double strtod( const char *%@AE@%%@AI@%nptr%@AE@%%@AB@%, char %@AE@% %@AB@%**%@AE@%%@AI@%endptr %@AE@%%@AB@%);%@AE@% long strtol( const char *%@AI@%nptr%@AE@%%@AB@%, char **%@AE@%%@AI@%%@AE@% %@AI@%endptr%@AE@%%@AB@%, int %@AE@%%@AI@%base%@AE@%%@AB@% );%@AE@% unsigned long strtoul( const char *%@AI@%nptr%@AE@%%@AB@%,%@AE@% %@AB@%char **%@AE@%%@AI@%endptr%@AE@%%@AB@%, int %@AE@%%@AI@%base%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%nptr%@AE@% String to convert %@AI@%endptr%@AE@% End of scan %@AI@%base%@AE@% Number base to use %@AB@%Returns%@AE@% %@AB@%strtod%@AE@%: the converted value; overflow returns %@AB@%HUGE_VAL%@AE@%, underflow returns 0 %@AB@%strtol%@AE@%: the converted value; overflow returns %@AB@%LONG_MAX%@AE@% %@AB@%%@AE@% or%@AB@% LONG_MIN%@AE@%, depending on sign of converted value %@AB@%strtoul%@AE@%: the converted value if successful, 0 if not, and %@AB@%ULONG_MAX%@AE@% on overflow %@NL@% %@2@%%@CR:C6A-B0006 @%%@AB@%Error Message Routines%@AE@%%@EH@%%@NL@% %@NL@% The routines in this category handle the display of error messages. %@NL@% %@NL@% The %@AB@%assert%@AE@% macro is typically used to test for program logic errors; it prints a message when a given "assertion" fails to hold true. Defining the identifier %@AB@%NDEBUG%@AE@% to any value causes occurrences of %@AB@%assert%@AE@% to be disabled in the source file, thus allowing you to turn off assertion checking without modifying the source file. %@NL@% %@NL@% The %@AB@%perror%@AE@% routine prints the system-error message, along with a user-supplied message, for the last system-level call that produced an error. The %@AB@%perror%@AE@% routine is declared in the include files STDLIB.H and STDIO.H. The error number is obtained from the %@AB@%errno%@AE@% variable. The system message is taken from the %@AB@%sys_errlist%@AE@% array. %@NL@% %@NL@% The %@AB@%strerror%@AE@% and %@AB@%_strerror%@AE@% routines store error messages in a string. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%assert%@AE@% - Tests for logic error.%@NL@% %@NL@% %@AB@%Include%@AE@% ASSERT.H, STDIO.H %@AB@%Prototype%@AE@% %@AB@%void assert(%@AE@%%@AI@% expression %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%expression%@AE@% Expression to test %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%perror%@AE@% - Prints error message.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototypes%@AE@% %@AB@%void perror( const char *%@AE@%%@AI@%string%@AE@%%@AB@% );%@AE@% int %@AI@%errno%@AE@%%@AB@%;%@AE@% int %@AI@%sys_nerr%@AE@%%@AB@%;%@AE@% char *%@AI@%sys_errlist %@AE@%%@AB@%[%@AE@%%@AI@%sys_nerr%@AE@%%@AB@%];%@AE@% %@AB@%Arguments%@AE@% %@AI@%string%@AE@% User-supplied message %@AI@%errno%@AE@% Error number %@AI@%sys_nerr%@AE@% Number of system-error messages %@AI@%sys_errlis%@AE@% Array of error messages %@AI@%t%@AE@% %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%strerror, _strerror %@AE@% - Saves system-error message and optional user-error message in string. The routine %@AB@%strerror%@AE@% is the ANSI-compatible version.%@NL@% %@NL@% %@AB@%Include%@AE@% STRING.H %@AB@%Prototypes%@AE@% %@AB@%char *strerror( int %@AE@%%@AI@%errnum%@AE@%%@AB@% );%@AE@% %@AB@%char *_strerror( char *%@AE@%%@AI@%string%@AE@%%@AB@% );%@AE@% %@AB@%int%@AE@% %@AI@%errno%@AE@%%@AB@%;%@AE@% %@AB@%int%@AE@% %@AI@%sys_nerr%@AE@%%@AB@%;%@AE@% %@AB@%char *%@AE@%%@AI@%sys_errlist %@AE@%%@AB@%[%@AE@%%@AI@%sys_nerr%@AE@%%@AB@%];%@AE@% %@AB@%Arguments%@AE@% %@AI@%errnum%@AE@% Error number %@AI@%string%@AE@% User-supplied message %@AI@%errno%@AE@% Error number %@AI@%sys_nerr%@AE@% Number of system-error messages %@AI@%sys_errlis%@AE@% Array of error messages %@AI@%t%@AE@% %@AB@%Returns%@AE@% A pointer to the error-message string %@NL@% %@2@%%@CR:C6A-B0007 @%%@AB@%Graphics 1: Low-Level Graphics Routines%@AE@%%@EH@%%@NL@% %@NL@% The low-level graphics routines provide line, figure, and pixel manipulation capabilities. The routines for presentation graphics are described in the next section. The routines for displaying fonts follow the presentation graphics section. %@NL@% %@NL@% The graphics package supports the IBM(R) (and compatible) Enhanced Graphics Adapter (EGA), Color Graphics Adapter (CGA), certain operating modes of the Video Graphics Array (VGA) hardware configurations, and the MCGA (Multicolor Graphics Array). The graphics package also supports the Hercules Graphics Card, Graphics Card Plus, InColor Card, and 100 percent compatible cards, as well as the special Olivetti(R) modes available on AT&T(R) computers. %@NL@% %@NL@% The low-level graphics routines can be divided into the seven categories listed below, corresponding to the different tasks involved with creating and manipulating graphic objects: %@NL@% %@NL@% %@AB@%Category%@AE@% %@AB@%Task%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% Configure mode and environment Selects the proper display mode for the hardware and establishes memory areas for writing and displaying images Set coordinates Specifies the logical origin and the active display area within the screen Set palette Specifies a palette mapping Set attributes Specifies background and foreground colors and mask and line styles Output images Draws and fills figures on the screen Output text Writes text to the screen Transfer images Stores images in memory and retrieves them %@NL@% %@4@%%@AB@%Configure Mode and Environment%@AE@%%@EH@%%@NL@% %@NL@% The configure category of functions sets the status of the cursor, sets active and visual pages, and determines and sets video display modes. %@NL@% %@NL@% The %@AB@%_setvideomode%@AE@% and %@AB@%_getvideoconfig%@AE@% functions are generally used at the very beginning of a graphics program. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%_displaycursor%@AE@% - Determines whether the cursor will be left on or turned off on exit from graphics routines.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%short _far _displaycursor( short %@AE@%%@AI@%toggle %@AE@% %@AI@%%@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%toggle%@AE@% Cursor state (%@AB@%_GCURSORON%@AE@%,%@AB@% %@AE@% %@AB@%_GCURSOROFF%@AE@% ) %@AB@%Returns%@AE@% The previous value of toggle ──────────────────────────────────────────────────────────────────────────── %@AB@%_getvideoconfig%@AE@% - Obtains status of current graphics environment.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%struct videoconfig _far * _far %@AE@% %@AB@%_getvideoconfig%@AE@% ( struct videoconfig _far *%@AI@%config %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%config%@AE@% Configuration information %@AB@%Returns%@AE@% The configuration information as a %@AB@%%@AE@% %@AB@%videoconfig%@AE@% structure ──────────────────────────────────────────────────────────────────────────── %@AB@%_setvideomode%@AE@% - Selects screen display mode.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%short _far _setvideomode( short %@AE@%%@AI@%mode%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%mode%@AE@% Desired mode (%@AB@%_DEFAULTMODE%@AE@%,%@AB@% %@AE@% %@AB@%_TEXTBW40%@AE@%,%@AB@%%@AE@% _TEXTC40,%@AB@% _TEXTBW80%@AE@%,%@AB@% _TEXTC80%@AE@%,%@AB@% %@AE@% %@AB@%_MRES4COLOR%@AE@%, %@AB@%_MRESNOCOLOR%@AE@%,%@AB@% _HRESBW%@AE@%,%@AB@% _TEXTMONO%@AE@%,%@AB@%%@AE@% _HERCMONO, %@AB@%_MRES16COLOR%@AE@%,%@AB@% _HRES16COLOR%@AE@%,%@AB@%%@AE@% _ERESNOCOLOR,%@AB@% _ERESCOLOR%@AE@%,%@AB@% _VRES2COLOR%@AE@%,%@AB@%%@AE@% _VRES16COLOR,%@AB@% _MRES256COLOR%@AE@%,%@AB@% _ORESCOLOR%@AE@%%@AI@%,%@AE@% %@AB@%_MAXRESMODE%@AE@%, %@AB@%_MAXCOLORMODE%@AE@%) %@AB@%Returns%@AE@% A nonzero value if successful, 0 if not %@NL@% %@4@%%@AB@%Set Coordinates%@AE@%%@EH@%%@NL@% %@NL@% The Microsoft C graphics routines recognize three sets of coordinates: %@NL@% %@NL@% %@NL@% 1. Window coordinates defined with real-number values that are mapped to a specified viewport%@NL@% %@NL@% 2. Viewport coordinates defined by the application (viewport coordinates)%@NL@% %@NL@% 3. Fixed physical coordinates determined by the hardware and display configuration of the user's environment (physical coordinates)%@NL@% %@NL@% %@NL@% The functions in this category alter the coordinate systems and provide a means to translate coordinates between the various systems. %@NL@% %@NL@% Most of these routines have two or three forms. The functions are listed by the "base" name, without a suffix. Note, though, that function names that end with a %@AB@%_w%@AE@%, such as %@AB@%_getcurrentposition_w%@AE@%, use the window-coordinate system. Those that end with a %@AB@%_wxy%@AE@%, such as %@AB@%_getviewcoord_wxy%@AE@%, use the window-coordinate system and a %@AB@%_wxycoord%@AE@% structure to define the coordinates. %@NL@% %@NL@% The default viewport-coordinate system is identical to the physical one. The physical origin (0, 0) is always in the upper left corner of the display. The %@AI@%x%@AE@% axis extends in the positive direction left to right, and the %@AI@%y%@AE@% axis extends in the positive direction top to bottom. %@NL@% %@NL@% The dimensions of the %@AI@%x%@AE@% and %@AI@%y%@AE@% axes depend upon the hardware display configuration and the selected mode. These values are accessible at run time by examining the %@AB@%numxpixels%@AE@% and %@AB@%numypixels%@AE@% fields of the %@AB@%videoconfig%@AE@% structure returned by %@AB@%_getvideoconfig%@AE@%. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%_getcurrentposition%@AE@% - Obtains the coordinates of the current graphic-output position. The %@AB@%_getcurrentposition%@AE@% function returns the position as an %@AB@%xycoord%@AE@% structure and the %@AB@%_getcurrentposition_w%@AE@% function returns the position as a %@AB@% _wxycoord%@AE@% structure.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%struct xycoord _far _getcurrentposition(%@AE@% %@AB@%void );%@AE@% struct _wxycoord _far _getcurrentposition_w( void ); %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% %@AB@%_getcurrentposition%@AE@%: the coordinates of the current position as an %@AB@%xycoord%@AE@% structure %@AB@%_getcurrentposition_w%@AE@%: the coordinates of the current position as a %@AB@%_wxycoord%@AE@% structure ──────────────────────────────────────────────────────────────────────────── %@AB@%_getphyscoord%@AE@% - Converts viewport coordinates to physical coordinates.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%struct xycoord _far _getphyscoord( short%@AE@% %@AB@%%@AE@%%@AI@%x%@AE@%%@AB@%, short %@AE@%%@AI@%y%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@%, %@AI@%y%@AE@% View point to translate %@AB@%Returns%@AE@% A pair of physical coordinates as an %@AB@%%@AE@% %@AB@%xycoord%@AE@% structure ──────────────────────────────────────────────────────────────────────────── %@AB@%_getviewcoord %@AE@% - Converts specified coordinates to viewport coordinates.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%struct xycoord _far _getviewcoord( short%@AE@% %@AB@%%@AE@%%@AI@%x%@AE@%%@AB@%, short );%@AE@% struct xycoord _far _getviewcoord_w( double %@AI@%wx%@AE@%%@AB@%, double %@AE@%%@AI@%wy %@AE@%%@AB@%);%@AE@% struct xycoord _far _getviewcoord_wxy( struct _wxycoord _far *%@AI@%pwxy1%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%x%@AE@%, %@AI@%y%@AE@% Physical point to translate %@AI@%wx%@AE@%, %@AI@%wy%@AE@% Window-coordinate point to translate %@AI@%pwxy1%@AE@% Window-coordinate point to translate %@AB@%Returns%@AE@% A pair of logical coordinates as an %@AB@%%@AE@% %@AB@%xycoord%@AE@% structure ──────────────────────────────────────────────────────────────────────────── %@AB@%_getwindowcoord%@AE@% - Converts physical coordinates to window coordinates.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%struct _wxycoord _far _getwindowcoord( %@AE@% %@AB@%short %@AE@%%@AI@%x%@AE@%%@AB@%, short %@AE@%%@AI@%y%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@%, %@AI@%y%@AE@% Physical point to translate %@AB@%Returns%@AE@% A pair of window coordinates as a %@AB@%%@AE@% %@AB@%_wxycoord%@AE@% structure ──────────────────────────────────────────────────────────────────────────── %@AB@%_setcliprgn%@AE@% - Limits graphic output to part of the screen.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%void _far _setcliprgn( short %@AE@%%@AI@%x1%@AE@%%@AB@%, short %@AE@% %@AI@%y1%@AE@%%@AB@%, short %@AE@%%@AI@%x2%@AE@%%@AB@%, short %@AE@%%@AI@%y2 %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%x1%@AE@%,%@AI@% y1%@AE@% Upper left corner of clip region %@AI@%x2, y2%@AE@% Lower right corner of clip region %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%_setvieworg%@AE@% - Positions the logical origin.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%struct xycoord _far _setvieworg( short %@AE@%%@AI@%x%@AE@% %@AB@%, short %@AE@%%@AI@%y %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@%, %@AI@%y%@AE@% New origin point %@AB@%Returns%@AE@% The physical coordinates of the previous viewport origin in an %@AB@%xycoord%@AE@% structure ──────────────────────────────────────────────────────────────────────────── %@AB@%_setviewport%@AE@% - Limits graphic output and positions the logical origin within a limited area.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%void _far _setviewport( short %@AE@%%@AI@%x1%@AE@%%@AB@%, short%@AE@% %@AB@%%@AE@%%@AI@%y1%@AE@%%@AB@%, short %@AE@%%@AI@%x2%@AE@%%@AB@%, short %@AE@%%@AI@%y2%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%x1%@AE@%, %@AI@%y1%@AE@% Upper left corner of window %@AI@%x2%@AE@%, %@AI@%y2%@AE@% Lower right corner of window %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%_setwindow%@AE@% - Defines a window-coordinate system.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%void _far _setwindow( short %@AE@%%@AI@%finvert%@AE@%%@AB@%, %@AE@% %@AB@%double %@AE@%%@AI@%wx1%@AE@%%@AB@%, double %@AE@%%@AI@%wy1%@AE@%%@AB@%,%@AE@% double %@AI@%wx2%@AE@%%@AB@%, double %@AE@%%@AI@%wy2%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%wx1%@AE@%,%@AI@% wy1%@AE@% Upper left corner of window %@AI@%wx2%@AE@%,%@AI@% wy2%@AE@% Lower right corner of window %@AI@%finvert%@AE@% Invert flag (TRUE, FALSE) %@AB@%Returns%@AE@% Void %@NL@% %@4@%%@AB@%Set Palette%@AE@%%@EH@%%@NL@% %@NL@% A screen pixel can be represented as a one-, two-, or four-bit value, depending on the particular mode. The byte representation is called the "color value." %@NL@% %@NL@% Each color that can be displayed is represented by a unique ordinal value called a "color index." A palette is simply a mapping of the actual display colors to the legal values. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%_remapallpalette, _remappalette%@AE@% - The %@AB@%_remapallpalette%@AE@% routine assigns colors to all color values. The %@AB@%_remappalette%@AE@% routine assigns color indexes to selected color values.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%short _far _remapallpalette( long _far *%@AE@% %@AI@%colors%@AE@%%@AB@% );%@AE@% long _far _remappalette( short %@AI@%index%@AE@%%@AB@%, %@AE@% %@AB@%long %@AE@%%@AI@%color%@AE@%%@AB@% );%@AE@% Arguments %@AI@%colors%@AE@% Color value array: %@AB@%(_BLACK%@AE@%, %@AB@%_BLUE%@AE@%, %@AB@%_GREEN,%@AE@% _CYAN, _RED,%@AB@% _MAGENTA%@AE@%,%@AB@% _BROWN%@AE@%,%@AB@% _WHITE%@AE@%, %@AB@%%@AE@% _GRAY, %@AB@%_LIGHTBLUE, ,_LIGHTGREEN,%@AE@% _LIGHTCYAN, %@AB@%_LIGHTRED, _LIGHTMAGENTA,%@AE@% _LIGHTYELL %@AB@%_BRIGHTWHITE)%@AE@% OW, %@AI@%index%@AE@% Color index to reassign %@AI@%color%@AE@% Color value to assign color index %@AB@%Returns%@AE@% %@AB@%_remapallpalette:%@AE@% 0 if successful, -1 if not %@AB@%_remappalette:%@AE@% the previous color value of the index argument if successful, -1 if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_selectpalette%@AE@% - Selects a predefined palette.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%short _far _selectpalette( short %@AE@%%@AI@%number %@AE@% %@AI@%%@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%number%@AE@% Palette number %@AB@%Returns%@AE@% The value of the previous palette %@NL@% %@4@%%@AB@%Set Attributes%@AE@%%@EH@%%@NL@% %@NL@% Attributes are characteristics (color, fill pattern, or line style) that can be specified for low-level graphics routines. %@NL@% %@NL@% A fill mask is an 8-by-8-bit template array, with each bit representing a pixel. If a bit is 0, the pixel in memory is left untouched: the mask is transparent to that pixel. If a bit is 1, the pixel is assigned the current color value. The template is repeated over the entire fill area. %@NL@% %@NL@% A line style is a 16-bit template buffer, with each bit corresponding to a pixel. If a bit is 0, the pixel is set to the current background color. If a bit is 1, the pixel is set to the current color. The template is repeated for the length of the line. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%_getbkcolor%@AE@% - Reports the current background color.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%long _far _getbkcolor( void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% The current background color ──────────────────────────────────────────────────────────────────────────── %@AB@%_getcolor%@AE@% - Obtains the current color.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%short _far _getcolor( void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% The current color ──────────────────────────────────────────────────────────────────────────── %@AB@%_setbkcolor%@AE@% - Sets the current background color.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%long _far _setbkcolor( long %@AE@%%@AI@%color %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%color%@AE@% Desired color value %@AB@%Returns%@AE@% The color value of the previous background color ──────────────────────────────────────────────────────────────────────────── %@AB@%_setcolor%@AE@% - Sets the current color.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%short _far _setcolor( short %@AE@%%@AI@%color %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%color%@AE@% Desired color index %@AB@%Returns%@AE@% The previous color %@NL@% %@4@%%@AB@%Output Images%@AE@%%@EH@%%@NL@% %@NL@% These routines display graphic elements (arcs, lines, pixels, etc.) on the screen. %@NL@% %@NL@% Circular figures such as arcs and ellipses are centered within a "bounding rectangle," specified by two points that define the diagonally opposed corners of the rectangle. The center of the rectangle becomes the center of the figure, and the rectangle's borders determine the size of the figure. %@NL@% %@NL@% Most of these routines have two or three forms. The functions are listed by the "base" name, without a suffix. Note, though, that function names that end with a %@AB@%_w%@AE@%, such as %@AB@%_arc_w%@AE@%, use the window coordinate system. Those that end with a %@AB@%_wxy%@AE@%, such as %@AB@%_ellipse_wxy%@AE@%, use the window coordinate system and a %@AB@% _wxycoord%@AE@% structure to define the coordinates. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%_arc %@AE@% - Draws an arc.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%short _far _arc( short %@AE@%%@AI@%x1%@AE@%%@AB@%, short %@AE@%%@AI@%y1%@AE@%%@AB@%, %@AE@% %@AB@%short %@AE@%%@AI@%x2%@AE@%%@AB@%, short %@AE@%%@AI@%y2%@AE@%%@AB@%,%@AE@% short %@AI@%x3%@AE@%%@AB@%, short %@AE@%%@AI@%y3%@AE@%%@AB@%, short %@AE@%%@AI@%x4%@AE@%%@AB@%, short %@AE@%%@AI@%y4 %@AE@% %@AB@%);%@AE@% short _far _arc_wxy( struct _wxycoord %@AI@%%@AE@% %@AI@%pwxy1%@AE@%%@AB@%,%@AE@% struct _wxycoord*%@AI@%pwxy2%@AE@%%@AB@%, struct %@AE@% %@AB@%_wxycoord*%@AE@%%@AI@%pwxy3%@AE@%%@AB@%, %@AE@% struct _wxycoord*%@AI@%pwxy4 %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%x1%@AE@%, %@AI@%y1%@AE@% Upper left corner of bounding rectangle %@AI@%x2%@AE@%,%@AI@% y2%@AE@% Lower right corner of bounding rectangle %@AI@%x%@AE@%3,%@AI@% y3%@AE@% Start vector %@AI@%x4%@AE@%,%@AI@% y4%@AE@% End vector %@AI@%pwxy1%@AE@% Upper left corner of bounding rectangle %@AI@%pwxy2%@AE@% Lower right corner of bounding rectangle %@AI@%pwxy3%@AE@% Start vector %@AI@%pwxy4%@AE@% End vector %@AB@%Returns%@AE@% A nonzero value if the arc is drawn successfully, 0 if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_clearscreen%@AE@% - Erases the screen and fills it with the current background color.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%void _far _clearscreen( short %@AE@%%@AI@%area %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%area%@AE@% Target area (%@AB@%_GCLEARSCREEN%@AE@%,%@AB@% %@AE@% %@AB@%_GVIEWPORT%@AE@%, %@AB@% _GWINDOW%@AE@%) %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%_ellipse %@AE@% - Draws an ellipse.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%short _far _ellipse( short %@AE@%%@AI@%control%@AE@%%@AB@%, %@AE@% %@AB@%short %@AE@%%@AI@%x1%@AE@%%@AB@%, short %@AE@%%@AI@%y1%@AE@%%@AB@%,%@AE@% short %@AI@%x2%@AE@%%@AB@%, short %@AE@%%@AI@%y2 %@AE@%%@AB@%);%@AE@% short _far _ellipse_w( short %@AI@%control%@AE@%%@AB@%, %@AE@% %@AB@%double %@AE@%%@AI@%wx1%@AE@%%@AB@%, double %@AE@%%@AI@%wy1%@AE@%%@AB@%,%@AE@% double %@AI@%wx2%@AE@%%@AB@%, double %@AE@%%@AI@%wy2 %@AE@%%@AB@%);%@AE@% short _far _ellipse_wxy( short %@AI@%control%@AE@%%@AB@%, %@AE@% %@AB@%struct _wxycoord* %@AE@%%@AI@%pwxy1%@AE@%%@AB@%,%@AE@% struct _wxycoord*%@AI@%pwxy2%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%control%@AE@% Fill flag (%@AB@% _GFILLINTERIOR%@AE@%, %@AB@% _GBORDER%@AE@%) %@AI@%x1%@AE@%, %@AI@%y1%@AE@% Upper left corner of bounding rectangle (view coordinates) %@AI@%x2%@AE@%, %@AI@%y2%@AE@% Lower right corner of bounding rectangle (view coordinates) %@AI@%wx1, wy1%@AE@% Upper left corner of bounding rectangle (window coordinates) %@AI@%wx%@AE@%2,%@AI@% wy2%@AE@% Lower right corner of bounding rectangle (window coordinates) %@AI@%pwxy1%@AE@% Upper left corner of bounding rectangle (window coordinates) %@AI@%pwxy2%@AE@% Lower right corner of bounding rectangle (window coordinates) %@AB@%Returns%@AE@% A nonzero value if the ellipse is drawn successfully, 0 if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_floodfill %@AE@% - Fills an area of the screen with the current color.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%short _far _floodfill( short %@AE@%%@AI@%x%@AE@%%@AB@%, short %@AE@%%@AI@%y%@AE@% %@AB@%, short %@AE@%%@AI@%boundary %@AE@%%@AB@%);%@AE@% short _far _floodfill_w( double %@AI@%wx%@AE@%%@AB@%, %@AE@% %@AB@%double %@AE@%%@AI@%wy%@AE@%%@AB@%, short %@AE@%%@AI@%boundary %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%x, y%@AE@% Start point (view coordinates)%@AB@%%@AE@% %@AI@%wx%@AE@%, %@AI@%wy%@AE@% Start point (window coordinates) %@AI@%boundary%@AE@% Boundary color %@AB@%Returns%@AE@% A nonzero value if successful, 0 if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_getpixel %@AE@% - Obtains a pixel's color index. The coordinates can be specified in either view coordinates (%@AB@%_getpixel%@AE@%) or in window coordinates (%@AB@%_getpixel_w%@AE@%).%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%short _far _getpixel( short %@AE@%%@AI@%x%@AE@%%@AB@%, short %@AE@%%@AI@%y %@AE@% %@AB@%);%@AE@% short _far _getpixel_w( double %@AI@%wx%@AE@%%@AB@%, %@AE@% %@AB@%double %@AE@%%@AI@%wy%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%x%@AE@%,%@AI@% y%@AE@% Pixel position (view coordinates) %@AI@%wx, wy%@AE@% Pixel position (window coordinates) %@AB@%Returns%@AE@% The color index if successful, -1 if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_lineto %@AE@% - Draws a line from the current graphic output position to a specified point. The coordinate of the end point can be specified in either view coordinates (%@AB@%_lineto%@AE@%) or in window coordinates (%@AB@%_lineto_w%@AE@%).%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%short _far _lineto( short %@AE@%%@AI@%x%@AE@%%@AB@%, short %@AE@%%@AI@%y %@AE@%%@AB@%);%@AE@% short _far _lineto_w( double %@AI@%wx%@AE@%%@AB@%, double %@AE@% %@AI@%wy %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%x%@AE@%, %@AI@%y%@AE@% End point (view coordinates) %@AI@%wx%@AE@%,%@AI@% wy%@AE@% End point (window coordinates) %@AB@%Returns%@AE@% A nonzero value if the line is drawn successfully, 0 if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_moveto %@AE@% - Moves the current graphic-output position to a specified point. The coordinates can be specified in either view coordinates (%@AB@%_moveto%@AE@%) or in window coordinates (%@AB@%_moveto_w%@AE@%).%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%struct xycoord _far _moveto( short %@AE@%%@AI@%x%@AE@%%@AB@%, %@AE@% %@AB@%short );%@AE@% struct _wxycoord _far _moveto_w( double %@AI@%%@AE@% %@AI@%wx%@AE@%%@AB@%, double %@AE@%%@AI@%wy %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%x%@AE@%, %@AI@%y%@AE@% Target position (view coordinates) %@AI@%wx%@AE@%, %@AI@%wy%@AE@% Target position (window coordinates) %@AB@%Returns%@AE@% The logical coordinates of the previous position as an %@AB@%xycoord%@AE@% structure (%@AB@%_moveto%@AE@%) or as a %@AB@%_wxycoord%@AE@% structure (%@AB@%_moveto_w%@AE@%) ──────────────────────────────────────────────────────────────────────────── %@AB@%_pie %@AE@% - Draws a figure shaped like a pie wedge.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%short _far _pie( short %@AE@%%@AI@%control%@AE@%%@AB@%, short %@AE@%%@AI@%%@AE@% %@AI@%x1%@AE@%%@AB@%, short %@AE@%%@AI@%y1%@AE@%%@AB@%,%@AE@% short %@AI@%x2%@AE@%%@AB@%, short %@AE@%%@AI@%y2%@AE@%%@AB@%, short %@AE@%%@AI@%x3%@AE@%%@AB@%, short %@AE@%%@AI@%y3%@AE@%%@AB@%, %@AE@% %@AB@%short %@AE@%%@AI@%x4%@AE@%%@AB@%, short %@AE@%%@AI@%y%@AE@%%@AB@%4 );%@AE@% short _far _pie_wxy( short %@AI@%control%@AE@%%@AB@%, %@AE@% %@AB@%struct _wxycoord* %@AE@%%@AI@%pwxy1%@AE@%%@AB@%,%@AE@% struct _wxycoord*%@AI@%pwxy2%@AE@%%@AB@%, struct %@AE@% %@AB@%_wxycoord* %@AE@%%@AI@%pwxy3%@AE@%%@AB@%,%@AE@% struct _wxycoord*%@AI@%pwxy4 %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%control%@AE@% Fill flag (%@AB@%_GFILLINTERIOR%@AE@%, %@AB@%%@AE@% %@AB@%_GBORDER%@AE@%) %@AI@%x1, y1%@AE@% Upper left corner of bounding rectangle (view coordinates) %@AI@%x2%@AE@%, %@AI@%y2%@AE@% Lower right corner of bounding rectangle (view coordinates) %@AI@%x3%@AE@%, %@AI@%y3%@AE@% Start vector(view coordinates) %@AI@%x4%@AE@%,%@AI@% y4%@AE@% End vector (view coordinates) %@AI@%pwxy1%@AE@% Upper left corner of bounding rectangle (window coordinates) %@AI@%pwxy2%@AE@% Lower right corner of bounding rectangle (window coordinates) %@AI@%pwxy3%@AE@% Start vector (window coordinates) %@AI@%pwxy4%@AE@% End vector (window coordinates) %@AB@%Returns%@AE@% A nonzero value if the pie is drawn successfully, 0 if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_rectangle %@AE@% - Draws a rectangle.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%short _far _rectangle( short %@AE@%%@AI@%control%@AE@%%@AB@%, %@AE@% %@AB@%short %@AE@%%@AI@%x1%@AE@%%@AB@%, short %@AE@%%@AI@%y1%@AE@%%@AB@%,%@AE@% short %@AI@%x2%@AE@%%@AB@%, short %@AE@%%@AI@%y2 %@AE@%%@AB@%);%@AE@% short _far _rectangle_w( short%@AI@% control%@AE@%%@AB@%, %@AE@% %@AB@%double %@AE@%%@AI@%wx1%@AE@%%@AB@%, double %@AE@%%@AI@%wy1%@AE@%%@AB@%,%@AE@% double %@AI@%wx2%@AE@%%@AB@%, double %@AE@%%@AI@%wy2 %@AE@%%@AB@%);%@AE@% short _far _rectangle_wxy( short %@AI@%control%@AE@% %@AB@%, struct _wxycoord*%@AE@%%@AI@%pwxy1%@AE@%%@AB@%,%@AE@% struct _wxycoord*%@AI@%pwxy2%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%control%@AE@% Fill flag (%@AB@%_GFILLINTERIOR%@AE@%, %@AB@%%@AE@% %@AB@%_GBORDER%@AE@%) %@AI@%x1%@AE@%,%@AI@% y1%@AE@% Upper left corner (view coordinates) %@AI@%x2%@AE@%,%@AI@% y2%@AE@% Lower right corner (view coordinates) %@AI@%wx1%@AE@%, %@AI@%wy1%@AE@% Upper left corner (window coordinates) %@AI@%wx2%@AE@%, %@AI@%wy2%@AE@% Lower right corner (window coordinates) %@AI@%pwxy1%@AE@% Upper left corner (window coordinates) %@AI@%pwxy2%@AE@% Lower right corner (window coordinates) %@AB@%Returns%@AE@% A nonzero value if the rectangle is drawn successfully, 0 if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_setpixel %@AE@% - Sets a pixel's color index.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%short _far _setpixel( short %@AE@%%@AI@%x%@AE@%%@AB@%, short %@AE@%%@AI@%y %@AE@% %@AB@%);%@AE@% short _far _setpixel_w( double %@AI@%wx%@AE@%%@AB@%, %@AE@% %@AB@%double%@AE@%%@AI@% wy%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%x%@AE@%, %@AI@%y%@AE@% Target pixel (view coordinates) %@AI@%wx%@AE@%, %@AI@%wy%@AE@% Target pixel (window coordinates) %@AB@%Returns%@AE@% The pixel's previous value if successful, -1 if not %@NL@% %@4@%%@AB@%Output Text%@AE@%%@EH@%%@NL@% %@NL@% These routines provide text output in both graphics and text modes. %@NL@% %@NL@% These functions recognize text window boundaries and should be used in applications using text windows. %@NL@% %@NL@% No formatting capability is provided. If you want to output integer or floating-point values, you must convert the values into a string variable before calling these routines. All screen positions are specified as character-row and character-column coordinates. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%_displaycursor%@AE@% - Sets the cursor "on" or "off" on exit from a graphics routine.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%short _far _displaycursor( short %@AE@%%@AI@%toggle %@AE@% %@AI@%%@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%toggle%@AE@% Cursor state (%@AB@%_GCURSORON%@AE@%,%@AB@% %@AE@% %@AB@%_GCURSOROFF%@AE@%) %@AB@%Returns%@AE@% The previous value of %@AI@%toggle%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%_gettextcolor%@AE@% - Obtains the current text color.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%short _far _gettextcolor( void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% The color index of the current text color ──────────────────────────────────────────────────────────────────────────── %@AB@%_gettextcursor%@AE@% - Obtains the current cursor attribute.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%short _far _gettextcursor( void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% The current cursor attribute ──────────────────────────────────────────────────────────────────────────── %@AB@%_gettextposition%@AE@% - Obtains the current text-output position.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%struct rccoord _far _gettextposition( %@AE@% %@AB@%void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% The current text position as an %@AB@%rccoord%@AE@% structure ──────────────────────────────────────────────────────────────────────────── %@AB@%_outtext%@AE@% - Outputs text to the screen at the current position.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%void _far _outtext( unsigned char _far *%@AE@% %@AI@%text %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%text%@AE@% Text to be output %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%_settextposition%@AE@% - Relocates the current text position.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%struct rccoord _far _settextposition( %@AE@% %@AB@%short %@AE@%%@AI@%row%@AE@%%@AB@%, short %@AE@%%@AI@%col %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%row%@AE@% Row coordinate of new output position %@AI@%col%@AE@% Column coordinate of new output position %@AB@%Returns%@AE@% The previous text position in an%@AB@% rccoord%@AE@% structure ──────────────────────────────────────────────────────────────────────────── %@AB@%_settextcolor%@AE@% - Sets the current text color.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%short _far _settextcolor( short %@AE@%%@AI@%index %@AE@%%@AB@%%@AE@% %@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%index%@AE@% Desired color index %@AB@%Returns%@AE@% The value of the previous color ──────────────────────────────────────────────────────────────────────────── %@AB@%_settextwindow%@AE@% - Sets the current text-display window.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%void _far _settextwindow( short %@AE@%%@AI@%r1%@AE@%%@AB@%, %@AE@% %@AB@%short %@AE@%%@AI@%c1%@AE@%%@AB@%, short %@AE@%%@AI@%r2%@AE@%%@AB@%, short %@AE@%%@AI@%c2 %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%r1%@AE@%,%@AI@% c1%@AE@% Upper left corner of window %@AI@%r2%@AE@%, %@AI@%c2%@AE@% Lower right corner of window %@AB@%Returns%@AE@% Void %@NL@% %@4@%%@AB@%Transfer Images%@AE@%%@EH@%%@NL@% %@NL@% These functions transfer screen images between memory and the display, using a buffer allocated by the application. You can use these functions to animate graphics elements on the screen. %@NL@% %@NL@% Most of these routines have two or three forms. The functions are listed by the "base" name, without a suffix. Note, though, that function names that end in a %@AB@%_w%@AE@%, such as %@AB@%_getimage_w%@AE@%, use the window-coordinate system. Those that end with a %@AB@%_wxy%@AE@%, such as %@AB@%_imagesize_wxy%@AE@%, use the window-coordinate system and a %@AB@%_wxycoord%@AE@% structure to define the coordinates. %@NL@% %@NL@% The %@AB@%_imagesize%@AE@% function is used to find the size in bytes of the buffer needed to store a given image. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%_getimage%@AE@% - Stores a screen image in memory.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%void _far _getimage( short %@AE@%%@AI@%x1%@AE@%%@AB@%, short %@AE@%%@AI@%y1%@AE@% %@AB@%,%@AE@% short %@AI@%x2%@AE@%%@AB@%, short %@AE@%%@AI@%y2%@AE@%%@AB@%, char _huge *%@AE@%%@AI@%image%@AE@%%@AB@% %@AE@% %@AB@%);%@AE@% void _far _getimage_w( double %@AI@%wx1%@AE@%%@AB@%, %@AE@% %@AB@%double %@AE@%%@AI@%wy1%@AE@%%@AB@%,%@AE@% double %@AI@%wx2%@AE@%%@AB@%, double %@AE@%%@AI@%wy2%@AE@%%@AB@%, char _huge *%@AE@%%@AI@%%@AE@% %@AI@%image %@AE@%%@AB@%);%@AE@% void _far _getimage_wxy( struct _wxycoord*%@AI@%pwxy1%@AE@%%@AB@%,%@AE@% struct _wxycoord*%@AI@%pwxy2%@AE@%%@AB@%, char _huge *%@AE@%%@AI@%%@AE@% %@AI@%image %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%x1%@AE@%,%@AI@% y1%@AE@% Upper left corner of bounding rectangle (view coordinates) %@AI@%x2%@AE@%, %@AI@%y2%@AE@% Lower right corner of bounding rectangle (view coordinates) %@AI@%wx1%@AE@%,%@AI@% wy1%@AE@% Upper left corner of bounding rectangle (window coordinates) %@AI@%wx2%@AE@%, %@AI@%wy2%@AE@% Lower right corner of bounding rectangle (window coordinates) %@AI@%pwxy1%@AE@% Upper left corner of bounding rectangle (window coordinates) %@AI@%pwxy2%@AE@% Lower right corner of bounding rectangle (window coordinates) %@AI@%image%@AE@% Storage buffer for screen image %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%_imagesize%@AE@% - Returns image size in bytes.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%long _far _imagesize( short %@AE@%%@AI@%x1%@AE@%%@AB@%, short %@AE@%%@AI@%%@AE@% %@AI@%y1%@AE@%%@AB@%, short %@AE@%%@AI@%x2%@AE@%%@AB@%, short %@AE@%%@AI@%y2 %@AE@%%@AB@%);%@AE@% long _far _imagesize_w( double %@AI@%wx1%@AE@%%@AB@%, %@AE@% %@AB@%double %@AE@%%@AI@%wy1%@AE@%%@AB@%, double %@AE@%%@AI@%wx2%@AE@%%@AB@%,%@AE@% double %@AI@%wy2 %@AE@%%@AB@%);%@AE@% long _far _imagesize_wxy( struct _wxycoord* %@AI@%pwxy1%@AE@%%@AB@%,%@AE@% struct _wxycoord* %@AI@%pwxy2 %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%x1%@AE@%, %@AI@%y1%@AE@% Upper left corner of bounding rectangle (view coordinates) %@AI@%x2%@AE@%,%@AI@% y2%@AE@% Lower right corner of bounding rectangle (view coordinates) %@AI@%wx1%@AE@%,%@AI@% wy1%@AE@% Upper left corner of bounding rectangle (window coordinates) %@AI@%wx2%@AE@%,%@AI@% wy2%@AE@% Lower right corner of bounding rectangle (window coordinates) %@AI@%pwxy1%@AE@% Upper left corner of bounding rectangle (window coordinates) %@AI@%pwxy2%@AE@% Lower right corner of bounding rectangle (window coordinates) %@AB@%Returns%@AE@% The storage size of the image in bytes ──────────────────────────────────────────────────────────────────────────── %@AB@%_putimage%@AE@% - Retrieves an image from memory and displays it.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototypes%@AE@% %@AB@%void _far _putimage( short %@AE@%%@AI@%x%@AE@%%@AB@%, short %@AE@%%@AI@%y%@AE@%%@AB@%,%@AE@% char _huge *%@AI@%image%@AE@%%@AB@%, short %@AE@%%@AI@%action%@AE@%%@AB@% );%@AE@% void _far _putimage_w( double %@AI@%wx%@AE@%%@AB@%, double%@AE@% %@AB@%%@AE@%%@AI@%wy%@AE@%%@AB@%,%@AE@% char _huge *%@AI@%image%@AE@%%@AB@%, short %@AE@%%@AI@%action %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%x, y%@AE@% Position of upper left corner of image (view coordinates) %@AI@%wx%@AE@%,%@AI@% wy%@AE@% Position of upper left corner of image (window coordinates) %@AI@%image%@AE@% Stored image buffer %@AI@%action%@AE@% Interaction with existing screen image (%@AB@%_GAND%@AE@%, %@AB@% _GOR,%@AE@% _GXOR, %@AB@%_GPSET%@AE@%, %@AB@%_GPRESET%@AE@%) %@AB@%Returns%@AE@% Void %@NL@% %@2@%%@CR:C6A-B0008 @%%@AB@%Graphics 2: Presentation Graphics Routines%@AE@%%@EH@%%@NL@% %@NL@% The presentation graphics routines provide complete charting capabilities for line, bar, column, scatter, and pie charts. %@NL@% %@NL@% Some charts plot both "categories," or non-numeric data such as time periods, and "values," or specific numeric data, such as sales. Presentation graphics routines support the following kinds of charts: %@NL@% %@NL@% %@AB@%Chart Name%@AE@% %@AB@%Description%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% Line Category/value chart, with styles for lines between points and for no lines Bar Category/value chart, horizontal bars, styles for stacked and unstacked multiple series charts Column Category/value chart, vertical bars, with styles for stacked and unstacked multiple series charts Scatter Value/value chart, with styles for lines connecting points or for no lines Pie Pie chart, with optional percentages and exploded sections The graphics package supports the IBM (and compatible) Enhanced Graphics Adapter (EGA), Color Graphics Adapter (CGA), certain operating modes of the Video Graphics Array (VGA) hardware configurations, and the Multicolor Graphics Array (MCGA). The graphics package also supports the Hercules Graphics Card, Graphics Card Plus, InColor Card, and 100-percent compatible cards, as well as the special Olivetti modes available on AT&T computers. %@NL@% %@NL@% The %@AB@%_pg_initchart%@AE@% and %@AB@%_pg_defaultchart%@AE@% functions are generally used at the very beginning of a presentation graphics program. %@NL@% %@NL@% The %@AB@%_pg_chart%@AE@% functions produce column charts, line charts, and bar charts. The %@AB@%_pg_chartscatter%@AE@% functions produce a scatter plot of data. The %@AB@%_pg_chartpie%@AE@% function generates a pie chart. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%_pg_chart%@AE@% - Generates a chart of the type specified in the %@AI@%env%@AE@% environment variable. It produces a column, bar, or line chart for a single series of data.%@NL@% %@NL@% %@AB@%Include%@AE@% PGCHART.H %@AB@%Prototype%@AE@% %@AB@%short _far _pg_chart( chartenv _far*%@AE@%%@AI@%env%@AE@%%@AB@%,%@AE@% %@AB@%%@AE@% char _far*_far *%@AI@%categories%@AE@%%@AB@%, float _far*%@AE@%%@AI@%%@AE@% %@AI@%values%@AE@%%@AB@%, short %@AE@%%@AI@%n %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%env%@AE@% Chart environment variable %@AI@%categories%@AE@% Array of category variables %@AI@%values%@AE@% Array of data values %@AI@%n%@AE@% Number of data values to chart %@AB@%Returns%@AE@% 0 if successful, nonzero if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_pg_chartms%@AE@% - Generates a multiple series of charts of the type specified in the %@AI@%env%@AE@% environment variable. It produces a column, bar, or line chart for a multiple series of data. All series must be the same length.%@NL@% %@NL@% %@AB@%Include%@AE@% PGCHART.H %@AB@%Prototype%@AE@% %@AB@%short _far _pg_chartms( chartenv _far *%@AE@%%@AI@%%@AE@% %@AI@%env%@AE@%%@AB@%, %@AE@% char _far * _far*%@AI@%categories%@AE@%%@AB@%, float _far*%@AE@% %@AI@%values%@AE@%%@AB@%, short %@AE@%%@AI@%n%@AE@%%@AB@%, short %@AE@%%@AI@%nseries%@AE@%%@AB@%,%@AE@% short %@AI@%arraydim%@AE@%%@AB@%, char _far* _far*%@AE@%%@AI@%%@AE@% %@AI@%serieslabels %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%env%@AE@% Chart environment variable %@AI@%categories%@AE@% Array of category variables %@AI@%values%@AE@% Two-dimensional array of data values (series, data) %@AI@%n%@AE@% Number of data values to chart in a series %@AI@%nseries%@AE@% Number of series to chart %@AI@%arraydim%@AE@% Second (row) dimension of data array %@AI@%serieslabe%@AE@% Array of labels for series %@AI@%ls%@AE@% %@AB@%Returns%@AE@% 0 if successful, nonzero if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_pg_chartpie%@AE@% - Generates a pie chart for a single series of data.%@NL@% %@NL@% %@AB@%Include%@AE@% PGCHART.H %@AB@%Prototype%@AE@% %@AB@%short _far _pg_chartpie( chartenv _far*%@AE@%%@AI@%%@AE@% %@AI@%env%@AE@%%@AB@%, %@AE@% char _far* _far*%@AI@%categories%@AE@%%@AB@%, float _far*%@AE@%%@AI@%%@AE@% %@AI@%values%@AE@%%@AB@%, %@AE@% short _far*%@AI@%explode%@AE@%%@AB@%, short %@AE@%%@AI@%n %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%env%@AE@% Chart environment variable %@AI@%categories%@AE@% Array of category names %@AI@%values%@AE@% Array of data values %@AI@%explode %@AE@% Array of explode flags; 1=explode, 0=do not explode %@AI@%n%@AE@% Number of data values to chart %@AB@%Returns%@AE@% 0 if successful, nonzero if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_pg_chartscatter%@AE@% - Generates a scatter chart for a single series of data. %@NL@% %@NL@% %@AB@%Include%@AE@% PGCHART.H %@AB@%Prototype%@AE@% %@AB@%short _far _pg_chartscatter( chartenv %@AE@% %@AB@%_far *%@AE@%%@AI@%env%@AE@%%@AB@%, float _far *%@AE@%%@AI@%xvalues%@AE@%%@AB@%,%@AE@% float _far *%@AI@%yvalues%@AE@%%@AB@%, short %@AE@%%@AI@%n %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%env%@AE@% Chart environment variable %@AI@%xvalues%@AE@% Array of %@AI@%x-%@AE@%axis data values %@AI@%yvalues%@AE@% Array of%@AI@% y%@AE@%-axis data values %@AI@%n%@AE@% Number of data values to chart %@AB@%Returns%@AE@% 0 if successful, nonzero if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_pg_chartscatterms%@AE@% - Generates a scatter chart for a multiple series of data. %@NL@% %@NL@% %@AB@%Include%@AE@% PGCHART.H %@AB@%Prototype%@AE@% %@AB@%short _far _pg_chartscatterms( chartenv %@AE@% %@AB@%_far *%@AE@%%@AI@%env%@AE@%%@AB@%,%@AE@% float _far*%@AI@%xvalues%@AE@%%@AB@%, float _far*%@AE@%%@AI@%yvalues%@AE@%%@AB@%, %@AE@% %@AB@%short %@AE@%%@AI@%nseries%@AE@%%@AB@%, short %@AE@%%@AI@%n%@AE@%%@AB@%,%@AE@% short %@AI@%rowdim%@AE@%%@AB@%, char _far* _far *%@AE@%%@AI@%%@AE@% %@AI@%serieslabels %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%env%@AE@% Chart environment variable %@AI@%xvalues%@AE@% Two-dimensional array of %@AI@%x%@AE@% -axis values %@AI@%yvalues%@AE@% Two-dimensional array of %@AI@%y%@AE@% -axis values %@AI@%n%@AE@% Number of data values to chart in a series %@AI@%nseries%@AE@% Number of series to chart %@AI@%rowdim%@AE@% Second (row) dimension of data array %@AI@%serieslabe%@AE@% Array of labels for series %@AI@%ls%@AE@% %@AB@%Returns%@AE@% 0 if successful, nonzero if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_pg_defaultchart%@AE@% - Initializes all necessary variables in the chart environment for the specified default chart and chart style.%@NL@% %@NL@% %@AB@%Include%@AE@% PGCHART.H %@AB@%Prototype%@AE@% %@AB@%short _far _pg_defaultchart( chartenv %@AE@% %@AB@%_far *%@AE@%%@AI@%env%@AE@%%@AB@%, short %@AE@%%@AI@%charttype%@AE@%%@AB@%,%@AE@% short %@AI@%chartstyle %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%env%@AE@% Chart environment variable %@AI@%charttype%@AE@% Chart type (%@AB@%_PG_BARCHART%@AE@%, %@AB@%_PG_COLUMNCHART%@AE@%, %@AB@%_PG_LINECHART%@AE@%, %@AB@%_PG_SCATTERCHART%@AE@%, %@AB@%_PG_PIECHART)%@AE@% %@AI@%chartstyle%@AE@% Chart style %@AB@%Returns%@AE@% 0 if successful, nonzero if not ──────────────────────────────────────────────────────────────────────────── %@AB@%_pg_initchart%@AE@% - Initializes chart line-style set, default palettes, screen modes, and character fonts. You must call this routine before any other charting routine.%@NL@% %@NL@% %@AB@%Include%@AE@% PGCHART.H %@AB@%Prototype%@AE@% %@AB@%short _far _pg_initchart( void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% 0 if successful, nonzero if not %@NL@% %@2@%%@CR:C6A-B0009 @%%@AB@%Graphics 3: Font Display Routines%@AE@%%@EH@%%@NL@% %@NL@% The font graphics routines display font-based characters on the screen. %@NL@% %@NL@% The %@AB@%_registerfonts%@AE@% function initializes the fonts package with a set of disk-based type fonts. This must be done at the very beginning of any fonts program. The %@AB@%_unregisterfonts%@AE@% function frees fonts from memory when they are no longer needed. %@NL@% %@NL@% The %@AB@%_setfont%@AE@% function makes a specified font the current active font for output. The %@AB@%_outgtext%@AE@% function displays text on the screen using the current font. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%_getfontinfo%@AE@% - Obtains the current font characteristics.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%short _far _getfontinfo( struct %@AE@% %@AB@%_fontinfo _far *%@AE@%%@AI@%fontbuffer%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%fontbuffer%@AE@% Font information %@AB@%Returns%@AE@% Font information as a %@AB@%_fontinfo%@AE@% structure ──────────────────────────────────────────────────────────────────────────── %@AB@%_getgtextextent%@AE@% - Determines the width of the specified text in the current font.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%short _far _getgtextextent( unsigned %@AE@% %@AB@%char _far * %@AE@%%@AI@%text %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%text%@AE@% Text to be analyzed %@AB@%Returns%@AE@% The width of the text in pixels ──────────────────────────────────────────────────────────────────────────── %@AB@%_outgtext%@AE@% - Outputs text in the current font to the screen at the current position.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%void _far _outgtext( unsigned char _far %@AE@% %@AB@%*%@AE@%%@AI@%text %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%text%@AE@% Text to be output %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%_registerfonts%@AE@% - Initializes the font library.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%short _far _registerfonts( unsigned char%@AE@% %@AB@%_far *%@AE@%%@AI@%filename %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%file name%@AE@% File name of .FON files to register %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%_setfont%@AE@% - Finds a single font that matches a specified set of characteristics and makes this font the current font.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%short _far _setfont( unsigned char _far %@AE@% %@AB@%*%@AE@%%@AI@%options%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%options%@AE@% Font options string %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%_unregisterfonts%@AE@% - Frees memory associated with fonts.%@NL@% %@NL@% %@AB@%Include%@AE@% GRAPH.H %@AB@%Prototype%@AE@% %@AB@%void _far _unregisterfonts( void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% Void %@NL@% %@2@%%@CR:C6A-B0010 @%%@AB@%Input and Output Routines%@AE@%%@EH@%%@NL@% %@NL@% The input and output (I/O) routines of the standard C library allow you to read and write data to and from files and devices. In C, there are no predefined file structures; all data is treated as sequences of bytes. %@NL@% %@NL@% Three types of I/O functions are available: %@NL@% %@NL@% %@NL@% ■ Stream I/O, in which the data file is a stream of individual characters%@NL@% %@NL@% ■ Low-level I/O, which uses the system's I/O capabilities directly%@NL@% %@NL@% ■ Console and port I/O, which are stream routines for console or port%@NL@% %@NL@% %@NL@% Stream I/O uses the %@AB@%FILE%@AE@% structure. The stream routines provide for buffered, formatted, or unformatted input and output. %@NL@% %@NL@% Low-level I/O uses a file "handle" to access files. This handle is an integer value that is used to refer to the file in subsequent operations. %@NL@% %@NL@% Do not mix stream and low-level routines on the same file or device. %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Stream Routines%@AE@%%@EH@%%@NL@% %@NL@% In the stream routines listed below, the following manifest constants are used: %@NL@% %@NL@% %@NL@% ■ %@AB@%EOF%@AE@% is defined to be the value returned at end-of-file%@NL@% %@NL@% ■ %@AB@%NULL%@AE@% is the null pointer%@NL@% %@NL@% ■ %@AB@%FILE%@AE@% is the structure that maintains information about a stream%@NL@% %@NL@% ■ %@AB@%BUFSIZ%@AE@% defines the default size of stream buffers, in bytes%@NL@% %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%clearerr%@AE@% - Clears the error indicator for a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%void clearerr( FILE%@AE@% %@AB@%*%@AE@%%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%fclose%@AE@% - Closes a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int fclose( FILE *%@AE@%%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%stream%@AE@% Target %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% 0 if successful, %@AB@%EOF%@AE@% if not ──────────────────────────────────────────────────────────────────────────── %@AB@%feof%@AE@% - Tests for end-of-file on a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int feof( FILE *%@AE@%%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% A nonzero value when the current position is the end-of-file, 0 if not ──────────────────────────────────────────────────────────────────────────── %@AB@%ferror%@AE@% - Tests for error on a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int ferror( FILE *%@AE@%%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% A nonzero value to indicate an error in stream, 0 to indicate no error ──────────────────────────────────────────────────────────────────────────── %@AB@%fflush%@AE@% - Flushes a stream. %@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int fflush( FILE *%@AE@%%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% 0 if successful, if stream has no buffer, or if stream is open only for reading; returns %@AB@%EOF%@AE@% otherwise ──────────────────────────────────────────────────────────────────────────── %@AB@%fgetc%@AE@% - Reads a character from a stream (function version).%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int fgetc( FILE *%@AE@%%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% The character read; %@AB@%EOF%@AE@% may indicate error ──────────────────────────────────────────────────────────────────────────── %@AB@%fgetpos%@AE@% - Gets the position indicator of a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int fgetpos( FILE *%@AE@%%@AI@%stream%@AE@%%@AB@%, fpos_t *%@AE@%%@AI@%pos %@AE@% %@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%stream%@AE@% Target stream %@AI@%pos%@AE@% Position indicator storage %@AB@%Returns%@AE@% 0 if successful, a nonzero value if not %@AB@%errno%@AE@%:%@AB@% EINVAL%@AE@%,%@AB@% EBADF%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%fgets%@AE@% - Reads a string from a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%char *fgets( char *%@AE@%%@AI@%string%@AE@%%@AB@%, int %@AE@%%@AI@%n%@AE@%%@AB@%, FILE %@AE@% %@AB@%*%@AE@%%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%string%@AE@% Storage location for data %@AI@%n%@AE@% Number of characters stored %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% A pointer to string if successful, %@AB@%NULL%@AE@% if unsuccessful or at end-of-file ──────────────────────────────────────────────────────────────────────────── %@AB@%fopen%@AE@% - Opens a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%FILE *fopen( const char *%@AE@%%@AI@%filename%@AE@%%@AB@%, %@AE@% %@AB@%const char *%@AE@%%@AI@%mode %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%filename%@AE@% Path name of file %@AI@%mode%@AE@% Type of access permitted such as %@AB@%r%@AE@%, %@AB@%w%@AE@%,%@AB@% a%@AE@%,%@AB@% r+%@AE@%,%@AB@% w+%@AE@%,%@AB@% a+%@AE@% ,%@AB@% t%@AE@%,%@AB@% b%@AE@% (appended to type to indicate mode) %@AB@%Returns%@AE@% A pointer to the open file if successful, %@AB@%NULL%@AE@% if not ──────────────────────────────────────────────────────────────────────────── %@AB@%fprintf%@AE@% - Writes formatted data to a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int fprintf( FILE *%@AE@%%@AI@%stream%@AE@%%@AB@%, const char *%@AE@% %@AI@%format %@AE@%[[,%@AI@% argument%@AE@%]]... ); %@AB@%Arguments%@AE@% %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AI@%format%@AE@% Format-control string %@AB@%Returns%@AE@% The number of characters printed ──────────────────────────────────────────────────────────────────────────── %@AB@%fputc%@AE@% - Writes a character to a stream (function version).%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int fputc( int %@AE@%%@AI@%c%@AE@%%@AB@%, FILE *%@AE@%%@AI@%stream%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%c%@AE@% Character to be written %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% The character written; %@AB@%EOF%@AE@% may indicate error ──────────────────────────────────────────────────────────────────────────── %@AB@%fputs%@AE@% - Writes a string to a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int fputs( const char *%@AE@%%@AI@%string%@AE@%%@AB@%, FILE *%@AE@%%@AI@%%@AE@% %@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%string%@AE@% String to be output %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% 0 if successful, nonzero if not ──────────────────────────────────────────────────────────────────────────── %@AB@%fread%@AE@% - Reads unformatted data from a stream. %@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%size_t fread( void *%@AE@%%@AI@%buffer%@AE@%%@AB@%, size_t %@AE@%%@AI@%size%@AE@% %@AB@%, size_t %@AE@%%@AI@%count%@AE@%%@AB@%, FILE *%@AE@%%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%buffer%@AE@% Storage location for data %@AI@%size%@AE@% Item size in bytes %@AI@%count%@AE@% Maximum number of items to be read %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% The number of items actually read ──────────────────────────────────────────────────────────────────────────── %@AB@%freopen%@AE@% - Reassigns a %@AB@%FILE%@AE@% pointer. %@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%FILE *freopen( const char *%@AE@%%@AI@%filename%@AE@%%@AB@%, %@AE@% %@AB@%const char *%@AE@%%@AI@%mode%@AE@%%@AB@%,%@AE@% FILE *%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%filename%@AE@% Path name of new file %@AI@%mode%@AE@% Type of access permitted such as %@AB@%r, w, a, r+, w+,%@AE@% a+, t, b (appended to type to indicate mode) %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% A pointer to the newly opened file if successful, a %@AB@%NULL%@AE@% pointer if not ──────────────────────────────────────────────────────────────────────────── %@AB@%fscanf%@AE@% - Reads formatted data from a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int fscanf( FILE *%@AE@%%@AI@%stream%@AE@%%@AB@%, const char* %@AE@%%@AI@%%@AE@% %@AI@%format %@AE@%%@AB@% %@AE@%[[%@AB@%,%@AE@%%@AI@% argument%@AE@%]] ... ); %@AB@%Arguments%@AE@% %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AI@%format%@AE@% Format-control string %@AB@%Returns%@AE@% The number of fields successfully converted and assigned; %@AB@%EOF%@AE@% indicates an attempt to read the end-of-file ──────────────────────────────────────────────────────────────────────────── %@AB@%fseek%@AE@% - Repositions %@AB@%FILE%@AE@% pointer to given location.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int fseek( FILE *%@AE@%%@AI@%stream%@AE@%%@AB@%, long %@AE@%%@AI@%offset%@AE@%%@AB@%, %@AE@% %@AB@%int %@AE@%%@AI@%origin%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AI@%offset%@AE@% Number of bytes from origin %@AI@%origin%@AE@% Initial position (%@AB@%SEEK_SET%@AE@%,%@AB@% %@AE@% %@AB@%SEEK_CUR%@AE@%,%@AB@% SEEK_END)%@AE@% %@AB@%Returns%@AE@% 0 if successful, a nonzero value if not ──────────────────────────────────────────────────────────────────────────── %@AB@%fsetpos%@AE@% - Sets the position indicator of a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int fsetpos( FILE *%@AE@%%@AI@%stream%@AE@%%@AB@%, const fpos_t%@AE@% %@AB@%*%@AE@%%@AI@%pos %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%stream%@AE@% Target stream %@AI@%pos%@AE@% Position-indicator storage %@AB@%Returns%@AE@% 0 if successful, a nonzero value if not %@AB@%errno%@AE@%: %@AB@%EINVAL%@AE@%, %@AB@%EBADF%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%ftell%@AE@% - Gets current %@AB@%FILE%@AE@% pointer position.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%long ftell( FILE *%@AE@%%@AI@%stream%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%stream%@AE@% Target %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% The current position if successful, -1L if not %@AB@%errno%@AE@%: %@AB@%EINVAL%@AE@%, %@AB@%EBADF%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%fwrite%@AE@% - Writes unformatted data items to a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%size_t fwrite( const void *%@AE@%%@AI@%buffer%@AE@%%@AB@%, %@AE@% %@AB@%size_t %@AE@%%@AI@%size%@AE@%%@AB@%, size_t %@AE@%%@AI@%count%@AE@%%@AB@%,%@AE@% FILE *%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%buffer%@AE@% Pointer to data to be written %@AI@%size%@AE@% Item size in bytes %@AI@%count%@AE@% Maximum number of items to be written %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% The number of full items actually written ──────────────────────────────────────────────────────────────────────────── %@AB@%getc%@AE@% - Reads a character from a stream (macro version). %@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int getc( FILE *%@AE@%%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% The character read; %@AB@%EOF%@AE@% may indicate error ──────────────────────────────────────────────────────────────────────────── %@AB@%getchar%@AE@% - Reads a character from %@AB@%stdin%@AE@% (macro version).%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int getchar( void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% The character read; %@AB@%EOF%@AE@% may indicate error ──────────────────────────────────────────────────────────────────────────── %@AB@%gets%@AE@% - Reads a line from %@AB@%stdin%@AE@%.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%char *gets( char *%@AE@%%@AI@%buffer%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%buffer%@AE@% Storage location for input string %@AB@%Returns%@AE@% A pointer to its argument if successful, a %@AB@%NULL%@AE@% pointer if at end-of-file or unsuccessful ──────────────────────────────────────────────────────────────────────────── %@AB@%printf%@AE@% - Writes formatted data to %@AB@%stdout%@AE@%.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int printf( const char *%@AE@%%@AI@%format%@AE@%%@AB@% %@AE@%[[, %@AI@%%@AE@% %@AI@%argument%@AE@%]]... ); %@AB@%Argument%@AE@% %@AI@%format%@AE@% Format-control string %@AB@%Returns%@AE@% The number of characters printed ──────────────────────────────────────────────────────────────────────────── %@AB@%putc%@AE@% - Writes a character to a stream (macro version). %@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int putc( int %@AE@%%@AI@%c%@AE@%%@AB@%, FILE *%@AE@%%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%c%@AE@% Character to be written %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% The character written; %@AB@%EOF%@AE@% may indicate error ──────────────────────────────────────────────────────────────────────────── %@AB@%putchar%@AE@% - Writes a character to %@AB@%stdout%@AE@% (macro version).%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int putchar( int %@AE@%%@AI@%c %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%c%@AE@% Character to be written %@AB@%Returns%@AE@% The character written; %@AB@%EOF%@AE@% may indicate error ──────────────────────────────────────────────────────────────────────────── %@AB@%puts%@AE@% - Writes a line to a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int puts( const char *%@AE@%%@AI@%string %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%string%@AE@% String to be output %@AB@%Returns%@AE@% 0 if successful, nonzero if not ──────────────────────────────────────────────────────────────────────────── %@AB@%rewind%@AE@% - Repositions %@AB@%FILE%@AE@% pointer to beginning of a stream.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%void rewind( FILE *%@AE@%%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%scanf%@AE@% - Reads formatted data from %@AB@%stdin%@AE@%.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int scanf( const char *%@AE@%%@AI@%format %@AE@%[[, %@AI@%%@AE@% %@AI@%argument%@AE@%]]... ); %@AB@%Argument%@AE@% %@AI@%format%@AE@% Format control string %@AB@%Returns%@AE@% The number of fields converted and assigned if successful, 0 if no fields were assigned, %@AB@%EOF%@AE@% for an attempt to read end-of-file ──────────────────────────────────────────────────────────────────────────── %@AB@%sprintf%@AE@% - Writes formatted data to string.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int sprintf( char *%@AE@%%@AI@%buffer%@AE@%%@AB@%, const char *%@AE@% %@AI@%format %@AE@%[[, %@AI@%argument%@AE@%]] ... );%@AI@%%@AE@% %@AB@%Arguments%@AE@% %@AI@%buffer%@AE@% Storage location for output %@AI@%format%@AE@% Format-control string %@AB@%Returns%@AE@% The number of characters stored in buffer ──────────────────────────────────────────────────────────────────────────── %@AB@%sscanf%@AE@% - Reads formatted data from string.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int sscanf( const char *%@AE@%%@AI@%buffer%@AE@%%@AB@%, const %@AE@% %@AB@%char *%@AE@%%@AI@%format %@AE@%[[, %@AI@%argument%@AE@%]] ... ); %@AB@%Arguments%@AE@% %@AI@%buffer%@AE@% Stored data %@AI@%format%@AE@% Format-control string %@AB@%Returns%@AE@% The number of fields converted and assigned if successful, 0 if no fields were assigned, %@AB@%EOF%@AE@% for an attempt to read at end-of-string ──────────────────────────────────────────────────────────────────────────── %@AB@%tmpfile%@AE@% - Creates a temporary file.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%FILE *tmpfile( void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% A stream pointer if successful, %@AB@%NULL%@AE@% if not ──────────────────────────────────────────────────────────────────────────── %@AB@%tmpnam%@AE@% - Generates a temporary file name.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%char *tmpnam( char *%@AE@%%@AI@%string %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%string%@AE@% Pointer to temporary name %@AB@%Returns%@AE@% A pointer to the new name if successful, %@AB@%NULL%@AE@% if not ──────────────────────────────────────────────────────────────────────────── %@AB@%ungetc%@AE@% - Places a character in the input stream buffer.%@NL@% %@NL@% %@AB@%Include%@AE@% STDIO.H %@AB@%Prototype%@AE@% %@AB@%int ungetc( int %@AE@%%@AI@%c%@AE@%%@AB@%, FILE *%@AE@%%@AI@%stream %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%c%@AE@% Character to be pushed %@AI@%stream%@AE@% Pointer to %@AB@%FILE%@AE@% structure %@AB@%Returns%@AE@% The character argument %@AI@%c%@AE@% if successful, %@AB@%EOF%@AE@% if not %@NL@% %@4@%%@AB@%Low-Level Routines%@AE@%%@EH@%%@NL@% %@NL@% The low-level input and output calls do not buffer or format data. %@NL@% %@NL@% Files opened by low-level calls are referenced by a "file handle," an integer value used by the operating system to refer to the file. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%close%@AE@% - Closes a file.%@NL@% %@NL@% %@AB@%Include%@AE@% IO.H %@AB@%Prototype%@AE@% %@AB@%int close( int %@AE@%%@AI@%handle%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%handle%@AE@% Handle referring to open file %@AB@%Returns%@AE@% 0 if successful, -1 if not %@AB@%errno%@AE@%: %@AB@%EBADF%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%creat %@AE@% - Creates a file.%@NL@% %@NL@% %@AB@%Include%@AE@% IO.H, SYS\TYPES.H, SYS\STAT.H %@AB@%Prototype%@AE@% %@AB@%int creat( char *%@AE@%%@AI@%filename%@AE@%%@AB@%, int %@AE@%%@AI@%pmode %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%filename%@AE@% Path name of new file %@AI@%pmode%@AE@% Permission setting ( %@AB@%%@AE@% %@AB@%S_IWRITE , S_IREAD%@AE@%,%@AB@% %@AE@% S_IREAD | S_IWRITE) %@AB@%Returns%@AE@% A handle if successful, -1 if not %@AB@%errno%@AE@%: %@AB@%EACCES%@AE@%, %@AB@%EMFILE%@AE@%, %@AB@%ENOENT%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%eof %@AE@% - Tests for end-of-file.%@NL@% %@NL@% %@AB@%Include%@AE@% IO.H %@AB@%Prototype%@AE@% %@AB@%int eof( int %@AE@%%@AI@%handle%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%handle%@AE@% Handle referring to open file %@AB@%Returns%@AE@% 1 if the current position is the end-of-file and 0 if it is not, -1 to indicate an error %@AB@%errno%@AE@%: %@AB@%EBADF%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%lseek %@AE@% - Repositions file pointer to a given location. %@NL@% %@NL@% %@AB@%Include%@AE@% IO.H, STDIO.H %@AB@%Prototype%@AE@% %@AB@%long lseek( int %@AE@%%@AI@%handle%@AE@%%@AB@%, long %@AE@%%@AI@%offset%@AE@%%@AB@%, %@AE@% %@AB@%int %@AE@%%@AI@%origin%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%handle%@AE@% Handle referring to open file %@AI@%offset%@AE@% Number of bytes from origin %@AI@%origin%@AE@% Initial position (%@AB@%SEEK_SET%@AE@%,%@AB@% %@AE@% %@AB@%SEEK_CUR%@AE@%,%@AB@% SEEK_END)%@AE@% %@AB@%Returns%@AE@% The new position offset (in bytes) from the beginning of the file if successful, -1L if not %@AB@%errno%@AE@%: %@AB@%EBADF%@AE@%, %@AB@%EINVAL%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%open %@AE@% - Opens a file.%@NL@% %@NL@% %@AB@%Include%@AE@% FCNTL.H, IO.H, SYS\TYPES.H, SYS\STAT.H %@AB@%Prototype%@AE@% %@AB@%int open( char *%@AE@%%@AI@%path%@AE@%%@AB@%, int %@AE@%%@AI@%oflag %@AE@%[[, int %@AI@%pmode%@AE@%]] ); %@AB@%Arguments%@AE@% %@AI@%path%@AE@% File path name %@AI@%oflag%@AE@% Type of operations allowed such as %@AB@%O_APPEND%@AE@%,%@AB@%%@AE@% O_BINARY,%@AB@% O_CREAT%@AE@%,%@AB@% O_EXCL%@AE@%, %@AB@% O_RDONLY%@AE@%,%@AB@%%@AE@% O_RDWR,%@AB@% O_TEXT%@AE@%,%@AB@% O_TRUNC%@AE@%,%@AB@% O_WRONLY%@AE@% (may be joined by%@AB@% |%@AE@% ) %@AI@%pmode%@AE@% Permission setting (%@AB@%S_IWRITE%@AE@% ,%@AB@% S_IREAD%@AE@%,%@AB@%%@AE@% S_IREAD | S_IWRITE) %@AB@%Returns%@AE@% A handle if successful, -1 if not %@AB@%errno%@AE@%: %@AB@%EACCES%@AE@%, %@AB@%EEXIST%@AE@%, %@AB@%EMFILE%@AE@%, %@AB@%ENOENT%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%read %@AE@% - Reads data from a file.%@NL@% %@NL@% %@AB@%Include%@AE@% IO.H %@AB@%Prototype%@AE@% %@AB@%int read( int %@AE@%%@AI@%handle%@AE@%%@AB@%, char *%@AE@%%@AI@%buffer%@AE@%%@AB@%, %@AE@% %@AB@%unsigned int %@AE@%%@AI@%count%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%handle%@AE@% Handle referring to open file %@AI@%buffer%@AE@% Storage location of data %@AI@%count%@AE@% Maximum number of bytes %@AB@%Returns%@AE@% The number of bytes actually read or 0 at end-of-file if successful; -1 if not %@AB@%errno%@AE@%: %@AB@%EBADF%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%tell %@AE@% - Gets current file-pointer position.%@NL@% %@NL@% %@AB@%Include%@AE@% IO.H %@AB@%Prototype%@AE@% %@AB@%long tell( int %@AE@%%@AI@%handle %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%handle%@AE@% Handle referring to open file %@AB@%Returns%@AE@% The current position if successful, -1L if not %@AB@%errno%@AE@%: %@AB@%EBADF%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%write %@AE@% - Writes data to a file.%@NL@% %@NL@% %@AB@%Include%@AE@% IO.H %@AB@%Prototype%@AE@% %@AB@%int write( int %@AE@%%@AI@%handle%@AE@%%@AB@%, void *%@AE@%%@AI@%buffer%@AE@%%@AB@%, %@AE@% %@AB@%unsigned int %@AE@%%@AI@%count %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%handle%@AE@% Handle referring to open file %@AI@%buffer%@AE@% Data to be written %@AI@%count%@AE@% Number of bytes %@AB@%Returns%@AE@% The number of bytes actually written if successful, -1 if not %@AB@%errno%@AE@%: %@AB@% EBADF%@AE@%, %@AB@%ENOSPC%@AE@% %@NL@% %@NL@% %@NL@% %@4@%%@AB@%Console and Port I/O Routines%@AE@%%@EH@%%@NL@% %@NL@% The console and port I/O routines perform reading and writing operations on your console or on the specified port. %@NL@% %@NL@% The %@AB@%cgets%@AE@%, %@AB@%cscanf%@AE@%, %@AB@%getch%@AE@%, %@AB@%getche%@AE@%, and %@AB@%kbhit%@AE@% routines take input from the console. %@NL@% %@NL@% The %@AB@%cprintf%@AE@%, %@AB@%cputs%@AE@%, %@AB@%putch%@AE@%, and %@AB@%ungetch%@AE@% routines write to the console. %@NL@% %@NL@% The console or port does not have to be opened or closed before I/O is performed. %@NL@% %@NL@% The console I/O routines use the corresponding MS-DOS system calls to read and write characters. Since these routines are not compatible with stream or low-level library routines, console routines should not be used with them. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%cgets%@AE@% - Reads a string from the console.%@NL@% %@NL@% %@AB@%Include%@AE@% CONIO.H %@AB@%Prototype%@AE@% %@AB@%char *cgets( char *%@AE@%%@AI@%buffer %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%buffer%@AE@% Storage location for data %@AB@%Returns%@AE@% A pointer to the start of the string, which is at %@AI@%str%@AE@%[2] ──────────────────────────────────────────────────────────────────────────── %@AB@%cprintf%@AE@% - Writes formatted data to the console.%@NL@% %@NL@% %@AB@%Include%@AE@% CONIO.H %@AB@%Prototype%@AE@% %@AB@%int cprintf( char *%@AE@%%@AI@%format %@AE@%[[, %@AI@%argument%@AE@%]] ... ); %@AB@%Argument%@AE@% %@AI@%format%@AE@% Format-control string %@AB@%Returns%@AE@% The number of characters printed ──────────────────────────────────────────────────────────────────────────── %@AB@%cputs%@AE@% - Writes a string to the console.%@NL@% %@NL@% %@AB@%Include%@AE@% CONIO.H %@AB@%Prototype%@AE@% %@AB@%int cputs( char *%@AE@%%@AI@%string %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%string%@AE@% Output string %@AB@%Returns%@AE@% 0 if successful, nonzero if not ──────────────────────────────────────────────────────────────────────────── %@AB@%cscanf%@AE@% - Reads formatted data from the console.%@NL@% %@NL@% %@AB@%Include%@AE@% CONIO.H %@AB@%Prototype%@AE@% %@AB@%int cscanf( char *%@AE@%%@AI@%format %@AE@%[[, %@AI@%argument%@AE@% ]]... ); %@AB@%Argument%@AE@% %@AI@%format%@AE@% Format-control string %@AB@%Returns%@AE@% The number of fields converted and assigned if successful (0 means no fields were assigned), %@AB@%EOF%@AE@% for an attempt to read end-of-file ──────────────────────────────────────────────────────────────────────────── %@AB@%getch%@AE@% - Reads a character from the console.%@NL@% %@NL@% %@AB@%Include%@AE@% CONIO.H %@AB@%Prototype%@AE@% %@AB@%int getch( void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% The character read ──────────────────────────────────────────────────────────────────────────── %@AB@%getche%@AE@% - Reads a character from the console and echoes it.%@NL@% %@NL@% %@AB@%Include%@AE@% CONIO.H %@AB@%Prototype%@AE@% %@AB@%int getche( void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% The character read ──────────────────────────────────────────────────────────────────────────── %@AB@%kbhit%@AE@% - Checks for a keystroke at the console.%@NL@% %@NL@% %@AB@%Include%@AE@% CONIO.H %@AB@%Prototype%@AE@% %@AB@%int kbhit( void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% A nonzero value if a key has been pressed, 0 if not ──────────────────────────────────────────────────────────────────────────── %@AB@%putch%@AE@% - Writes a character to the console.%@NL@% %@NL@% %@AB@%Include%@AE@% CONIO.H %@AB@%Prototype%@AE@% %@AB@%int putch( int %@AE@%%@AI@%c%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%c%@AE@% Character to be output %@AB@%Returns%@AE@% The argument %@AI@%c%@AE@% if successful, %@AB@%EOF%@AE@% if not ──────────────────────────────────────────────────────────────────────────── %@AB@%ungetch%@AE@% - "Ungets" the last character read from the console so that it becomes the next character read.%@NL@% %@NL@% %@AB@%Include%@AE@% CONIO.H %@AB@%Prototype%@AE@% %@AB@%int ungetch( int %@AE@%%@AI@%c %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%c%@AE@% Character to be pushed %@AB@%Returns%@AE@% The argument %@AI@%c%@AE@% if successful, %@AB@%EOF%@AE@% if not %@NL@% %@2@%%@CR:C6A-B0011 @%%@AB@%Math Routines%@AE@%%@EH@%%@NL@% %@NL@% The math routines allow you to perform common mathematical calculations. %@NL@% %@NL@% All math routines work with floating-point values and therefore require floating-point support. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%abs, fabs, labs%@AE@% - The %@AB@%abs%@AE@%, %@AB@%fabs%@AE@%, and %@AB@%labs%@AE@% routines return the absolute value of an integer, a double, and a long argument, respectively.%@NL@% %@NL@% %@AB@%Includes%@AE@% STDLIB.H (%@AB@%abs%@AE@%, %@AB@%labs%@AE@%), MATH.H (%@AB@%fabs%@AE@%) %@AB@%Prototypes%@AE@% %@AB@%int abs( int %@AE@%%@AI@%n %@AE@%%@AB@%)%@AE@%; %@AB@%double fabs( double%@AE@% %@AI@%x %@AE@%%@AB@%);%@AE@% long labs( long %@AI@%x %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%n%@AE@% Integer (%@AB@%abs%@AE@%) or long (%@AB@%labs%@AE@%) value %@AI@%x%@AE@% Floating-point value %@AB@%Returns%@AE@% Absolute value of its argument ──────────────────────────────────────────────────────────────────────────── %@AB@%acos%@AE@% - Calculates the arccosine.%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototype%@AE@% %@AB@%double acos( double %@AE@%%@AI@%x%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@% Value whose arccosine is to be calculated %@AB@%Returns%@AE@% The arccosine result if successful, or 0 if %@AI@%x%@AE@% > 1 %@AB@%errno%@AE@%: %@AB@%EDOM%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%asin%@AE@% - Calculates the arcsine.%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototype%@AE@% %@AB@%double asin( double %@AE@%%@AI@%x %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@% Value whose arcsine is to be calculated %@AB@%Returns%@AE@% The arcsine result if successful, or 0 if %@AI@%x%@AE@% >1 %@AB@%errno%@AE@%: %@AB@%EDOM%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%atan, atan2%@AE@% - Calculates the arctangent of %@AI@%x%@AE@% (%@AB@%atan%@AE@%) or the arctangent of %@AI@%y%@AE@%/%@AI@%x%@AE@% (%@AB@%atan2%@AE@%).%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototypes%@AE@% %@AB@%double atan( double %@AE@%%@AI@%x%@AE@%%@AB@% );%@AE@% %@AB@%double atan2( double%@AE@% %@AI@%y%@AE@%%@AB@%, double %@AE@%%@AI@%x %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@%, %@AI@%y%@AE@% Floating-point values %@AB@%Returns%@AE@% %@AB@%atan%@AE@%: the arctangent result %@AB@%atan2%@AE@%: the arctangent of %@AI@%y%@AE@%/%@AI@%x%@AE@%, or 0 if both arguments are 0 %@AB@%errno%@AE@%: %@AB@%EDOM%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%ceil%@AE@% - Rounds the argument up to an integer.%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototype%@AE@% %@AB@%double ceil( double %@AE@%%@AI@%x %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@% Floating-point value %@AB@%Returns%@AE@% The double result ──────────────────────────────────────────────────────────────────────────── %@AB@%cos, cosh%@AE@% - Calculates the cosine (%@AB@%cos%@AE@%) or the hyperbolic cosine (%@AB@%cosh%@AE@%).%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototypes%@AE@% %@AB@%double cos( double %@AE@%%@AI@%x %@AE@%%@AB@%);%@AE@% %@AB@%double cosh( double%@AE@% %@AI@%x%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@% Angle (in radians) %@AB@%Returns%@AE@% %@AB@%cos%@AE@%: the cosine result if successful, 0 if not %@AB@%cosh%@AE@%: the hyperbolic result if successful, or %@AB@%HUGE_VAL%@AE@% if the result is too large %@AB@%errno:%@AE@% %@AB@%ERANGE%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%exp%@AE@% - Calculates the exponential function.%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototype%@AE@% %@AB@%double exp( double %@AE@%%@AI@%x %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@% Floating-point value %@AB@%Returns%@AE@% The exponential value if successful, %@AB@%%@AE@% %@AB@%HUGE_VAL%@AE@% on overflow, 0 on underflow %@AB@%errno%@AE@%: %@AB@%ERANGE%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%floor%@AE@% - Rounds the argument down to an integer.%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototype%@AE@% %@AB@%double floor( double %@AE@%%@AI@%x%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@% Floating-point value %@AB@%Returns%@AE@% The floating-point result ──────────────────────────────────────────────────────────────────────────── %@AB@%fmod%@AE@% - Finds the floating-point remainder.%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototype%@AE@% %@AB@%double fmod( double %@AE@%%@AI@%x%@AE@%%@AB@%, double %@AE@%%@AI@%y %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@%,%@AI@% y%@AE@% Floating-point values %@AB@%Returns%@AE@% The floating-point remainder, or 0 if %@AI@%y%@AE@% is 0 ──────────────────────────────────────────────────────────────────────────── %@AB@%frexp%@AE@% - Calculates an exponential value.%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototype%@AE@% %@AB@%double frexp( double %@AE@%%@AI@%x%@AE@%%@AB@%, int *%@AE@%%@AI@%expptr %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@% Floating-point value %@AI@%expptr%@AE@% Pointer to stored integer exponent %@AB@%Returns%@AE@% The mantissa, or 0 if %@AI@%x%@AE@% is 0 ──────────────────────────────────────────────────────────────────────────── %@AB@%ldexp%@AE@% - Calculates the argument times 2exp.%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototype%@AE@% %@AB@%double ldexp( double %@AE@%%@AI@%x%@AE@%%@AB@%, int %@AE@%%@AI@%exp %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%x%@AE@% Floating-point value %@AI@%exp%@AE@% Integer exponent %@AB@%Returns%@AE@% An exponential value if successful, %@AB@%%@AE@% %@AB@%HUGE_VAL%@AE@% on overflow %@AB@%errno:%@AE@% %@AB@%ERANGE%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%log, log10%@AE@% - Calculates the natural logarithm (%@AB@%log%@AE@%) or the base-10 log (%@AB@%log10%@AE@%).%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototypes%@AE@% %@AB@%double log( double %@AE@%%@AI@%x%@AE@%%@AB@% );%@AE@% double log10( double %@AI@%x %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@% Floating-point value %@AB@%Returns%@AE@% A logarithm result if successful, %@AB@%%@AE@% %@AB@%-HUGE_VAL%@AE@% if not %@AB@%errno%@AE@%: %@AB@%EDOM%@AE@% (if %@AI@%x%@AE@% < 0), %@AB@%ERANGE%@AE@% (if %@AI@%x%@AE@% = 0) ──────────────────────────────────────────────────────────────────────────── %@AB@%modf%@AE@% - Breaks argument into integer and fractional parts.%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototype%@AE@% %@AB@%double modf( double %@AE@%%@AI@%x%@AE@%%@AB@%, double *%@AE@%%@AI@%intptr%@AE@%%@AB@% %@AE@% %@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%x%@AE@% Floating-point value %@AI@%intptr%@AE@% Pointer to stored integer position %@AB@%Returns%@AE@% The signed fractional portion of %@AI@%x%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%pow%@AE@% - Calculates a value raised to a power. %@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototype%@AE@% %@AB@%double pow( double %@AE@%%@AI@%x%@AE@%%@AB@%, double %@AE@%%@AI@%y %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%x%@AE@% Number to be raised %@AI@%y%@AE@% Power of %@AI@%x%@AE@% %@AB@%Returns%@AE@% The argument %@AI@%x%@AE@% raised to the %@AI@%y%@AE@% power if successful, %@AB@%HUGE_VAL%@AE@% if not ──────────────────────────────────────────────────────────────────────────── %@AB@%rand, srand%@AE@% - The %@AB@%rand%@AE@% function returns a pseudorandom integer in the range 0-32,767. The %@AB@%srand%@AE@% function initializes the random number generator.%@NL@% %@NL@% %@AB@%Include%@AE@% STDLIB.H %@AB@%Prototypes%@AE@% %@AB@%int rand( void );%@AE@% %@AB@%void srand( unsigned%@AE@% %@AI@%seed %@AE@%%@AB@%)%@AE@%; %@AB@%Argument%@AE@% %@AI@%seed%@AE@% Seed for random-number generation (%@AB@%srand%@AE@%) %@AB@%Returns%@AE@% %@AB@%rand%@AE@%: a pseudorandom number %@AB@%srand%@AE@%: void ──────────────────────────────────────────────────────────────────────────── %@AB@%sin, sinh%@AE@% - Calculates the sine (%@AB@%sin%@AE@%) or hyperbolic sine (%@AB@%sinh%@AE@%).%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototypes%@AE@% %@AB@%double sin( double %@AE@%%@AI@%x%@AE@%%@AB@% );%@AE@% %@AB@%double sinh( double%@AE@% %@AI@%x %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@% Angle (in radians) %@AB@%Returns%@AE@% %@AB@%sin%@AE@%: the sine of %@AI@%x%@AE@% if successful, 0 if not %@AB@%sinh%@AE@%: the hyperbolic sine of %@AI@%x%@AE@% if successful, %@AB@%HUGE_VAL%@AE@% if not %@AB@%errno%@AE@%: %@AB@%ERANGE%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%sqrt%@AE@% - Finds the square root.%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototype%@AE@% %@AB@%double sqrt( double %@AE@%%@AI@%x%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@% Nonnegative floating-point value %@AB@%Returns%@AE@% A square root if successful, 0 if not %@AB@%errno%@AE@%: %@AB@%EDOM%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%tan, tanh%@AE@% - Calculates the tangent (%@AB@%tan%@AE@%) or hyperbolic tangent (%@AB@%tanh%@AE@%).%@NL@% %@NL@% %@AB@%Includes%@AE@% FLOAT.H, MATH.H %@AB@%Prototypes%@AE@% %@AB@%double tan( double %@AE@%%@AI@%x%@AE@%%@AB@% );%@AE@% %@AB@%double tanh( double%@AE@% %@AI@%x%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%x%@AE@% Angle (in radians) %@AB@%Returns%@AE@% %@AB@%tan:%@AE@% the tangent of %@AI@%x%@AE@% if successful, 0 if not %@AB@%tanh:%@AE@% the hyperbolic tangent of %@AI@%x%@AE@% %@AB@%errno%@AE@%: %@AB@%ERANGE%@AE@% (%@AB@%tan%@AE@% only) %@NL@% %@2@%%@CR:C6A-B0012 @%%@AB@%Memory-Allocation Routines%@AE@%%@EH@%%@NL@% %@NL@% The memory-allocation routines allocate, free, analyze, and reallocate blocks of memory. %@NL@% %@NL@% Many of the memory-allocation functions are prefixed by an %@AB@%_f%@AE@% or an %@AB@%_n%@AE@%. This notation means use the far (%@AB@%_f%@AE@%) heap or the near (%@AB@%_n%@AE@%) heap. %@NL@% %@NL@% The %@AB@%malloc%@AE@% family of routines (%@AB@%malloc%@AE@%, %@AB@%_fmalloc%@AE@%, and %@AB@%_nmalloc%@AE@%) allocates memory blocks of a specified size. The %@AB@%calloc%@AE@% function allocates storage for an array. The %@AB@%halloc%@AE@% function allocates storage for a huge array. %@NL@% %@NL@% The %@AB@%realloc%@AE@% routine changes the size of an allocated block. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%calloc%@AE@% - Allocates storage for an array. %@NL@% %@NL@% %@AB@%Includes%@AE@% MALLOC.H, STDLIB.H %@AB@%Prototype%@AE@% %@AB@%void *calloc( size_t %@AE@%%@AI@%num%@AE@%%@AB@%, size_t %@AE@%%@AI@%size %@AE@%%@AB@%%@AE@% %@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%num%@AE@% Number of elements %@AI@%size%@AE@% Length in bytes of each element %@AB@%Returns%@AE@% A void pointer to the allocated space if successful, %@AB@%NULL%@AE@% if not ──────────────────────────────────────────────────────────────────────────── %@AB@%free, _ffree, hfree, _nfree%@AE@% - Frees a block of memory previously allocated by the corresponding %@AB@%malloc%@AE@% routine. The corresponding routines are listed below:%@NL@% %@NL@% %@AB@%Free Function%@AE@% %@AB@%Allocation Function%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%_ffree%@AE@% %@AB@%_fmalloc%@AE@% %@AB@%free%@AE@% %@AB@%calloc, malloc, realloc%@AE@% %@AB@%hfree%@AE@% %@AB@%halloc%@AE@% %@AB@%_nfree%@AE@% %@AB@%_nmalloc%@AE@% %@AB@%Includes%@AE@% MALLOC.H, STDLIB.H (ANSI-compatible %@AB@%free%@AE@% only) %@AB@%Prototypes%@AE@% %@AB@%void _ffree( void _far *%@AE@%%@AI@%memblock %@AE@%%@AB@%);%@AE@% %@AB@%void free( void *%@AE@%%@AI@%memblock%@AE@%%@AB@% );%@AE@% void _nfree( void near *%@AI@%memblock%@AE@%%@AB@% );%@AE@% %@AB@%void hfree( void huge *%@AE@%%@AI@%%@AE@% %@AI@%memblock%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%memblock%@AE@% Allocated memory block %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%malloc , _fmalloc, _nmalloc%@AE@% - Allocates a block of memory. The %@AB@%_fmalloc%@AE@% function allocates the block in the far heap. The %@AB@%_nmalloc%@AE@% function allocates the block in the near heap.%@NL@% %@NL@% %@AB@%Includes%@AE@% MALLOC.H, STDLIB.H (ANSI-compatible %@AB@%%@AE@% %@AB@%malloc%@AE@% only) %@AB@%Prototypes%@AE@% %@AB@%void *malloc( size_t %@AE@%%@AI@%size %@AE@%%@AB@%);%@AE@% void _far *_fmalloc( size_t %@AI@%size %@AE@%%@AB@%);%@AE@% void near *_nmalloc( size_t %@AI@%size %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%size%@AE@% Bytes to allocate %@AB@%Returns%@AE@% A void pointer to the allocated space if successful, %@AB@%NULL%@AE@% if not ──────────────────────────────────────────────────────────────────────────── %@AB@%realloc%@AE@% - Reallocates a block. %@NL@% %@NL@% %@AB@%Include%@AE@% MALLOC.H, STDLIB.H %@AB@%Prototype%@AE@% %@AB@%void *realloc( void *%@AE@%%@AI@%memblock%@AE@%%@AB@%, size_t %@AE@%%@AI@%%@AE@% %@AI@%size%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%memblock%@AE@% Pointer to previously allocated memory block %@AI@%size%@AE@% New size in bytes %@AB@%Returns%@AE@% A pointer to the reallocated memory if successful, %@AB@%NULL%@AE@% if not %@NL@% %@2@%%@CR:C6A-B0013 @%%@AB@%Process-Control Routines%@AE@%%@EH@%%@NL@% %@NL@% The term "process" refers to a program being executed by the operating system. %@NL@% %@NL@% Use the process-control routines to %@NL@% %@NL@% %@NL@% ■ Terminate a process (%@AB@%abort%@AE@%, %@AB@%exit%@AE@%, and %@AB@%_exit%@AE@%)%@NL@% %@NL@% ■ Call a new function when a process terminates (%@AB@%atexit%@AE@%)%@NL@% %@NL@% ■ Start a new process (%@AB@%system%@AE@%) %@NL@% %@NL@% %@NL@% Use the %@AB@%abort%@AE@% and %@AB@%_exit%@AE@% functions to exit without flushing stream buffers. Use the %@AB@%exit%@AE@% function to exit after flushing stream buffers. %@NL@% %@NL@% Use the %@AB@%atexit%@AE@% function to create a list of functions to be executed when the calling program exits. %@NL@% %@NL@% Use the %@AB@%system%@AE@% call to execute a given MS-DOS command. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%abort%@AE@% - Aborts a process.%@NL@% %@NL@% %@AB@%Include%@AE@% PROCESS.H or STDLIB.H %@AB@%Prototype%@AE@% %@AB@%void abort( void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%atexit%@AE@% - Executes functions at program termination.%@NL@% %@NL@% %@AB@%Include%@AE@% STDLIB.H %@AB@%Prototype%@AE@% %@AB@%int atexit( void (*%@AE@%%@AI@%func%@AE@%%@AB@%)( void ) );%@AE@% %@AB@%Argument%@AE@% %@AI@%func%@AE@% Function to be called %@AB@%Returns%@AE@% A pointer to %@AI@%func%@AE@% if successful, %@AB@%NULL%@AE@% if not ──────────────────────────────────────────────────────────────────────────── %@AB@%exit, _exit%@AE@% - Terminates the process after flushing buffers (%@AB@%exit%@AE@%); terminates the process without flushing buffers (%@AB@%_exit%@AE@%).%@NL@% %@NL@% %@AB@%Include%@AE@% PROCESS.H or%@AB@% %@AE@%STDLIB.H%@AB@%%@AE@% %@AB@%Prototypes%@AE@% %@AB@%void exit( int %@AE@%%@AI@%status %@AE@%%@AB@%);%@AE@% %@AB@%void _exit( int %@AE@%%@AI@%status%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%status%@AE@% Exit status %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%system%@AE@% - Executes an MS-DOS command.%@NL@% %@NL@% %@AB@%Include%@AE@% PROCESS.H, STDLIB.H %@AB@%Prototype%@AE@% %@AB@%int system( const char *%@AE@%%@AI@%command %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%command%@AE@% Command to be executed%@AB@%%@AE@% %@AB@%Returns%@AE@% 0 if successful, -1 if not %@AB@%errno%@AE@%: %@AB@%E2BIG, ENOENT, ENOEXEC, ENOMEM%@AE@% %@NL@% %@2@%%@CR:C6A-B0014 @%%@AB@%Searching and Sorting Routines%@AE@%%@EH@%%@NL@% %@NL@% The %@AB@%bsearch%@AE@%, %@AB@%lfind%@AE@%, %@AB@%lsearch%@AE@%, and %@AB@%qsort%@AE@% routines provide helpful binary-search, linear-search, and quick-sort utilities. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%bsearch%@AE@% - Performs a binary search.%@NL@% %@NL@% %@AB@%Includes%@AE@% STDLIB.H, SEARCH.H %@AB@%Prototype%@AE@% %@AB@%void *bsearch( const void *%@AE@%%@AI@%key%@AE@%%@AB@%, const %@AE@% %@AB@%void *%@AE@%%@AI@%base%@AE@%%@AB@%,%@AE@% size_t %@AI@%num%@AE@%%@AB@%, size_t %@AE@%%@AI@%width%@AE@%%@AB@%, int( *%@AE@%%@AI@%compare %@AE@% %@AB@%)( const void *%@AE@%%@AI@%elem1%@AE@%%@AB@%,%@AE@% const void *%@AI@%elem2%@AE@%%@AB@% ) );%@AE@% %@AB@%Arguments%@AE@% %@AI@%key%@AE@% Object to search for %@AI@%base%@AE@% Pointer to base of search data %@AI@%num%@AE@% Number of elements %@AI@%width%@AE@% Width of elements %@AI@%compare%@AE@% Compare function %@AI@%elem1%@AE@%, %@AI@%%@AE@% Array elements to compare %@AI@%elem2%@AE@% %@AB@%Returns%@AE@% A pointer if successful, %@AB@%NULL%@AE@% if not ──────────────────────────────────────────────────────────────────────────── %@AB@%lfind, lsearch%@AE@% - Performs a linear search for given value. If the value is not found, %@AB@%lsearch%@AE@% adds it to the end of the list.%@NL@% %@NL@% %@AB@%Includes%@AE@% STDLIB.H, SEARCH.H %@AB@%Prototypes%@AE@% %@AB@%char *lfind( char *%@AE@%%@AI@%key%@AE@%%@AB@%, char *%@AE@%%@AI@%base%@AE@%%@AB@%, %@AE@% %@AB@%unsigned *%@AE@%%@AI@%num%@AE@%%@AB@%,%@AE@% unsigned %@AI@%width%@AE@%%@AB@%, int( *%@AE@%%@AI@%compare %@AE@%%@AB@%)( const %@AE@% %@AB@%void *%@AE@%%@AI@%elem1%@AE@%%@AB@%,%@AE@% const void *%@AI@%elem2%@AE@%%@AB@% ) );%@AE@% char *lsearch( const char *%@AI@%key%@AE@%%@AB@%, const %@AE@% %@AB@%char *%@AE@%%@AI@%base%@AE@%%@AB@%,%@AE@% unsigned *%@AI@%num%@AE@%%@AB@%, unsigned %@AE@%%@AI@%width%@AE@%%@AB@%, int( *%@AE@%%@AI@%%@AE@% %@AI@%compare %@AE@%%@AB@%)%@AE@% ( const void *%@AI@%elem1%@AE@%%@AB@%, const void *%@AE@%%@AI@%elem2 %@AE@%%@AB@%)%@AE@% %@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%key%@AE@% Object to search for %@AI@%base%@AE@% Pointer to base of search data %@AI@%num%@AE@% Number of elements %@AI@%width%@AE@% Width of elements %@AI@%compare%@AE@% Compare function %@AI@%elem1%@AE@%, %@AI@%%@AE@% Array elements to compare %@AI@%elem2%@AE@% %@AB@%Returns%@AE@% A pointer if successful, %@AB@%NULL%@AE@% if not ──────────────────────────────────────────────────────────────────────────── %@AB@%qsort%@AE@% - Performs a quick sort.%@NL@% %@NL@% %@AB@%Includes%@AE@% STDLIB.H, SEARCH.H %@AB@%Prototype%@AE@% %@AB@%void qsort( void *%@AE@%%@AI@%base%@AE@%%@AB@%, size_t %@AE@%%@AI@%num%@AE@%%@AB@%, %@AE@% %@AB@%size_t %@AE@%%@AI@%width%@AE@%%@AB@%,%@AE@% int( *%@AI@%compare%@AE@%%@AB@% )( const void *%@AE@%%@AI@%elem1%@AE@%%@AB@%, %@AE@% %@AB@%const void *%@AE@%%@AI@%elem2 %@AE@%%@AB@%) );%@AE@% %@AB@%Arguments%@AE@% %@AI@%base%@AE@% Start of target array %@AI@%num%@AE@% Array size in elements %@AI@%width%@AE@% Element size in bytes %@AI@%compare%@AE@% Compare function %@AI@%elem1%@AE@%, %@AI@%%@AE@% Array elements to compare %@AI@%elem2%@AE@% %@AB@%Returns%@AE@% Void%@AB@%%@AE@% %@NL@% %@2@%%@CR:C6A-B0015 @%%@AB@%String-Manipulation Routines%@AE@%%@EH@%%@NL@% %@NL@% A wide variety of string routines is available in the run-time library. With these functions, you can do the following: %@NL@% %@NL@% %@NL@% ■ Copy strings (%@AB@%strcat%@AE@%, %@AB@%strcpy%@AE@%, %@AB@%strdup%@AE@%, %@AB@%strncat%@AE@%, %@AB@%strncpy%@AE@%)%@NL@% %@NL@% ■ Search for strings, individual characters, or characters from a given set (%@AB@%strchr%@AE@%, %@AB@%strcspn%@AE@%, %@AB@%strpbrk%@AE@%, %@AB@%strrchr%@AE@%, %@AB@%strspn%@AE@%, %@AB@%strstr%@AE@%)%@NL@% %@NL@% ■ Perform string comparisons (%@AB@%strcmp%@AE@%, %@AB@%strcmpi%@AE@%, %@AB@%stricmp%@AE@%, %@AB@%strncmp%@AE@%, %@AB@%strnicmp%@AE@%)%@NL@% %@NL@% ■ Find the length of a string (%@AB@%strlen%@AE@%)%@NL@% %@NL@% ■ Convert strings to a different case (%@AB@%strlwr%@AE@%, %@AB@%strupr%@AE@%)%@NL@% %@NL@% ■ Set characters of the string to a given character (%@AB@%strnset%@AE@%, %@AB@%strset%@AE@%)%@NL@% %@NL@% ■ Break strings into tokens (%@AB@%strtok%@AE@%)%@NL@% %@NL@% %@NL@% All string functions work on null-terminated character strings. %@NL@% %@NL@% Use the buffer-manipulation routines described earlier in this appendix for manipulating character arrays that do not end with a null character. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%strcat, strcpy, strdup, strncat, strncpy%@AE@% - Use these routines to copy and concatenate strings. The list below describes each function.%@NL@% %@NL@% %@AB@%Function%@AE@% %@AB@%Action%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%strcat%@AE@% Append (concatenate) a string %@AB@%strcpy%@AE@% Copy one string to another %@AB@%strdup%@AE@% Duplicate a string %@AB@%strncat%@AE@% Append a specified number of characters to a string %@AB@%strncpy%@AE@% Copy a specified number of characters from one string to another %@AB@%Include%@AE@% STRING.H %@AB@%Prototypes%@AE@% %@AB@%char *strcat( char *%@AE@%%@AI@%dest%@AE@%%@AB@%, const char *%@AE@%%@AI@%%@AE@% %@AI@%src%@AE@% ); char *strcpy( char *%@AI@%dest%@AE@%%@AB@%, const char *%@AE@%%@AI@%%@AE@% %@AI@%src%@AE@% ); char *strdup( const char *%@AI@%string %@AE@%%@AB@%);%@AE@% char *strncat( char *%@AI@%dest%@AE@%%@AB@%, const char *%@AE@%%@AI@%%@AE@% %@AI@%src%@AE@%%@AB@%, size_t %@AE@%%@AI@%n%@AE@%%@AB@% );%@AE@% char *strncpy( char *%@AI@%dest%@AE@%%@AB@%, const char *%@AE@%%@AI@%%@AE@% %@AI@%src%@AE@%%@AB@%, size_t %@AE@%%@AI@%n %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%dest%@AE@% Destination string %@AI@%src%@AE@% Source string %@AI@%string%@AE@% Null-terminated string %@AI@%n%@AE@% Number of characters %@AB@%Returns%@AE@% %@AB@%strcat:%@AE@% a pointer to the concatenated string %@AB@%strcpy%@AE@%: %@AI@%dest%@AE@% string %@AB@%strdup%@AE@%: a pointer if successful, %@AB@%NULL%@AE@% if not %@AB@%strncat, strncpy%@AE@%: a pointer to%@AI@% dest%@AE@% string ──────────────────────────────────────────────────────────────────────────── %@AB@%strchr, strcspn, strpbrk, strrchr, strspn, strstr%@AE@% - Use these routines to search strings. The list below describes each function.%@NL@% %@NL@% %@AB@%Function%@AE@% %@AB@%Action%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%strchr%@AE@% Finds first occurrence of a given character in a string %@AB@%strcspn%@AE@% Finds first occurrence of a character from a given character set in a string %@AB@%strpbrk%@AE@% Finds first occurrence of a character from one string in another %@AB@%strrchr%@AE@% Finds last occurrence of a given character in a string %@AB@%strspn%@AE@% Finds first substring from a given character set in a string %@AB@%strstr%@AE@% Finds first occurrence of a given string in another string %@AB@%Include%@AE@% STRING.H %@AB@%Prototypes%@AE@% %@AB@%char *strchr( const char *%@AE@%%@AI@%string%@AE@%%@AB@%, int%@AE@%%@AI@% c%@AE@% %@AB@% );%@AE@% size_t strcspn( const char *%@AI@%string1%@AE@%%@AB@%, %@AE@% %@AB@%const char *%@AE@%%@AI@%string2 %@AE@%%@AB@%);%@AE@% char *strpbrk( const char *%@AI@%string1%@AE@%%@AB@%, %@AE@% %@AB@%const char *%@AE@%%@AI@%string2%@AE@%%@AB@% );%@AE@% char *strrchr( const char *%@AI@%string%@AE@%%@AB@%, int %@AE@%%@AI@%c%@AE@% %@AB@% );%@AE@% size_t strspn( const char *%@AI@%string1%@AE@%%@AB@%, %@AE@% %@AB@%const char *%@AE@%%@AI@%string2 %@AE@%%@AB@%);%@AE@% char *strstr( const char *%@AI@%string1%@AE@%%@AB@%, const%@AE@% %@AB@%char *%@AE@%%@AI@%string2%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%string%@AE@%, %@AI@%%@AE@% Null-terminated strings %@AI@%string1%@AE@%, %@AI@%%@AE@% %@AI@%string2%@AE@% %@AI@%c%@AE@% Character %@AB@%Returns%@AE@% %@AB@%strchr%@AE@%: a pointer if successful, %@AB@%NULL%@AE@% if not %@AB@%strcspn%@AE@%: an offset into %@AI@%string1%@AE@% %@AB@%strpbrk%@AE@%: a pointer to the first matching character in %@AI@%string1%@AE@%, %@AB@%NULL%@AE@% if no match is found %@AB@%strrchr%@AE@%: a pointer to the last occurrence of %@AI@%c%@AE@% in%@AI@% string%@AE@%, %@AB@%NULL%@AE@% if %@AI@%c%@AE@% is not found %@AB@%strspn%@AE@%: the position of the first nonmatching character in %@AI@%string1%@AE@% %@AB@%strstr%@AE@%: a pointer to the first occurrence of%@AI@% string2%@AE@% in %@AI@%string1%@AE@%, or %@AB@%NULL%@AE@% if %@AI@%string2%@AE@% is not found ──────────────────────────────────────────────────────────────────────────── %@AB@%strcmp, strcmpi, stricmp, strncmp, strnicmp%@AE@% - Use these routines to compare strings. The list below describes the operation of each function. An "%@AB@%n%@AE@%" in the function name means to use up to %@AB@%n%@AE@% characters; "%@AB@%i%@AE@%" in the name means to operate without regard to the case of the string.%@NL@% %@NL@% %@AB@%Function%@AE@% %@AB@%Action%@AE@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@% %@AB@%strcmp%@AE@% Compares two strings %@AB@%strcmpi%@AE@% Compares two strings without regard to case ("%@AB@%i%@AE@%" indicates that this function is case insensitive) %@AB@%stricmp%@AE@% Compares two strings without regard to case (identical to %@AB@%strcmpi%@AE@%) %@AB@%strncmp%@AE@% Compares characters of two strings %@AB@%strnicmp%@AE@% Compares characters of two strings without regard to case %@AB@%Include%@AE@% STRING.H %@AB@%Prototypes%@AE@% %@AB@%int strcmp( const char *%@AE@%%@AI@%string1%@AE@%%@AB@%, const %@AE@% %@AB@%char *%@AE@%%@AI@%string2 %@AE@%%@AB@%);%@AE@% int strcmpi( const char *%@AI@%string1%@AE@%%@AB@%, const %@AE@% %@AB@%char *%@AE@%%@AI@%string2%@AE@%%@AB@% );%@AE@% int stricmp( const char *%@AI@%string1%@AE@%%@AB@%, const %@AE@% %@AB@%char *%@AE@%%@AI@%string2 %@AE@%%@AB@%);%@AE@% int strncmp( const char *%@AI@%string1%@AE@%%@AB@%, const %@AE@% %@AB@%char *%@AE@%%@AI@%string2%@AE@%%@AB@%, size_t %@AE@%%@AI@%n%@AE@%%@AB@% );%@AE@% int strnicmp( const char *%@AI@%string1%@AE@%%@AB@%, const%@AE@% %@AB@%char *%@AE@%%@AI@%string2%@AE@%%@AB@%, size_t %@AE@%%@AI@%n %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%string1%@AE@% Destination string %@AI@%string2%@AE@% Source string %@AI@%n%@AE@% Number of characters %@AB@%Returns%@AE@% A negative value if %@AI@%string1%@AE@%, 0 if %@AI@%%@AE@% %@AI@%string1%@AE@% = %@AI@%string2%@AE@%, a positive value if%@AI@% string1>string2%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%strlen%@AE@% - The %@AB@%strlen%@AE@% function returns the length in bytes of the string, not including the terminating null character (%@AB@%\0%@AE@%).%@NL@% %@NL@% %@AB@%Include%@AE@% STRING.H %@AB@%Prototype%@AE@% %@AB@%size_t strlen( const char *%@AE@%%@AI@%string%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%string%@AE@% Null-terminated string %@AB@%Returns%@AE@% The string length ──────────────────────────────────────────────────────────────────────────── %@AB@%strlwr, strupr%@AE@% - The %@AB@%strlwr%@AE@% and %@AB@%strupr%@AE@% routines convert the characters of a string to lowercase and uppercase, respectively.%@NL@% %@NL@% %@AB@%Include%@AE@% STRING.H %@AB@%Prototypes%@AE@% %@AB@%char *strlwr( char *%@AE@%%@AI@%string %@AE@%%@AB@%);%@AE@% %@AB@%char *strupr( char *%@AE@%%@AI@%string %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%string%@AE@% String to be converted %@AB@%Returns%@AE@% A pointer to a copy of the converted input string ──────────────────────────────────────────────────────────────────────────── %@AB@%strnset, strset%@AE@% - The routines %@AB@%strnset%@AE@% and %@AB@%strset%@AE@% set the characters of a string to a specified character. The%@AB@% strnset%@AE@% function sets the first %@AI@%n%@AE@% characters in the string to the specified character. The %@AB@%strset%@AE@% function sets the entire string to the specified character.%@NL@% %@NL@% %@AB@%Include%@AE@% STRING.H %@AB@%Prototypes%@AE@% %@AB@%char *strnset( char *%@AE@%%@AI@%string%@AE@%%@AB@%, int %@AE@%%@AI@%c%@AE@%%@AB@%, %@AE@% %@AB@%size_t %@AE@%%@AI@%n%@AE@%%@AB@% );%@AE@% char*strset( char *%@AB@%string, int c );%@AE@% %@AB@%Arguments%@AE@% %@AI@%string%@AE@% String to be set %@AI@%c%@AE@% Character setting %@AI@%n%@AE@% Number of characters set %@AB@%Returns%@AE@% A pointer to %@AI@%string%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%strtok%@AE@% - The %@AB@%strtok%@AE@% function finds a token in a string. A "token" is a series of characters delimited by a character from a specified set. For example, use the %@AB@%strtok%@AE@% function to break an input line into the component words.%@NL@% %@NL@% %@AB@%Include%@AE@% STRING.H %@AB@%Prototype%@AE@% %@AB@%char *strtok( char *%@AE@%%@AI@%string1%@AE@%%@AB@%, const char%@AE@% %@AB@%*%@AE@%%@AI@%string2%@AE@%%@AB@% );%@AE@% %@AB@%Arguments%@AE@% %@AI@%string1%@AE@% String containing tokens %@AI@%string2%@AE@% Set of delimiter characters %@AB@%Returns%@AE@% A pointer to a token in %@AI@%string1%@AE@% %@NL@% %@2@%%@CR:C6A-B0016 @%%@AB@%Time Routines%@AE@%%@EH@%%@NL@% %@NL@% Use the time routines to get the current time, convert it to a convenient format, and store it according to your particular needs. %@NL@% %@NL@% The current time is always taken from the system time. %@NL@% %@NL@% The %@AB@%time%@AE@% function returns the current time as the number of seconds elapsed since Greenwich mean time, January 1, 1970. %@NL@% %@NL@% Use the %@AB@%asctime%@AE@%, %@AB@%ctime%@AE@%, %@AB@%gmtime%@AE@%, and %@AB@%mktime%@AE@% functions to manipulate the time value. %@NL@% %@NL@% ──────────────────────────────────────────────────────────────────────────── %@AB@%asctime%@AE@% - Converts a time from a structure to a character string.%@NL@% %@NL@% %@AB@%Include%@AE@% TIME.H %@AB@%Prototype%@AE@% %@AB@%char *asctime( const struct tm *%@AE@%%@AI@%timeptr %@AE@% %@AI@%%@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%timeptr%@AE@% Time structure %@AB@%Returns%@AE@% A pointer to string result ──────────────────────────────────────────────────────────────────────────── %@AB@%clock%@AE@% - Returns the elapsed CPU time for a process.%@NL@% %@NL@% %@AB@%Include%@AE@% TIME.H %@AB@%Prototype%@AE@% %@AB@%clock_t clock( void );%@AE@% %@AB@%Arguments%@AE@% None %@AB@%Returns%@AE@% The elapsed processor time if successful, -1 if not ──────────────────────────────────────────────────────────────────────────── %@AB@%ctime%@AE@% - Converts time from a long integer to a character string.%@NL@% %@NL@% %@AB@%Include%@AE@% TIME.H %@AB@%Prototype%@AE@% %@AB@%char *ctime( const time_t *%@AE@%%@AI@%timer %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%timer%@AE@% Pointer to stored time %@AB@%Returns%@AE@% A pointer to string result; %@AB@%NULL%@AE@% if time represents a date before 1980 ──────────────────────────────────────────────────────────────────────────── %@AB@%difftime%@AE@% - Computes the difference between two times.%@NL@% %@NL@% %@AB@%Include%@AE@% TIME.H %@AB@%Prototype%@AE@% %@AB@%double difftime( time_t %@AE@%%@AI@%timer1%@AE@%%@AB@%, time_t %@AE@% %@AI@%timer0 %@AE@%%@AB@%);%@AE@% %@AB@%Arguments%@AE@% %@AI@%timer0%@AE@%,%@AI@% %@AE@% Beginning and ending times %@AI@%timer1%@AE@% %@AB@%Returns%@AE@% The difference in elapsed time between%@AI@% %@AE@% %@AI@%timer1%@AE@% and%@AI@% timer0%@AE@% ──────────────────────────────────────────────────────────────────────────── %@AB@%ftime%@AE@% - Gets current system time as structure.%@NL@% %@NL@% %@AB@%Includes%@AE@% SYS\TYPES.H, SYS\TIMEB.H %@AB@%Prototype%@AE@% %@AB@%void ftime( struct timeb *%@AE@%%@AI@%timeptr %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%timeptr%@AE@% Pointer to time structure %@AB@%Returns%@AE@% Void ──────────────────────────────────────────────────────────────────────────── %@AB@%gmtime%@AE@% - Converts time from integer to structure.%@NL@% %@NL@% %@AB@%Include%@AE@% TIME.H %@AB@%Prototype%@AE@% %@AB@%struct tm *gmtime( const time_t *%@AE@%%@AI@%timer %@AE@% %@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%timer%@AE@% Pointer to stored time %@AB@%Returns%@AE@% A pointer to a structure ──────────────────────────────────────────────────────────────────────────── %@AB@%mktime%@AE@% - Converts time to a calendar value.%@NL@% %@NL@% %@AB@%Include%@AE@% TIME.H %@AB@%Prototype%@AE@% %@AB@%time_t mktime( struct tm *%@AE@%%@AI@%timeptr %@AE@%%@AB@%);%@AE@% %@AB@%Argument%@AE@% %@AI@%timeptr%@AE@% Local time structure %@AB@%Returns%@AE@% The encoded calendar time if successful, -1 if not ──────────────────────────────────────────────────────────────────────────── %@AB@%time%@AE@% - Gets current system time as a long integer.%@NL@% %@NL@% %@AB@%Include%@AE@% TIME.H %@AB@%Prototype%@AE@% %@AB@%time_t time( time_t *%@AE@%%@AI@%timer%@AE@%%@AB@% );%@AE@% %@AB@%Argument%@AE@% %@AI@%timer%@AE@% Storage location for time %@AB@%Returns%@AE@% The elapsed time %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@NL@% %@CR:C6A-B0028 @%%@1@%%@AB@%Glossary%@AE@%%@EH@%%@NL@% %@AB@%────────────────────────────────────────────────────────────────────────────%@AE@%%@NL@%%@NL@% %@NL@% %@2@%%@AB@%8087 or 80287 coprocessor:%@AE@%%@EH@%%@NL@% %@3@%Intel hardware products that provide very fast and precise floating-point%@EH@% number processing.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%%@CR:C6A00170029 @%%@CR:C6A00170030 @%aggregate types:%@AE@%%@EH@%%@NL@% %@3@%Arrays, structures, and unions.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%%@CR:C6A00170031 @%ANSI (American National Standards Institute):%@AE@%%@EH@%%@NL@% %@3@%The national institute responsible for defining programming-language%@EH@% standards to promote portability of these languages between different computer systems. The ANSI standard for C will become official in 1990.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%argc:%@AE@%%@EH@%%@NL@% %@3@%The traditional name for the first argument to the %@AB@%main%@AE@% function in a C%@EH@% source program. It is an integer that specifies how many arguments are passed to the program from the command line.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%%@CR:C6A00170032 @%argument:%@AE@%%@EH@%%@NL@% %@3@%A value passed to a function.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%argv:%@AE@%%@EH@%%@NL@% %@3@%The traditional name for the second argument to the %@AB@%main%@AE@% function in a C%@EH@% source program. It is a pointer to an array of strings. Traditionally, the first string is the program name, and each following string is an argument passed to the program from the command line.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%%@CR:C6A00170033 @%array:%@AE@%%@EH@%%@NL@% %@3@%A set of elements with the same type.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%array pointer:%@AE@%%@EH@%%@NL@% %@3@%A pointer that holds the address of any element of an array.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%%@CR:C6A00170034 @%ASCII (American Standard Code for Information Interchange):%@AE@%%@EH@%%@NL@% %@3@%A set of 256 codes that many computers use to represent letters, digits,%@EH@% special characters, and other symbols. Only the first 128 of these codes are standardized; the remaining 128 are special characters that are defined by the computer manufacturer.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%%@CR:C6A00170035 @%%@CR:C6A00170036 @%automatic variable:%@AE@%%@EH@%%@NL@% %@3@%A variable, declared in a block, whose value is discarded when the program%@EH@% exits from the block. See "static variable" and "lifetime."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%background color:%@AE@%%@EH@%%@NL@% %@3@%A long integer representing the background color of the display screen. In%@EH@% graphics modes, the background color applies to the entire screen. In text modes, the background color specifies the text background for each character. See "foreground color."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%basic data types:%@CR:C6A00170037 @%%@CR:C6A00170038 @%%@AE@%%@EH@%%@NL@% %@3@%The integral, enumerated, floating-point, and pointer types in the C%@EH@% language.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%binary file:%@CR:C6A00170039 @%%@AE@%%@EH@%%@NL@% %@3@%A file that is not used for text processing. It may be an executable file, a%@EH@% data file, or some other nontext file.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%binary format:%@CR:C6A00170040 @%%@AE@%%@EH@%%@NL@% %@3@%A method of data representation in which data are stored directly from%@EH@% memory to disk with no translations. In binary format, numeric values are stored as binary numbers and are not translated to ASCII characters.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%binary mode:%@CR:C6A00170041 @%%@AE@%%@EH@%%@NL@% %@3@%A method of accessing files in which no translations are performed. There is%@EH@% no specific end-of-file character.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%binary operator:%@CR:C6A00170042 @%%@CR:C6A00170043 @%%@AE@%%@EH@%%@NL@% %@3@%An operator that takes two operands. Binary operators in the C language are%@EH@% the multiplicative operators (%@AB@%*/%@AE@%), additive operators (%@AB@%+ -%@AE@%), shift operators (%@AB@%<< >>%@AE@%), relational operators (%@AB@%< >> <= >= == !=%@AE@%), bitwise operators (%@AB@%& %@AB@%| ^%@AE@%), logical operators (%@AB@%&& ||%@AE@%), and the sequential-evaluation operator (%@AB@%,%@AE@%).%@NL@%%@NL@% %@NL@% %@2@%%@AB@%bit:%@CR:C6A00170044 @%%@AE@%%@EH@%%@NL@% %@3@%A binary digit (either 0 or 1), the smallest unit of information used with%@EH@% computers. Eight bits make up one byte.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%bit field:%@CR:C6A00170045 @%%@CR:C6A00170046 @%%@AE@%%@EH@%%@NL@% %@3@%A type of structure that allows manipulation of individual bits or groups of%@EH@% bits. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%bit-mapped font:%@CR:C6A00170047 @%%@AE@%%@EH@%%@NL@% %@3@%A font in which each character is defined by (mapped to) the bits of an%@EH@% array.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%bitwise operator:%@CR:C6A00170048 @%%@CR:C6A00170049 @%%@CR:C6A00170050 @%%@CR:C6A00170051 @%%@CR:C6A00170052 @%%@CR:C6A00170053 @%%@CR:C6A00170054 @%%@CR:C6A00170055 @%%@CR:C6A00170056 @%%@CR:C6A00170057 @%%@CR:C6A00170058 @%%@EH@% %@AB@%%@CR:C6A00170059 @%%@CR:C6A00170060 @%%@CR:C6A00170061 @%%@CR:C6A00170062 @%%@AE@%%@NL@% %@3@%An operator used to manipulate bits in an integer expression. Bitwise%@EH@% operators in the C language are %@AB@%&%@AE@% (AND),%@AB@% |%@AE@% (inclusive OR), %@AB@%^%@AE@% (exclusive OR), %@AB@%%@AE@% (left shift), %@AB@%>>%@AE@% (right shift), and %@AB@%~%@AE@% (one's complement).%@NL@%%@NL@% %@NL@% %@2@%%@AB@%block:%@CR:C6A00170063 @%%@AE@%%@EH@%%@NL@% %@3@%A sequence of declarations, definitions, and statements enclosed within%@EH@% curly braces ({}).%@NL@%%@NL@% %@NL@% %@2@%%@AB@%bounding rectangle:%@CR:C6A00170064 @%%@AE@%%@EH@%%@NL@% %@3@%An imaginary rectangle that defines the outer limits of a rounded shape such%@EH@% as an ellipse, arc, or pie.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%byte:%@CR:C6A00170065 @%%@AE@%%@EH@%%@NL@% %@3@%The unit of measure used for computer memory and data storage. One byte%@EH@% contains eight bits and can store one ASCII character.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%case label:%@CR:C6A00170066 @%%@AE@%%@EH@%%@NL@% %@3@%The %@AB@%case%@AE@% keyword and the constant, or constant expression, that follows it. %@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%CGA:%@AE@%%@EH@%%@NL@% %@3@%IBM's Color Graphics Adapter.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%character code:%@AE@%%@EH@%%@NL@% %@3@%A numeric code that represents a character. The default ASCII character set%@EH@% used in all PCs and PS/2s comprises 256 eight-bit character codes.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%character constant:%@CR:C6A00170067 @%%@AE@%%@EH@%%@NL@% %@3@%A character enclosed in single quotes, for example, %@AS@%'p'%@AE@%. A character%@EH@% constant has a type of %@AB@%char%@AE@%. See "string constant."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%character set:%@AE@%%@EH@%%@NL@% %@3@%A set of alphabetic and numeric characters and symbols.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%clipping:%@AE@%%@EH@%%@NL@% %@3@%The process of determining which parts of a graphics image lie within the%@EH@% clipping region. Parts of the image that lie outside this region are "clipped"; that is, they are not displayed.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%clipping region:%@CR:C6A00170068 @%%@AE@%%@EH@%%@NL@% %@3@%The rectangular area of the screen where graphics display occurs.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%color index:%@CR:C6A00170069 @%%@AE@%%@EH@%%@NL@% %@3@%A short integer that represents a displayable color. See "remapping" and%@EH@% "color value."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%color value:%@CR:C6A00170070 @%%@AE@%%@EH@%%@NL@% %@3@%A long integer representing an absolute color. See "remapping" and "color%@EH@% index."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%command-line argument:%@AE@%%@EH@%%@NL@% %@3@%A value passed to a program when the program begins execution.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%%@CR:C6A00170071 @%conditional expression:%@AE@%%@EH@%%@NL@% %@3@%An expression consisting of three operands joined by the ternary (%@AB@%? :%@AE@%)%@EH@% operator. Similar to an %@AB@%if%@AE@%-%@AB@%else%@AE@% construct, a conditional expression is used to evaluate either of two expressions depending on the value of a third expression. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%constant expression:%@CR:C6A00170072 @%%@CR:C6A00170073 @%%@AE@%%@EH@%%@NL@% %@3@%An expression that evaluates to a constant. A constant expression may%@EH@% involve integer constants, character constants, floating-point constants, enumeration constants, type casts to integral and floating-point types, and other constant expressions. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%current color:%@CR:C6A00170074 @%%@CR:C6A00170075 @%%@AE@%%@EH@%%@NL@% %@3@%The color index for the color in which graphics pixels are displayed. The%@EH@% current color can be examined with %@AB@%_getcolor%@AE@% or changed with%@AB@% _setcolor%@AE@%. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%declaration:%@CR:C6A00170076 @%%@AE@%%@EH@%%@NL@% %@3@%A construct that associates the name and the attributes of a variable,%@EH@% function, or type. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%default:%@AE@%%@EH@%%@NL@% %@3@%A condition that is assumed by a program if not specified.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%definition:%@CR:C6A00170077 @%%@AE@%%@EH@%%@NL@% %@3@%A construct that initializes and allocates storage for a variable or that%@EH@% specifies the name, formal parameters, body, and return type of a function.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%%@CR:C6A00170078 @%%@CR:C6A00170079 @%dimension:%@AE@%%@EH@%%@NL@% %@3@%The number of subscripts required to specify a single array element.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%directive:%@CR:C6A00170080 @%%@AE@%%@EH@%%@NL@% %@3@%An instruction to the C preprocessor to perform an action on source-program%@EH@% text before compilation.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%double precision:%@CR:C6A00170081 @%%@AE@%%@EH@%%@NL@% %@3@%A real (floating-point) value that occupies eight bytes of memory. Double%@EH@% precision values are accurate to 15 or 16 digits.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%EGA:%@AE@%%@EH@%%@NL@% %@3@%Enhanced Graphics Adapter.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%enumeration type:%@CR:C6A00170082 @%%@CR:C6A00170083 @%%@AE@%%@EH@%%@NL@% %@3@%A user-defined data type with values that range over a set of named integral%@EH@% constants.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%escape sequence:%@CR:C6A00170084 @%%@AE@%%@EH@%%@NL@% %@3@%A specific combination of a backslash (%@AB@%\%@AE@%) followed by a letter or%@EH@% combination of digits, which represents white space and nonprinting characters within strings and character constants. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%expression:%@CR:C6A00170085 @%%@AE@%%@EH@%%@NL@% %@3@%A combination of operands and operators that yields a single value.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%%@CR:C6A00170086 @%%@CR:C6A00170087 @%external variable:%@AE@%%@EH@%%@NL@% %@3@%A variable that is defined outside any function in a C source file and is%@EH@% used in other source files in the same program.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%file handle:%@CR:C6A00170088 @%%@AE@%%@EH@%%@NL@% %@3@%An integer value that is returned when a library function that performs%@EH@% low-level input/output opens or creates a file. The file handle is used to refer to that file in later operations.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%file pointer:%@CR:C6A00170089 @%%@CR:C6A00170090 @%%@CR:C6A00170091 @%%@AE@%%@EH@%%@NL@% %@3@%A value that keeps track of the current position in an input or output%@EH@% stream. It is updated to reflect the new position each time a read or write operation takes place.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%FILE pointer:%@AE@%%@EH@%%@NL@% %@3@%A pointer to a structure of type FILE that contains information about a%@EH@% file. It is returned by library functions that create or open files and use stream input/output.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%fill flag:%@CR:C6A00170092 @%%@AE@%%@EH@%%@NL@% %@3@%A parameter that determines whether a shape will be drawn as a solid.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%%@CR:C6A00170093 @%fill mask:%@AE@%%@EH@%%@NL@% %@3@%A group of pixels that defines the pattern used to fill a graphics shape.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%fill pattern:%@CR:C6A00170094 @%%@AE@%%@EH@%%@NL@% %@3@%The design defined by the fill mask and used to fill a shape.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%font:%@CR:C6A00170095 @%%@AE@%%@EH@%%@NL@% %@3@%A description of the style and shapes of the characters in a character set. %@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%foreground color:%@CR:C6A00170096 @%%@AE@%%@EH@%%@NL@% %@3@%The color index for the color in which text is displayed. See "background%@EH@% color."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%format specification:%@CR:C6A00170097 @%%@AE@%%@EH@%%@NL@% %@3@%A string that specifies how the %@AB@%printf%@AE@% and %@AB@%scanf%@AE@% families of functions%@EH@% interpret input and output data.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%function:%@CR:C6A00170098 @%%@AE@%%@EH@%%@NL@% %@3@%A collection of declarations and statements that has a unique name and can%@EH@% return a value. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%function body:%@AE@%%@EH@%%@NL@% %@3@%A statement block containing the local variable declarations and statements%@EH@% of a function.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%function call:%@CR:C6A00170099 @%%@AE@%%@EH@%%@NL@% %@3@%An expression that passes control and arguments (if any) to a function.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%function declaration:%@CR:C6A00170100 @%%@CR:C6A00170101 @%%@AE@%%@EH@%%@NL@% %@3@%A declaration that states the name, return type, and storage class of a%@EH@% function that is defined explicitly elsewhere in the program.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%function definition:%@CR:C6A00170102 @%%@AE@%%@EH@%%@NL@% %@3@%A definition that specifies a function's name, its formal parameters, the%@EH@% declarations and statements that define what it does, and (optionally) its return type and storage class.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%function pointer:%@CR:C6A00170103 @%%@AE@%%@EH@%%@NL@% %@3@%A pointer that holds the address of a function.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%function prototype:%@CR:C6A00170104 @%%@CR:C6A00170105 @%%@AE@%%@EH@%%@NL@% %@3@%A function declaration that includes a list of the names and types of formal%@EH@% parameters in the parentheses following the function name.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%global:%@AE@%%@EH@%%@NL@% %@3@%See "visibility."%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%graphics mode:%@CR:C6A00170106 @%%@AE@%%@EH@%%@NL@% %@3@%See "video mode."%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%header file:%@AE@%%@EH@%%@NL@% %@3@%An external source file that contains commonly used declarations and%@EH@% definitions. The %@AB@%#include%@AE@% directive is used to insert the contents of a header file into a C source file.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%hexadecimal:%@CR:C6A00170107 @%%@AE@%%@EH@%%@NL@% %@3@%The base-16 numbering system whose digits are 0 through F. The letters A%@EH@% through F represent the decimal numbers 10 through 15. It is often used in computer programming because it is easily converted to and from binary, the base-2 numbering system the computer itself uses.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%HGC:%@AE@%%@EH@%%@NL@% %@3@%Hercules monochrome Graphics Card. %@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%identifier:%@CR:C6A00170108 @%%@AE@%%@EH@%%@NL@% %@3@%A user-defined name in a C program. Identifiers name variables, functions,%@EH@% macros, constants, and data types.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%include file:%@CR:C6A00170109 @%%@AE@%%@EH@%%@NL@% %@3@%See "header file."%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%Incolor Card:%@CR:C6A00170110 @%%@CR:C6A00170111 @%%@AE@%%@EH@%%@NL@% %@3@%Hercules InColor Card, a 16-color version of the HGC+.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%indirection:%@CR:C6A00170112 @%%@AE@%%@EH@%%@NL@% %@3@%Accessing a data object through a pointer, rather than directly by name.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%initialize:%@CR:C6A00170113 @%%@AE@%%@EH@%%@NL@% %@3@%To assign a value to a variable, often at the time the variable is declared.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%in-line assembler:%@CR:C6A00170114 @%%@AE@%%@EH@%%@NL@% %@3@%The part of QuickC that converts assembly-language instructions into machine%@EH@% language.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%in-line assembly code:%@CR:C6A00170115 @%%@AE@%%@EH@%%@NL@% %@3@%Assembly language instructions that appear within a QuickC source program.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%input/output:%@AE@%%@EH@%%@NL@% %@3@%The processes involved in reading (input) and writing (output) data.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%integer:%@CR:C6A00170116 @%%@AE@%%@EH@%%@NL@% %@3@%A whole number represented in the machine as a 16-bit two's-complement%@EH@% binary number. A signed integer has a range of -32,768 to 32,767. An unsigned integer has a range of 0 to 65,535. See "long integer."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%I/O:%@CR:C6A00170117 @%%@AE@%%@EH@%%@NL@% %@3@%Abbreviation for input/output.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%keyword:%@CR:C6A00170118 @%%@AE@%%@EH@%%@NL@% %@3@%A word with a special, predefined meaning for the C compiler. %@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%%@CR:C6A00170119 @%label:%@AE@%%@EH@%%@NL@% %@3@%A unique name followed by a colon. Labels are used to denote statements to%@EH@% which a %@AB@%goto%@AE@% statement can branch. See "%@AB@%case%@AE@% label."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%library:%@CR:C6A00170120 @%%@AE@%%@EH@%%@NL@% %@3@%A file containing compiled modules. The linker extracts modules from the%@EH@% library file and combines them with the user-created object file to form an executable program.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%lifetime:%@CR:C6A00170121 @%%@CR:C6A00170122 @%%@AE@%%@EH@%%@NL@% %@3@%The time, during program execution, that a variable or function exists. An%@EH@% "automatic" variable has storage and a defined value only in the block where it is defined or declared. A "static" variable exists for the duration of the program. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%line style:%@CR:C6A00170123 @%%@AE@%%@EH@%%@NL@% %@3@%An unsigned short integer (16 bits) that specifies the pattern with which%@EH@% lines will be drawn. Each bit specifies whether a corresponding pixel in the line will be displayed. The default line style is a solid line.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%local:%@AE@%%@EH@%%@NL@% %@3@%See "visibility."%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%long integer:%@AE@%%@EH@%%@NL@% %@3@%A whole number represented inside the machine as a 32-bit two's-complement%@EH@% binary number. A signed long integer has a range of -2,147,483,648 to 2,147,483,647. An unsigned long integer has a range of 0 to 4,294,967,295. See "integer."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%low-level input and output routines:%@AE@%%@EH@%%@NL@% %@3@%Run-time library routines that perform unbuffered, unformatted I/O%@EH@% operations, for example, %@AB@%creat%@AE@%, %@AB@%read%@AE@%, %@AB@%write%@AE@%, and %@AB@%lseek%@AE@%.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%lvalue:%@CR:C6A00170124 @%%@AE@%%@EH@%%@NL@% %@3@%An expression (such as a variable name) that refers to a memory location and%@EH@% is required as the left-hand operand of an assignment operation, or as the single operand of a unary operator.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%machine language:%@CR:C6A00170125 @%%@AE@%%@EH@%%@NL@% %@3@%A series of binary numbers that a computer executes as program instructions.%@EH@% %@NL@%%@NL@% %@NL@% %@2@%%@AB@%macro:%@CR:C6A00170126 @%%@AE@%%@EH@%%@NL@% %@3@%An identifier defined in a %@AB@%#define%@AE@% preprocessor directive to represent%@EH@% another series of characters. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%main function:%@CR:C6A00170127 @%%@CR:C6A00170128 @%%@AE@%%@EH@%%@NL@% %@3@%The function with which program execution begins (the program's entry%@EH@% point).%@NL@%%@NL@% %@NL@% %@2@%%@AB@%manifest constant:%@AE@%%@EH@%%@NL@% %@3@%See "symbolic constant." %@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%MCGA (%@AB@%Multicolor Graphics Array%@AE@%):%@CR:C6A00170129 @%%@AE@%%@EH@%%@NL@% %@3@%The video subsystem integrated into the PS/2 Model 30. Also, Memory%@EH@% Controller Gate Array, one of the components of the Model 30's video subsystem. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%member:%@CR:C6A00170130 @%%@AE@%%@EH@%%@NL@% %@3@%One of the elements of a structure or union.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%member-of operator:%@AE@%%@EH@%%@NL@% %@3@%The dot operator (%@AB@%.%@AE@%), which is used with the name of a structure and one or%@EH@% more fields to identify a structure member.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%mode:%@CR:C6A00170131 @%%@AE@%%@EH@%%@NL@% %@3@%See "video mode."%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%monochrome display:%@AE@%%@EH@%%@NL@% %@3@%A computer monitor capable of showing only two colors─black and a second%@EH@% color such as white, green, or amber. Some monochrome monitors can also show the second color with higher intensity or with underlined text.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%Monochrome Display Adapter (MDA):%@CR:C6A00170132 @%%@AE@%%@EH@%%@NL@% %@3@%A printed-circuit card that controls the display and can show text only at%@EH@% medium resolution in one color.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%newline character:%@CR:C6A00170133 @%%@CR:C6A00170134 @%%@AE@%%@EH@%%@NL@% %@3@%The character used to mark the end of a line in a text file, or the escape%@EH@% sequence (%@AB@%\n%@AE@%) used to represent this character. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%%@CR:C6A00170135 @%%@CR:C6A00170136 @%null character:%@AE@%%@EH@%%@NL@% %@3@%The ASCII character encoded as the value 0, represented as the escape%@EH@% sequence (%@AB@%\0%@AE@%) in a source file. A null character marks the end of a string.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%%@CR:C6A00170137 @%%@CR:C6A00170138 @%null pointer:%@AE@%%@EH@%%@NL@% %@3@%A pointer to nothing, expressed as the value 0.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%one's complement:%@AE@%%@EH@%%@NL@% %@3@%The arithmetic operation in which all 1 bits are converted to 0 bits and%@EH@% vice versa. The tilde character (%@AB@%~%@AE@%) is the one's-complement operator.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%%@CR:C6A00170139 @%operand:%@AE@%%@EH@%%@NL@% %@3@%A constant or variable value that is manipulated in an expression.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%operator:%@CR:C6A00170140 @%%@AE@%%@EH@%%@NL@% %@3@%One or more symbols that specify how the operand or operands of an%@EH@% expression are manipulated. See "unary operator," "binary operator," and "ternary operator."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%origin:%@CR:C6A00170141 @%%@AE@%%@EH@%%@NL@% %@3@%The point on the screen at which the %@AI@%x%@AE@% and %@AI@%y%@AE@% coordinates are both equal to%@EH@% 0. On the physical screen, the origin is at the upper left corner%@AB@%.%@AE@%%@NL@%%@NL@% %@NL@% %@2@%%@AB@%palette:%@CR:C6A00170142 @%%@AE@%%@EH@%%@NL@% %@3@%The displayable colors for a given video mode. The CGA modes operate with a%@EH@% set of predetermined palette colors. The EGA, VGA, and MCGA color modes operate with a redefinable palette of colors. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%parameter:%@CR:C6A00170143 @%%@AE@%%@EH@%%@NL@% %@3@%An identifier that receives a value passed to a function.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%path:%@CR:C6A00170144 @%%@AE@%%@EH@%%@NL@% %@3@%The name that defines the location of a file or directory. A path may%@EH@% include a drive name and one or more directory names.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%PGA (Professional Graphics Adapter):%@CR:C6A00170145 @%%@AE@%%@EH@%%@NL@% %@3@%Another name for IBM's PGC.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%physical coordinates:%@CR:C6A00170146 @%%@AE@%%@EH@%%@NL@% %@3@%The coordinate system defined by the hardware. The physical coordinate%@EH@% system has the origin (0, 0) at the upper left corner of the screen. The value of %@AI@%x%@AE@% increases from left to right, and the value of %@AI@%y%@AE@% increases from top to bottom. See "viewport coordinates."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%pixel:%@CR:C6A00170147 @%%@AE@%%@EH@%%@NL@% %@3@%A single dot on the screen. It is the smallest item that may be manipulated%@EH@% with the graphics library, and it is the basic unit of the viewport-coordinate system. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%pointer:%@CR:C6A00170148 @%%@AE@%%@EH@%%@NL@% %@3@%A variable containing the address of another variable, function, or%@EH@% constant. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%pointer arithmetic:%@CR:C6A00170149 @%%@CR:C6A00170150 @%%@AE@%%@EH@%%@NL@% %@3@%The use of addition or subtraction to change a pointer's value. Pointer%@EH@% arithmetic is typically used with array pointers, though it is not illegal on other kinds of pointers.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%pointer-member operator:%@CR:C6A00170151 @%%@CR:C6A00170152 @%%@CR:C6A00170153 @%%@AE@%%@EH@%%@NL@% %@3@%The %@AB@%->%@AE@% operator, used with structure pointers to name a structure member.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%pragma:%@CR:C6A00170154 @%%@AE@%%@EH@%%@NL@% %@3@%An instruction to the compiler to perform an action at compile time.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%precedence:%@CR:C6A00170155 @%%@AE@%%@EH@%%@NL@% %@3@%The relative position of an operator in the hierarchy that determines the%@EH@% order in which expressions are evaluated.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%preprocessor:%@CR:C6A00170156 @%%@AE@%%@EH@%%@NL@% %@3@%A text processor that manipulates the contents of a C source file during the%@EH@% first phase of compilation.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%preprocessor directive:%@AE@%%@EH@%%@NL@% %@3@%See "directive."%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%prototype:%@AE@%%@EH@%%@NL@% %@3@%See "function prototype."%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%recursion:%@CR:C6A00170157 @%%@AE@%%@EH@%%@NL@% %@3@%The process by which a function calls itself.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%%@CR:C6A00170158 @%register variable:%@AE@%%@EH@%%@NL@% %@3@%An integer variable that is placed in a machine register, which may cause%@EH@% the program to be smaller and faster.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%remapping:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170159 @%The process of assigning new color values to color indexes. Remapping a%@EH@% color index changes the screen color of any pixels that have been drawn with that color index.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%reserved word:%@AE@%%@EH@%%@NL@% %@3@%See "keyword."%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%return value:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170160 @%The value that a function returns to the calling function.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%run time:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170161 @%The time during which a previously compiled and linked program is executing.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%run-time library:%@AE@%%@EH@%%@NL@% %@3@%A file containing the routines needed to implement certain functions of the%@EH@% Microsoft QuickC language.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%scaling:%@AE@%%@EH@%%@NL@% %@3@%The mapping of real-window coordinates to viewport coordinates.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%%@CR:C6A00170162 @%scope:%@AE@%%@EH@%%@NL@% %@3@%The parts of a program in which an item can be referenced by name. The scope%@EH@% of an item may be limited to the file, function, block, or function prototype in which it appears.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%screen mode:%@AE@%%@EH@%%@NL@% %@3@%See "video mode."%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%single precision:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170163 @%A real (floating-point) value that occupies four bytes of memory. Single-%@EH@% precision values are accurate to seven decimal places. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%sizeof operator:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170164 @%%@CR:C6A00170165 @%%@CR:C6A00170166 @%A C operator that returns the amount of storage, in bytes, associated with%@EH@% an identifier or a type.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%source file:%@AE@%%@EH@%%@NL@% %@3@%A text file containing C language code.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%standard error:%@AE@%%@EH@%%@NL@% %@3@%The device to which a program sends its error messages unless the error%@EH@% output is redirected. In normal DOS operation, standard error is the display. The predefined stream %@AB@%stderr%@AE@% is associated with standard error in the C language. %@NL@%%@NL@% %@NL@% %@2@%%@AB@%%@CR:C6A00170167 @%standard input:%@AE@%%@EH@%%@NL@% %@3@%The device from which a program reads its input unless the input is%@EH@% redirected. In normal DOS operation, standard input is the keyboard. The predefined stream %@AB@%stdin%@AE@% is associated with standard input in the C language.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%standard output:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170168 @%The device to which a program sends its output unless the output is%@EH@% redirected. In normal DOS operation, standard output is the display. The predefined stream %@AB@%stdout%@AE@% is associated with standard output in the C language.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%%@CR:C6A00170169 @%static variable:%@AE@%%@EH@%%@NL@% %@3@%A variable that keeps its value even after the program exits the block in%@EH@% which the variable is declared.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%stream:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170170 @%A sequence of bytes flowing into (input) or out of (output) a program.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%stream functions:%@AE@%%@EH@%%@NL@% %@3@%Run-time library functions that treat data files and data items as "streams"%@EH@% of individual characters.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%string:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170171 @%An array of characters, terminated by a null character (%@AB@%\0%@AE@%).%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%string constant:%@AE@%%@EH@%%@NL@% %@3@%A string of characters and escape sequences enclosed in double quotes ("").%@EH@% Every string constant is an array of elements of type %@AB@%char%@AE@%. See "character constant."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%structure:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170172 @%A set of elements, which may be of different types, grouped under a single%@EH@% name.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%structure member:%@AE@%%@EH@%%@NL@% %@3@%One of the elements of a structure.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%structure pointer:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170173 @%%@CR:C6A00170174 @%A pointer to a structure. Structure pointers identify structure members by%@EH@% specifying the name of the structure, the pointer-member operator (%@AB@%->%@AE@%), and the member name.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%symbolic constant:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170175 @%An identifier defined in a %@AB@%#define%@AE@% preprocessor directive to represent a%@EH@% constant value.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%tag:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170176 @%The name assigned to a structure, union, or enumeration type.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%ternary operator:%@AE@%%@EH@%%@NL@% %@3@%An operator used in ternary (three-part) expressions. C has one ternary%@EH@% operator, the conditional operator (%@AB@%? :%@AE@%).%@NL@%%@NL@% %@NL@% %@2@%%@AB@%text:%@AE@%%@EH@%%@NL@% %@3@%Ordinary, readable characters, including the uppercase and lowercase letters%@EH@% of the alphabet, the numerals 0-9, and punctuation marks.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%text file:%@AE@%%@EH@%%@NL@% %@3@%A file of ASCII characters that you can read with the TYPE command or a word%@EH@% processor.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%text format:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170177 @%A method of disk storage in which all data are converted to ASCII format.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%text mode:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170178 @%%@CR:C6A00170179 @%See "video mode."%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%text window:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170180 @%%@CR:C6A00170181 @%A window defined in row and column coordinates where text output to the%@EH@% screen will be displayed. Text printed beyond the edge of the text window is not visible. The default text window is the whole screen.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%two's complement:%@AE@%%@EH@%%@NL@% %@3@%A kind of base-2 notation used to represent positive and negative numbers in%@EH@% which negative values are formed by complementing all bits and adding 1 to the results.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%type:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170182 @%%@CR:C6A00170183 @%%@CR:C6A00170184 @%%@CR:C6A00170185 @%A description of a set of values. For example, the type %@AB@%char%@AE@% comprises the%@EH@% 256 values in the ASCII character set.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%type cast:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170186 @%An operation in which a value of one type is converted to a value of a%@EH@% different type.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%type checking:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170187 @%An operation in which the compiler verifies that the operands of an operator%@EH@% are valid, or that the actual arguments in a function call are of the same types as the corresponding formal parameters in the function definition and function prototype.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%type declaration:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170188 @%A declaration that defines the name and members of a structure or union%@EH@% type, or the name and enumeration set of an enumeration type.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%typedef declaration:%@AE@%%@EH@%%@NL@% %@3@%A declaration that defines a shorter or more meaningful name for an existing%@EH@% C data type or for a user-defined data type. Names defined in a %@AB@%typedef%@AE@% declaration are often referred to as "typedefs." %@NL@%%@NL@% %@NL@% %@2@%%@AB@%typeface:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170189 @%%@CR:C6A00170190 @%The style of displayed text.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%type name:%@AE@%%@EH@%%@NL@% %@3@%The name of a data type. See "type."%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%type qualifier:%@AE@%%@EH@%%@NL@% %@3@%The keywords %@AB@%short%@AE@%, %@AB@%long%@AE@%, %@AB@%signed%@AE@%, and %@AB@%unsigned%@AE@%, which modify a basic data%@EH@% type.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%type size:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170191 @%%@CR:C6A00170192 @%%@CR:C6A00170193 @%A measure of the screen area occupied by individual characters in a font,%@EH@% typically specified in pixels.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%unary expression:%@AE@%%@EH@%%@NL@% %@3@%An expression consisting of a single operand preceded or followed by a unary%@EH@% operator.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%unary operator:%@AE@%%@EH@%%@NL@% %@3@%An operator that takes a single operand. Unary operators in the C language%@EH@% are the complement operators (%@AB@%- ~ !%@AE@%), indirection operator %@AB@%(*%@AE@%), increment (%@AB@%++%@AE@%) and decrement (%@AB@%- -%@AE@%) operators, address-of operator (%@AB@%&%@AE@%), and %@AB@%sizeof%@AE@% operator. The unary plus (%@AB@%+%@AE@%) operator is legal but has no effect.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%union:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170194 @%%@CR:C6A00170195 @%%@CR:C6A00170196 @%%@CR:C6A00170197 @%A set of values of different types that occupy the same storage space.%@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%vector-mapped font:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170198 @%A font in which each character is defined in terms of lines and arcs. %@NL@%%@NL@%%@EH@% %@NL@% %@2@%%@AB@%VGA (Video Graphics Array):%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170199 @% Many users refer to the video subsystem integrated into the PS/2 Models 50,%@EH@% 60, and 80, as well as the IBM PS/2 Display Adapter, as the "VGA."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%video adapter:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170200 @%A printed-circuit card that generates video output. Well-known IBM PC video%@EH@% adapters include the MDA, CGA, HGC, EGA, MCGA, and VGA Adapters.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%video mode:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170201 @%An integer that specifies the resolution and other characteristics of video%@EH@% output. QuickC supports 17 different video modes, although some of them are available only with certain video adapters.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%viewport:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170202 @%A clipping region in which the origin (0, 0) may be redefined. The initial%@EH@% origin of a viewport is the upper left corner.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%viewport coordinates:%@AE@%%@EH@%%@NL@% %@3@%The integer coordinate system defined by the programmer for a specific%@EH@% viewport. By default, the viewport-coordinate system has the origin (0, 0) at the upper left corner of the viewport, but this may be changed by a call to %@AB@%_setvieworg%@AE@%.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%visibility:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170203 @%The parts of the program in which a particular variable or function can be%@EH@% referenced by name. An item has global visibility if it is visible in all source files constituting the program and local visibility if its use is restricted.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%white-space character:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170204 @%A space, tab, line-feed, carriage-return, form-feed, vertical-tab, or%@EH@% newline character.%@NL@%%@NL@% %@NL@% %@2@%%@AB@%window:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170205 @%%@CR:C6A00170206 @%%@CR:C6A00170207 @%An imaginary rectangle on the screen where output takes place. See "text%@EH@% window" and "window coordinates."%@NL@%%@NL@% %@NL@% %@2@%%@AB@%window coordinates:%@AE@%%@EH@%%@NL@% %@3@%%@CR:C6A00170208 @%The coordinate system defined by the programmer.%@NL@%%@NL@%%@EH@% %@NL@% %@NL@% %@NL@% %@NL@%