Tải bản đầy đủ (.pdf) (620 trang)

Prinz, crawford - c in a nutshell 2006

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (7.09 MB, 620 trang )

C
IN A NUTSHELL
Other resources from O’Reilly
Related titles
C Pocket Reference
Practical C Programming
Secure Programming
Cookbook
for C and C++
Programming Embedded
Systems with C
and C++
Programming with GNU
Software
Objective-C Pocket
Reference
Prefactoring
Practical Development
Environments
oreilly.com
oreilly.com is more than a complete catalog of O’Reilly
books. You’ll also find links to news, events, articles, web-
logs, sample chapters, and code examples.
oreillynet.com is the essential portal for developers inter-
ested in open and emerging technologies, including new
platforms, programming languages, and operating systems.
Conferences
O’Reilly brings diverse innovators together to nurture the
ideas that spark revolutionary industries. We specialize in


documenting the latest tools and systems, translating the
innovator’s knowledge into useful skills for those in the
trenches. Visit conferences.oreilly.com for our upcoming
events.
Safari Bookshelf (safari.oreilly.com) is the premier online
reference library for programmers and IT professionals.
Conduct searches across more than 1,000 books. Sub-
scribers can zero in on answers to time-critical questions
in a matter of seconds. Read the books on your Book-
shelf from cover to cover or simply flip to the page you
need. Try it today for free.
C
IN A NUTSHELL
Peter Prinz and Tony Crawford
Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo
C in a Nutshell
by Peter Prinz and Tony Crawford
Copyright © 2006 O’Reilly Media, Inc. All rights reserved.
Printed in the United States of America.
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly 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
Editor:
Jonathan Gennick
Production Editor:
A. J. Fox
Cover Designer:
Karen Montgomery
Interior Designer:

David Futato
Printing History:
December 2005: First Edition.
Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered
trademarks of O’Reilly Media, Inc. The In a Nutshell series designations, C in a Nutshell, 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.
ISBN: 978-0-596-00697-6
[LSI] [2012-05-11]
v
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
Chapter 1
Table of Contents
Preface
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
xi
Part I. Language
1. Language Basics
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3
Characteristics of C 3
The Structure of C Programs 4
Source Files 6

Comments 7
Character Sets 8
Identifiers 13
How the C Compiler Works 16
2. Types
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
20
Typology 20
Integer Types 21
Floating-Point Types 26
Complex Floating-Point Types (C99) 28
Enumerated Types 29
The Type void 30
3. Literals
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
32
Integer Constants 32
Floating-Point Constants 33
vi
|
Table of Contents
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
Character Constants 34
String Literals 37
4. Type Conversions
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
40
Conversion of Arithmetic Types 41
Conversion of Nonarithmetic Types 48

5. Expressions and Operators
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
55
How Expressions Are Evaluated 56
Operators in Detail 59
Constant Expressions 81
6. Statements
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
83
Expression Statements 83
Block Statements 84
Loops 85
Selection Statements 89
Unconditional Jumps 92
7. Functions
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
96
Function Definitions 96
Function Declarations 103
How Functions Are Executed 104
Pointers as Arguments and Return Values 104
Inline Functions 106
Recursive Functions 107
Variable Numbers of Arguments 108
8. Arrays
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
111
Defining Arrays 111
Accessing Array Elements 113
Initializing Arrays 114

Strings 116
Multidimensional Arrays 117
Arrays as Arguments of Functions 120
9. Pointers
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
122
Declaring Pointers 122
Operations with Pointers 125
Pointers and Type Qualifiers 129
Pointers to Arrays and Arrays of Pointers 132
Pointers to Functions 136
Table of Contents | vii
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
10. Structures, Unions, and Bit-Fields
. . . . . . . . . . . . . . . . . . . . . . . . . . .
139
Structures 139
Unions 149
Bit-Fields 151
11. Declarations
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
153
General Syntax 153
Type Names 160
typedef Declarations 161
Linkage of Identifiers 163
Storage Duration of Objects 164
Initialization 165
12. Dynamic Memory Management

. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
167
Allocating Memory Dynamically 168
Characteristics of Allocated Memory 169
Resizing and Releasing Memory 170
An All-Purpose Binary Tree 171
Characteristics 172
Implementation 172
13. Input and Output
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
182
Streams 182
Files 183
Opening and Closing Files 186
Reading and Writing 188
Random File Access 205
14. Preprocessing Directives
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
209
Inserting the Contents of Header Files 210
Defining and Using Macros 211
Conditional Compiling 218
Defining Line Numbers 220
Generating Error Messages 221
The #pragma Directive 221
The _Pragma Operator 222
Predefined Macros 223
viii
|
Table of Contents

This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
Part II. Standard Library
15. The Standard Headers
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
227
Using the Standard Headers 227
Contents of the Standard Headers 230
16. Functions at a Glance
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
252
Input and Output 252
Mathematical Functions 253
Character Classification and Conversion 260
String Processing 262
Multibyte Characters 263
Converting Between Numbers and Strings 264
Searching and Sorting 264
Memory Block Handling 265
Dynamic Memory Management 265
Date and Time 266
Process Control 267
Internationalization 268
Nonlocal Jumps 269
Debugging 269
Error Messages 270
17. Standard Library Functions
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
271
Part III. Basic Tools

18. Compiling with GCC
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
491
The GNU Compiler Collection 491
Obtaining and Installing GCC 492
Compiling C Programs with GCC 493
C Dialects 501
Compiler Warnings 502
Optimization 503
Debugging 507
Profiling 507
Option and Environment Variable Summary 508
Table of Contents | ix
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
19. Using make to Build C Programs
. . . . . . . . . . . . . . . . . . . . . . . . . . . . .
512
Targets, Prerequisites, and Commands 512
The Makefile 513
Rules 513
Comments 520
Variables 520
Phony Targets 527
Other Target Attributes 528
Macros 529
Functions 530
Directives 534
Running make 537
20. Debugging C Programs with GDB

. . . . . . . . . . . . . . . . . . . . . . . . . . . .
545
Installing GDB 546
A Sample Debugging Session 546
Starting GDB 550
Using GDB Commands 554
Index
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
577
xi
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
Chapter 2
Preface
This book is a complete reference to the C programming language and the C
runtime library. As a Nutshell book, its purpose is to serve as a convenient, reli-
able companion for C programmers in their day-to-day work. It describes all the
elements of the language and illustrates their use with numerous examples.
The present description of the C language is based on the 1999 international C
standard, ISO/IEC 9899:1999, including the Technical Corrigenda, TC1 of 2001
and TC2 of 2004. This standard, widely known as C99, is an extension of the ISO/
IEC 9899:1990 standard and the 1995 Normative Addendum 1 (ISO/IEC 9899/
AMD1:1995). The 1990 ISO/IEC standard corresponds to the ANSI standard
X3.159, which was ratified in late 1989 and is commonly called ANSI C or C89.
The new features of the 1999 C standard are not yet fully supported by all
compilers and standard library implementations. In this book we have therefore
labeled 1999 extensions, such as new standard library functions that were not
mentioned in earlier standards, with the abbreviation C99.
This book is not an introduction to programming in C. Although it covers the

fundamentals of the language, it is not organized or written as a tutorial. If you are
new to C, we assume that you have read at least one of the many introductory
books, or that you are familiar with a related language, such as Java or C++.
How This Book Is Organized
This book is divided into three parts. The first part describes the C language in the
strict sense of the term; the second part describes the standard library; and the
third part describes the process of compiling and testing programs with the
popular tools in the GNU software collection.
xii
|
Preface
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
Part I
Part I, which deals with the C language, includes Chapters 1 through 14. After
Chapter 1, which describes the general concepts and elements of the language,
each chapter is devoted to a specific topic, such as types, statements, or pointers.
Although the topics are ordered so that the fundamental concepts for each new
topic have been presented in an earlier chapter—types, for example, are described
before expressions and operators, which come before statements, and so on—you
may sometimes need to follow references to later chapters to fill in related details.
For example, some discussion of pointers and arrays is necessary in Chapter 5
(which covers expressions and operators), even though pointers and arrays are not
described in full detail until Chapters 8 and 9.
Chapter 1, Language Basics
Describes the characteristics of the language and how C programs are struc-
tured and compiled. This chapter introduces basic concepts such as the
translation unit, character sets, and identifiers.
Chapter 2, Types
Provides an overview of types in C and describes the basic types, the type

