C Pocket Reference: C Syntax and Fundamentals 0596004362, 9780596004361

C is one of the oldest programming languages and still one of the most widely used. Whether you're an experienced C

975 138 683KB

English Pages 120 [142] Year 2002

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

C Pocket Reference: C Syntax and Fundamentals
 0596004362, 9780596004361

Table of contents :
Contents
C Pocket Reference
Introduction
Font Conventions
Fundamentals
C Program Structure
Character Sets
Identifiers
Categories and Scope of Identifiers
Basic Types
Integer Types
Real and Complex Floating Types
Internal representation of a real floating-point number
Complex floating types
The Type void
Constants
Integer Constants
Floating Constants
Character Constants and String Literals
Expressions and Operators
Arithmetic Operators
Assignment Operators
Relational Operators
Logical Operators
Bitwise Operators
Memory Accessing Operators
Other Operators
Alternative notation for operators
Type Conversions
Integer Promotion
Usual Arithmetic Conversions
Type Conversions in Assignments and Pointers
Statements
Block and Expression Statements
Jumps
if ... else
switch
Loops
while
do ... while
for
Unconditional Jumps
goto
continue
break
return
Declarations
General Syntax and Examples
Complex Declarations
Variables
Storage Classes
Initialization
Derived Types
Enumeration Types
Structures, Unions, and Bit-Fields
Unions
Bit-fields
Arrays
Pointers
Pointer arithmetic
Function pointers
Type Qualifiers and Type Definitions
restrict
typedef
Functions
Function Prototypes
Function Definitions
Function Calls
Functions with Variable Numbers of Arguments
Linkage of Identifiers
Preprocessing Directives
#define
#undef
#include
#if, #elif, #else, #endif
The defined operator
#ifdef and #ifndef
#line
#pragma
Standard Library
Standard Header Files
Input and Output
Error Handling for Input/Output Functions
General File Access Functions
File Input/Output Functions
Reading and writing characters and strings
Block read and write functions
Formatted output
Formatted input
Numerical Limits and Number Classification
Value Ranges of Integer Types
Range and Precision of Real Floating Types
Classification of Floating-Point Numbers
Mathematical Functions
Mathematical Functions for Integer Types
Mathematical Functions for Real Floating Types
Optimizing Runtime Efficiency
Mathematical Functions for Complex Floating Types
Type-Generic Macros
Error Handling for Mathematical Functions
The Floating-Point Environment
Character Classification and Case Mapping
String Handling
Conversion Between Strings and Numbers
Multibyte Character Conversion
Searching and Sorting
Memory Block Management
Dynamic Memory Management
Time and Date
Process Control
Communication with the Operating System
Signals
Non-Local Jumps
Error Handling for System Functions
Internationalization
Index

Citation preview

C Pocket Reference

Peter Prinz and Ulla Kirch-Prinz Translated by Tony Crawford

Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo

C Pocket Reference by Peter Prinz and Ulla Kirch-Prinz Copyright © 2003 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. This book was originally published as C kurz & gut, Copyright © 2002 by O’Reilly Verlag GmbH & Co. KG. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly Media, Inc. books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or [email protected].

Editor: Production Editor: Cover Designer: Interior Designer:

Jonathan Gennick Jane Ellin Pam Spremulli David Futato

Printing History: November 2002:

First Edition.

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. The Pocket Reference series designations, C Pocket Reference, the image of a cow, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

0-596-00436-2 [C]

[6/06]

Contents

Introduction

1

Fundamentals C Program Structure Character Sets Identifiers Categories and Scope of Identifiers

2 3 4 6 7

Basic Types Integer Types Real and Complex Floating Types The Type void

9 9 11 13

Constants Integer Constants Floating Constants Character Constants and String Literals

14 14 16 16

Expressions and Operators Arithmetic Operators Assignment Operators Relational Operators Logical Operators Bitwise Operators Memory Accessing Operators Other Operators

18 20 21 22 23 24 25 27 v

Type Conversions Integer Promotion Usual Arithmetic Conversions Type Conversions in Assignments and Pointers

29 29 30 30

Statements Block and Expression Statements Jumps Loops Unconditional Jumps

31 32 33 35 37

Declarations General Syntax and Examples Complex Declarations

39 39 40

Variables Storage Classes Initialization

41 41 42

Derived Types Enumeration Types Structures, Unions, and Bit-Fields Arrays Pointers Type Qualifiers and Type Definitions

43 43 45 49 52 55

Functions Function Prototypes Function Definitions Function Calls Functions with Variable Numbers of Arguments

57 58 59 61 62

Linkage of Identifiers

64

Preprocessing Directives

65

vi |

Contents

Standard Library

73

Standard Header Files

73

Input and Output Error Handling for Input/Output Functions General File Access Functions File Input/Output Functions

74 76 76 79

Numerical Limits and Number Classification Value Ranges of Integer Types Range and Precision of Real Floating Types Classification of Floating-Point Numbers

87 87 88 90

Mathematical Functions Mathematical Functions for Integer Types Mathematical Functions for Real Floating Types Optimizing Runtime Efficiency Mathematical Functions for Complex Floating Types Type-Generic Macros Error Handling for Mathematical Functions The Floating-Point Environment