void, and enumerated types.
Chapter 3, Literals
Describes numeric constants, character constants, and string literals,
including escape sequences.
Chapter 4, Type Conversions
Describes implicit and explicit type conversions, including integer promotion
and the usual arithmetic conversions.
Chapter 5, Expressions and Operators
Describes the evaluation of expressions, all the operators, and their compat-
ible operands.
Chapter 6, Statements
Describes C statements such as blocks, loops, and jumps.
Chapter 7, Functions
Describes function definitions and function calls, including recursive and
inline functions.
Chapter 8, Arrays
Describes fixed-length and variable-length arrays, including strings, array
initialization, and multidimensional arrays.
Chapter 9, Pointers
Describes the definition and use of pointers to objects and functions.
Chapter 10, Structures, Unions, and Bit-Fields
Describes the organization of data in these user-defined derived types.
Preface | xiii
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
Chapter 11, Declarations
Describes the general syntax of a declaration, identifier linkage, and the
storage duration of objects.
Chapter 12, Dynamic Memory Management
Describes the standard library’s dynamic memory management functions,

illustrating their use in a sample implementation of a generalized binary tree.
Chapter 13, Input and Output
Describes the C concept of input and output, with an overview of the use of
the standard I/O library.
Chapter 14, Preprocessing Directives
Describes the definition and use of macros, conditional compiling, and all the
other preprocessor directives and operators.
Part II
Part II, consisting of Chapters 15, 16, and 17, is devoted to the C standard library.
It provides an overview of standard headers and also contains a detailed function
reference.
Chapter 15, The Standard Headers
Describes contents of the headers and their use. The headers contain all of
the standard library’s macros and type definitions.
Chapter 16, Functions at a Glance
Provides an overview of the standard library functions, organized by areas of
application, such as “Mathematical Functions,” “Time and Date Functions,”
and so on.
Chapter 17, Standard Library Functions
Describes each standard library function in detail, in alphabetical order, and
contains examples to illustrate the use of each function.
Part III
The third part of this book provides the necessary knowledge of the C
programmer’s basic tools: the compiler, the make utility, and the debugger. The
tools described here are those in the GNU software collection.
Chapter 18, Compiling with GCC
Describes the principal capabilities that the widely used compiler offers for C
programmers.
Chapter 19, Using make to Build C Programs
Describes how to use the make program to automate the compiling process

for large programs.
Chapter 20, Debugging C Programs with GDB
Describes how to run a program under the control of the GNU debugger and
how to analyze programs’ runtime behavior to find logical errors.
xiv
|
Preface
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
Further Reading
In addition to works mentioned at appropriate points in the text, there are a
number of resources for readers who want more technical detail than even this
book can provide. The international working group on C standardization has an
official home page at with links to the
latest version of the C99 standard and current projects of the working group.
For readers who are interested in not only the what and how of C, but also the
why, the WG14 site also has a link to the “C99 Rationale”: this is a nonnormative
but current document that describes some of the motivations and constraints
involved in the standardization process. The C89 Rationale is online at http://
www.lysator.liu.se/c/rat/title.html. Furthermore, for those who may wonder how C
“got to be that way” in the first place, the originator of C, Dennis Ritchie, has an
article titled “The Development of the C Language” as well as other historical
documents on his Bell Labs web site, />Readers who want details on floating-point math beyond the scope of C may wish
to start with David Goldberg’s thorough introduction, “What Every Computer
Scientist Should Know About Floating-Point Arithmetic,” currently available
online at />Conventions Used in This Book
The following typographical conventions are used in this book:
Italic
Highlights new terms; indicates filenames, file extensions, URLs, directories,
and Unix utilities.

Constant width
Indicates all elements of C source code: keywords, operators, variables, func-
tions, macros, types, parameters, and literals. Also used for console
commands and options, and the output from such commands.
Constant width bold
Highlights the function or statement under discussion in code examples. In
compiler, make, and debugger sessions, this font indicates command input to
be typed literally by the user.
Constant width italic
Indicates parameters in function prototypes, or placeholders to be replaced
with your own values.
Plain text
Indicates keys such as Return, Tab, and Ctrl.
Preface | xv
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
This icon signifies a tip, suggestion, or general note.
This icon signifies a warning or caution.
Using Code Examples
This book is here to help you get your job done. In general, you may use the code
in this book in your programs and documentation. You do not need to contact us
for permission unless you’re reproducing a significant portion of the code. For
example, writing a program that uses several chunks of code from this book does
not require permission. Selling or distributing a CD-ROM of examples from
O’Reilly books does require permission. Answering a question by citing this book
and quoting example code does not require permission. Incorporating a signifi-
cant amount of example code from this book into your product’s documentation
does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the
title, author, publisher, and ISBN. For example: “C in a Nutshell by Peter Prinz

and Tony Crawford. Copyright 2006 O’Reilly Media, Inc., 0-596-00697-7.”
If you feel that your use of code examples falls outside fair use or the permission
given here, feel free to contact us at
Safari® Enabled
When you see a Safari® Enabled icon on the cover of your favorite
technology book, that means the book is available online through
the O’Reilly Network Safari Bookshelf.
Safari offers a solution that’s better than e-books. It’s a virtual
library that lets you easily search thousands of top tech books, cut and paste code
samples, download chapters, and find quick answers when you need the most
accurate, current information. Try it for free at .
Your Questions and Comments
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
(800) 998-9938 (in the United States or Canada)
(707) 829-0515 (international or local)
(707) 829-0104 (fax)
xvi
|
Preface
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
We have a web page for this book, where we list errata, examples, and any addi-
tional information. You can access this page at:
/>To comment or ask technical questions about this book, send email to:

For more information about our books, conferences, Resource Centers, and the
O’Reilly Network, see our web site at:


Acknowledgments
Both of us want to thank Jonathan Gennick, our editor, for originally bringing
us together and starting us off on this book, and for all his guidance along the
way. We also thank our technical reviewers, Matt Crawford, David Kitabjian,
and Chris LaPre, for their valuable criticism of our manuscript, and we’re
grateful to our production editor, Abby Fox, for all her attention to making our
book look good.
Peter
I would like to thank Tony first of all for the excellent collaboration. My heartfelt
thanks also go to all my friends for the understanding they showed again and
again when I had so little time for them. Last but not least, I dedicate this book to
my daughters, Vivian and Jeanette—both of them now students of computer
science—who strengthened my ambition to carry out this book project.
Tony
I have enjoyed working on this book as a very rewarding exercise in teamwork. I
thank Peter for letting me take all the space I could fill in this project. The oppor-
tunity to work with my brother Matt in the review phase was particularly
gratifying.
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
I
Language
3
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
Chapter 1Language Basics
1
Language Basics

This chapter describes the basic characteristics and elements of the C program-
ming language.
Characteristics of C
C is a general-purpose, procedural programming language. Dennis Ritchie first
devised C in the 1970s at AT&T Bell Laboratories in Murray Hill, New Jersey, for
the purpose of implementing the Unix operating system and utilities with the
greatest possible degree of independence from specific hardware platforms. The
key characteristics of the C language are the qualities that made it suitable for that
purpose:
• Source code portability
• The ability to operate “close to the machine”
• Efficiency
As a result, the developers of Unix were able to write most of the operating system
in C, leaving only a minimum of system-specific hardware manipulation to be
coded in assembler.
C’s ancestors are the typeless programming languages BCPL (the Basic Combined
Programming Language), developed by Martin Richards; and B, a descendant of
BCPL, developed by Ken Thompson. A new feature of C was its variety of data
types: characters, numeric types, arrays, structures, and so on. Brian Kernighan
and Dennis Ritchie published an official description of the C programming
language in 1978. As the first de facto standard, their description is commonly
referred to simply as “K&R.”
*
C owes its high degree of portability to a compact
* The second edition, revised to reflect the first ANSI C standard, is available as The C Programming
Language, 2nd ed., by Brian W. Kernighan and Dennis M. Ritchie (Englewood Cliffs, N.J.: Prentice
Hall, 1988).
4
|
Chapter 1: Language Basics