91 91 92 94 95 96 97 98

Character Classification and Case Mapping

101

String Handling Conversion Between Strings and Numbers Multibyte Character Conversion

103 105 107

Searching and Sorting

108

Memory Block Management

109

Dynamic Memory Management

110

Time and Date

111

Contents |

vii

Process Control Communication with the Operating System Signals Non-Local Jumps Error Handling for System Functions

113 113 114 115 116

Internationalization

116

Index

121

viii |

Contents

C Pocket Reference

Introduction The programming language C was developed in the 1970s by Dennis Ritchie at Bell Labs (Murray Hill, New Jersey) in the process of implementing the Unix operating system on a DEC PDP-11 computer. C has its origins in the typeless programming language BCPL (Basic Combined Programming Language, developed by M. Richards) and in B (developed by K. Thompson). In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description of C, now known as the K&R standard. C is a highly portable language oriented towards the architecture of today’s computers. The actual language itself is relatively small and contains few hardware-specific elements. It includes no input/output statements or memory management techniques, for example. Functions to address these tasks are available in the extensive C standard library. C’s design has significant advantages: • Source code is highly portable • Machine code is efficient • C compilers are available for all current systems The first part of this pocket reference describes the C language, and the second part is devoted to the C standard library. The description of C is based on the ANSI X3.159 standard. This standard corresponds to the international

1

standard ISO/IEC 9899, which was adopted by the International Organization for Standardization in 1990, then amended in 1995 and 1999. The ISO/IEC 9899 standard can be ordered from the ANSI web site; see http://webstore.ansi. org/. The 1995 standard is supported by all common C compilers today. The new extensions defined in the 1999 release (called “ANSI C99” for short) are not yet implemented in many C compilers, and are therefore specially labeled in this book. New types, functions, and macros introduced in ANSI C99 are indicated by an asterisk in parentheses (*).

Font Conventions The following typographic conventions are used in this book: Italic Used to introduce new terms, and to indicate filenames. Constant width

Used for C program code as well as for functions and directives. Constant width italic

Indicates replaceable items within code syntax. Constant width bold

Used to highlight code passages for special attention.

Fundamentals A C program consists of individual building blocks called functions, which can invoke one another. Each function performs a certain task. Ready-made functions are available in the standard library; other functions are written by the programmer as necessary. A special function name is main(): this designates the first function invoked when a program starts. All other functions are subroutines.

2 |

C Pocket Reference

C Program Structure Figure 1 illustrates the structure of a C program. The program shown consists of the functions main() and showPage(), and prints the beginning of a text file to be specified on the command line when the program is started. /* Head.c: This program outputs the beginning of a * text file to the standard output. * Usage : Head #include #define LINES

Preprocessor directives

22

void showPage( FILE * );

* * Comments */

// prototype

Funtion main()

int main( int argc, char **argv ) { FILE *fp; int exit_code = 0; if ( argc != 2 ) { fprintf( stderr, "Usage: Head \n" ); exit_code = 1; } else if ( ( fp = fopen( argv[1], "r" )) == NULL ) { fprintf( stderr, "Error opening file!\n" ); exit_code = 2; } else { showPage( fp ); fclose( fp ); } return exit_code; } void showPage( FILE *fp ) // Output a screen page Other functions { int count = 0; char line[81]; while ( count < LINES && fgets( line, 81, fp ) != NULL ) { fputs( line, stdout ); ++count; } }

Figure 1. A C program

The statements that make up the functions, together with the necessary declarations and preprocessing directives, form the source code of a C program. For small programs, the source code is written in a single source file. Larger C programs

Fundamentals |

3

consist of several source files, which can be edited and compiled separately. Each such source file contains functions that belong to a logical unit, such as functions for output to a terminal, for example. Information that is needed in several source files, such as declarations, is placed in header files. These can then be included in each source file via the #include directive. Source files have names ending in .c; header files have names ending in .h. A source file together with the header files included in it is called a translation unit. There is no prescribed order in which functions must be defined. The function showPage() in Figure 1 could also be placed before the function main(). A function cannot be defined within another function, however. The compiler processes each source file in sequence and decomposes its contents into tokens, such as function names and operators. Tokens can be separated by one or more whitespace characters, such as space, tab, or newline characters. Thus only the order of tokens in the file matters. The layout of the source code—line breaks and indentation, for example—is unimportant. The preprocessing directives are an exception to this rule, however. These directives are commands to be executed by the preprocessor before the actual program is compiled, and each one occupies a line to itself, beginning with a hash mark (#). Comments are any strings enclosed either between /* and */, or between // and the end of the line. In the preliminary phases of translation, before any object code is generated, each comment is replaced by one space. Then the preprocessing directives are executed.

Character Sets ANSI C defines two character sets. The first is the source character set, which is the set of characters that may be used

4 |

C Pocket Reference

in a source file. The second is the execution character set, which consists of all the characters that are interpreted during the execution of the program, such as the characters in a string constant. Each of these character sets contains a basic character set, which includes the following: • The 52 upper- and lower-case letters of the Latin alphabet: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z

• The ten decimal digits (where the value of each character after 0 is one greater than the previous digit): 0

1

2

3

4

5

6

7

8

9

• The following 29 graphic characters: !