This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
core language that contains few hardware-dependent elements. For example, the
C language proper has no file access or dynamic memory management state-
ments. In fact, there aren’t even any statements for console input and output.
Instead, the extensive standard C library provides the functions for all of these
purposes.
This language design makes the C compiler relatively compact and easy to port to
new systems. Furthermore, once the compiler is running on a new system, you
can compile most of the functions in the standard library with no further modifi-
cation, because they are in turn written in portable C. As a result, C compilers are
available for practically every computer system.
Because C was expressly designed for system programming, it is hardly surprising
that one of its major uses today is in programming embedded systems. At the
same time, however, many developers use C as a portable, structured high-level
language to write programs such as powerful word processor, database, and
graphics applications.
The Structure of C Programs
The procedural building blocks of a C program are functions, which can invoke
one another. Every function in a well-designed program serves a specific purpose.
The functions contain statements for the program to execute sequentially, and
statements can also be grouped to form block statements,orblocks. As the
programmer, you can use the ready-made functions in the standard library, or
write your own whenever no standard function fulfills your intended purpose. In
addition to the standard C library, there are many specialized libraries available,
such as libraries of graphics functions. However, by using such nonstandard
libraries, you limit the portability of your program to those systems to which the
libraries themselves have been ported.
Every C program must define at least one function of its own, with the special
name

main( ): this is the first function invoked when the program starts. The
main( ) function is the program’s top level of control, and can call other functions
as subroutines.
Example 1-1 shows the structure of a simple, complete C program. We will discuss
the details of declarations, function calls, output streams and more elsewhere in
this book. For now, we are simply concerned with the general structure of the C
source code. The program in Example 1-1 defines two functions,
main( ) and
circularArea( ). The main( ) function calls circularArea() to obtain the area of a
circle with a given radius, and then calls the standard library function
printf( ) to
output the results in formatted strings on the console.
Example 1-1. A simple C program
// circle.c: Calculate and print the areas of circles
#include <stdio.h> // Preprocessor directive
double circularArea( double r ); // Function declaration (prototype form)
The Structure of C Programs | 5
Language
Basics
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
Output:
Areas of Circles
Radius Area

1.0 3.14
5.0 78.54
Note that the compiler requires a prior declaration of each function called. The
prototype of
circularArea( ) in the third line of Example 1-1 provides the infor-

mation needed to compile a statement that calls this function. The prototypes of
standard library functions are found in standard header files. Because the header
file stdio.h contains the prototype of the
printf( ) function, the preprocessor direc-
tive
#include <stdio.h> declares the function indirectly by directing the compiler’s
preprocessor to insert the contents of that file. (See also the section “How the C
Compiler Works,” at the end of this chapter.)
You may arrange the functions defined in a program in any order. In Example 1-1,
we could just as well have placed the function
circularArea( ) before the function
main( ). If we had, then the prototype declaration of circularArea( ) would be
superfluous, because the definition of the function is also a declaration.
Function definitions cannot be nested inside one another: you can define a local
variable within a function block, but not a local function.
int main( ) // Definition of main( ) begins
{
double radius = 1.0, area = 0.0;
printf( " Areas of Circles\n\n" );
printf( " Radius Area\n"
" \n" );
area = circularArea( radius );
printf( "%10.1f %10.2f\n", radius, area );
radius = 5.0;
area = circularArea( radius );
printf( "%10.1f %10.2f\n", radius, area );
return 0;
}
// The function circularArea( ) calculates the area of a circle
// Parameter: The radius of the circle

// Return value: The area of the circle
double circularArea( double r ) // Definition of circularArea( ) begins
{
const double pi = 3.1415926536; // Pi is a constant
return pi * r * r;
}
Example 1-1. A simple C program (continued)
6
|
Chapter 1: Language Basics
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
Source Files
The function definitions, global declarations and preprocessing directives make
up the source code of a C program. For small programs, the source code is written
in a single source file. Larger C programs consist of several source files. Because
the function definitions generally depend on preprocessor directives and global
declarations, source files usually have the following internal structure:
1. Preprocessor directives
2. Global declarations
3. Function definitions
C supports modular programming by allowing you to organize a program in as
many source and header files as desired, and to edit and compile them separately.
Each source file generally contains functions that are logically related, such as the
program’s user interface functions. It is customary to label C source files with the
filename suffix .c.
Examples 1-2 and 1-3 show the same program as Example 1-1, but divided into
two source files.
When a program consists of several source files, you need to declare the same
functions and global variables, and define the same macros and constants, in

many of the files. These declarations and definitions thus form a sort of file header
that is more or less constant throughout a program. For the sake of simplicity and
consistency, you can write this information just once in a separate header file, and
then reference the header file using an
#include directive in each source code file.
Header files are customarily identified by the filename suffix .h. A header file
explicitly included in a C source file may in turn include other files.
Example 1-2. The first source file, containing the main( ) function
// circle.c: Prints the areas of circles.
// Uses circulararea.c for the math
#include <stdio.h>
double circularArea( double r );
int main( )
{
/* As in Example 1-1 */
}
Example 1-3. The second source file, containing the circularArea( ) function
// circulararea.c: Calculates the areas of circles.
// Called by main( ) in circle.c
double circularArea( double r )
{
/* As in Example 1-1 */
}
Comments | 7
Language
Basics
This is the Title of the Book, eMatter Edition
Copyright © 2012 O’Reilly & Associates, Inc. All rights reserved.
Each C source file, together with all the header files included in it, makes up a
translation unit. The compiler processes the contents of the translation unit

sequentially, parsing the source code into tokens, its smallest semantic units, such
as variable names and operators. See the section “Tokens,” at the end of this
chapter for more detail.
Any number of whitespace characters can occur between two successive tokens,
allowing you a great deal of freedom in formatting the source code. There are no
rules for line breaks or indenting, and you may use spaces, tabs, and blank lines
liberally to format “human-readable” source code. The preprocessor directives are
slightly less flexible: a preprocessor directive must always appear on a line by
itself, and no characters except spaces or tabs may precede the hash mark (
#) that
begins the line.
There are many different conventions and “house styles” for source code format-
ting. Most of them include the following common rules:
• Start a new line for each new declaration and statement.
• Use indentation to reflect the nested structure of block statements.
Comments
You should use comments generously in the source code to document your C
programs. There are two ways to insert a comment in C: block comments begin
with
/* and end with */, and line comments begin with // and end with the next
new line character.
You can use the
/* and */ delimiters to begin and end comments within a line,
and to enclose comments of several lines. For example, in the following function
prototype, the ellipsis (
) signifies that the open( ) function has a third, optional
parameter. The comment explains the usage of the optional parameter:
int open( const char *name, int mode, /* int permissions */ );
You can use // to insert comments that fill an entire line, or to write source code
in a two-column format, with program code on the left and comments on the

right:
const double pi = 3.1415926536; // Pi is constant
These line comments were officially added to the C language by the C99 stan-
dard, but most compilers already supported them even before C99. They are
sometimes called “C++-style” comments, although they originated in C’s fore-
runner, BCPL.
Inside the quotation marks that delimit a character constant or a string literal, the
characters
/* and // do not start a comment. For example, the following state-
ment contains no comments:
printf( "Comments in C begin with /* or //.\n" );
The only thing that the preprocessor looks for in examining the characters in a
comment is the end of the comment; thus it is not possible to nest block

×