100% found this document useful (2 votes)
5 views

C in a Nutshell 2 (Early Release) Edition Peter Prinz pdf download

The document is a detailed overview of the book 'C in a Nutshell, Second Edition' by Peter Prinz and Tony Crawford, published by O'Reilly Media. It includes a comprehensive table of contents covering various aspects of the C programming language, such as language basics, types, expressions, functions, and multithreading. Additionally, it provides links to other related programming books and resources for digital downloads.

Uploaded by

sessoyousewi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
5 views

C in a Nutshell 2 (Early Release) Edition Peter Prinz pdf download

The document is a detailed overview of the book 'C in a Nutshell, Second Edition' by Peter Prinz and Tony Crawford, published by O'Reilly Media. It includes a comprehensive table of contents covering various aspects of the C programming language, such as language basics, types, expressions, functions, and multithreading. Additionally, it provides links to other related programming books and resources for digital downloads.

Uploaded by

sessoyousewi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

C in a Nutshell 2 (Early Release) Edition Peter

Prinz download

https://ebookgate.com/product/c-in-a-nutshell-2-early-release-
edition-peter-prinz/

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

C Pocket Reference 1st Edition Peter Prinz

https://ebookgate.com/product/c-pocket-reference-1st-edition-
peter-prinz/

Linux Kernel in a Nutshell In a Nutshell O Reilly 1st


Edition Greg Kroah-Hartman

https://ebookgate.com/product/linux-kernel-in-a-nutshell-in-a-
nutshell-o-reilly-1st-edition-greg-kroah-hartman/

SQL in a Nutshell A Desktop Quick Reference Guide In a


Nutshell O Reilly 3rd Edition Kevin Kline

https://ebookgate.com/product/sql-in-a-nutshell-a-desktop-quick-
reference-guide-in-a-nutshell-o-reilly-3rd-edition-kevin-kline/

MySQL in a Nutshell 1st Edition Dyer

https://ebookgate.com/product/mysql-in-a-nutshell-1st-edition-
dyer/
Petlyakov Pe 2 First Edition Peter C Smith

https://ebookgate.com/product/petlyakov-pe-2-first-edition-peter-
c-smith/

Web Design in a Nutshell 2nd Edition Jennifer Niederst

https://ebookgate.com/product/web-design-in-a-nutshell-2nd-
edition-jennifer-niederst/

HBase The Definitive Guide 2 (Early Release) Edition


Lars George

https://ebookgate.com/product/hbase-the-definitive-guide-2-early-
release-edition-lars-george/

PHP in a Nutshell A Desktop Quick Reference 1st Edition


Paul Hudson

https://ebookgate.com/product/php-in-a-nutshell-a-desktop-quick-
reference-1st-edition-paul-hudson/

Administrative Law and Process in a nutshell 6th


Edition Ronald Levin

https://ebookgate.com/product/administrative-law-and-process-in-
a-nutshell-6th-edition-ronald-levin/
SECOND EDITION

C in a Nutshell

Peter Prinz and Tony Crawford


C in a Nutshell, Second Edition
by Peter Prinz and Tony Crawford
Copyright © 2010 Peter Prinz, Tony Crawford. 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 (http://safaribookson
line.com). For more information, contact our corporate/institutional sales depart‐
ment: 800-998-9938 or <[email protected]>.
Editors: Andy Oram and Rachel Roume‐ Copyeditor: FIX ME!
liotis Proofreader: FIX ME!
Production Editor: FIX ME! Indexer: FIX ME!
Cover Designer: Karen Montgomery
Interior Designer: David Futato
Illustrator: Rebecca Demarest

January 2015: Second Edition

Revision History for the Second Edition:

2015-02-13 First Early release

2015-04-14 Second early release revision

2015-06-16 Third early release revision

2015-08-03 Fourth early release revision

See http://oreilly.com/catalog/errata.csp?isbn=0636920033844 for release details.

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are regis‐
tered trademarks of O’Reilly Media, Inc. !!FILL THIS IN!! 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 publish‐
er and authors assume no responsibility for errors or omissions, or for damages re‐
sulting from the use of the information contained herein.

ISBN: 063-6-920-03384-4
[?]
Table of Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

• Part I. Language

1. Language Basics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Characteristics of C 3
The Structure of C Programs 4
Source Files 6
Comments 8
Character Sets 9
Wide Characters and Multibyte Characters 10
Universal Character Names 13
Digraphs and Trigraphs 14
Identifiers 15
Identifier Name Spaces 17
Identifier Scope 18
How the C Compiler Works 20
The C Compiler’s Translation Phases 21
Tokens 23

2. Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Typology 25
Integer Types 26
Integer Types Defined in Standard Headers 31
Floating-Point Types 33
Complex Floating-Point Types (C99) 35
Enumerated Types 36
The Type void 37
void in Function Declarations 38
Expressions of Type void 38
Pointers to void 38

iii
The Alignment of Objects in Memory 39

3. Literals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Integer Constants 41
Floating-Point Constants 42
Decimal Floating-Point Constants 42
Hexadecimal Floating-Point Constants 43
Character Constants 44
Types and Values of Character Constants 44
Escape Sequences 46
String Literals 48

4. Type Conversions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Conversion of Arithmetic Types 54
Hierarchy of Types 54
Integer Promotion 55
Usual Arithmetic Conversions 56
Other Implicit Type Conversions 58
The Results of Arithmetic Type Conversions 59
Conversion of Nonarithmetic Types 63
Array and Function Designators 63
Explicit Pointer Conversions 65
Implicit Pointer Conversions 67
Conversions Between Pointer and Integer Types 70

5. Expressions and Operators. . . . . . . . . . . . . . . . . . . . . 73


How Expressions Are Evaluated 74
Generic Selections (C11) 74
Lvalues 75
Side Effects and Sequence Points 77
Operator Precedence and Associativity 78
Operators in Detail 79
Arithmetic Operators 80
Assignment Operators 83
Increment and Decrement Operators 86
Comparative Operators 88
Logical Operators 90
Bitwise Operators 91
Memory Addressing Operators 95
Other Operators 99
Constant Expressions 106
Integer Constant Expressions 106
Other Constant Expressions 107

6. Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109

iv Table of Contents
Expression Statements 109
Block Statements 110
Loops 111
while Statements 111
for Statements 112
do…while Statements 114
Nested Loops 115
Selection Statements 116
if Statements 116
switch Statements 117
Unconditional Jumps 119
The break Statement 119
The continue Statement 120
The goto Statement 121
The return Statement 123

7. Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Function Definitions 125
Functions and Storage Class Specifiers 126
K&R-Style Function Definitions 127
Function Parameters 128
Arrays as Function Parameters 128
The main() Function 130
Function Declarations 133
Declaring Optional Parameters 134
Declaring Variable-Length Array Parameters 134
How Functions Are Executed 135
Pointers as Arguments and Return Values 135
Inline Functions 137
Non-returning Functions 139
Recursive Functions 139
Variable Numbers of Arguments 141

8. Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Defining Arrays 143
Fixed-Length Arrays 144
Variable-Length Arrays 144
Accessing Array Elements 145
Initializing Arrays 146
Writing Initialization Lists 147
Initializing Specific Elements 148
Strings 149
Multidimensional Arrays 151
Matrices 151
Declaring Multidimensional Arrays 152

Table of Contents v
Initializing Multidimensional Arrays 152
Arrays as Arguments of Functions 153

9. Pointers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Declaring Pointers 157
Null Pointers 159
void Pointers 159
Initializing Pointers 160
Operations with Pointers 161
Using Pointers to Read and Modify Objects 161
Modifying and Comparing Pointers 163
Pointers and Type Qualifiers 165
Constant Pointers and Pointers to Constant Objects 166
Restricted Pointers 167
Pointers to Arrays and Arrays of Pointers 169
Array Pointers 170
Pointer Arrays 171
Pointers to Functions 174

10. Structures and Unions and Bit-Fields. . . . . . . . . . . . . 177


Structures 177
Defining Structure Types 178
Structure Objects and typedef Names 179
Incomplete Structure Types 179
Accessing Structure Members 180
Initializing Structures 182
Initializing Specific Members 183
Structure Members in Memory 184
Flexible Structure Members 185
Pointers as Structure Members 186
Unions 189
Defining Union Types 189
Initializing Unions 191
Anonymous Structures and Unions 191
Bit-Fields 192

11. Declarations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195


Object and Function Declarations 196
Examples 197
Storage Class Specifiers 199
Type Qualifiers 200
Declarations and Definitions 202
Complex Declarators 203
Type Names 205
typedef Declarations 206

vi Table of Contents
_Static_assert Declarations 208
Linkage of Identifiers 209
External Linkage 209
Internal Linkage 209
No Linkage 210
Storage Duration of Objects 211
Static Storage Duration 211
Thread Storage Duration 211
Automatic Storage Duration 211
Initialization 212
Implicit Initialization 212
Explicit Initialization 212

12. Dynamic Memory Management. . . . . . . . . . . . . . . . . 215


Allocating Memory Dynamically 216
Characteristics of Allocated Memory 217
Resizing and Releasing Memory 218
An All-Purpose Binary Tree 220
Characteristics 220
Implementation 221
Generating an Empty Tree 223
Inserting New Data 224
Finding Data in the Tree 225
Removing Data from the Tree 226
Traversing a Tree 229
A Sample Application 230

13. Input and Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . 233


Streams 234
Text Streams 234
Binary Streams 235
Files 235
File Position 236
Buffers 237
The Standard Streams 237
Opening and Closing Files 238
Opening a File 238
Access Modes 239
Closing a File 240
Reading and Writing 241
Byte-Oriented and Wide-Oriented Streams 241
Error Handling 242
Unformatted I/O 243
Formatted Output 249
Formatted Input 256

Table of Contents vii


Random File Access 262
Obtaining the Current File Position 262
Setting the File Access Position 263

14. Multithreading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267


Threads 268
Creating Threads 269
Other Thread Functions 271
Accessing Shared Data 273
Mutual Exclusion 274
Atomic Objects 276
Atomic Operations 276
Memory Ordering 278
Fences 280
Communication Between Threads: Condition Variables 280
Thread-local Objects and Thread-specific Storage 286
Using Thread-local Objects 286
Using Thread-specific Storage 287

15. Preprocessing Directives. . . . . . . . . . . . . . . . . . . . . . 291


Inserting the Contents of Header Files 292
How the Preprocessor Finds Header Files 293
Nested #include Directives 293
Defining and Using Macros 294
Macros Without Parameters 295
Macros with Parameters 296
Using Macros Within Macros 300
Macro Scope and Redefinition 302
Type-generic Macros 302
Conditional Compiling 303
The #if and #elif Directives 304
The defined Operator 304
The #ifdef and #ifndef Directives 305
Defining Line Numbers 305
Generating Error Messages 306
The #pragma Directive 306
The _Pragma Operator 307
Predefined Macros 308
Conditionally Defined Macros 309

• Part I. Standard Library

1. The Standard Headers. . . . . . . . . . . . . . . . . . . . . . . . 315


Using the Standard Headers 316

viii Table of Contents


Execution Environments 316
Function and Macro Calls 316
Reserved Identifiers 319
Functions with Bounds-Checking 320
Availability 320
Run-time Constraints 321
Contents of the Standard Headers 322
assert.h 322
complex.h 322
ctype.h 323
errno.h 324
fenv.h 325
float.h 326
inttypes.h 330
iso646.h 331
limits.h 332
locale.h 333
math.h 334
setjmp.h 336
signal.h 337
stdalign.h 338
stdarg.h 338
stdatomic.h 339
stdbool.h 341
stddef.h 342
stdint.h 343
stdio.h 345
stdlib.h 347
stdnoreturn.h 348
string.h 348
tgmath.h 349
threads.h 350
time.h 352
uchar.h 353
wchar.h 353
wctype.h 354

2. Functions at a Glance. . . . . . . . . . . . . . . . . . . . . . . . . 357


Input and Output 357
Mathematical Functions 359
Mathematical Functions for Integer Types 359
Floating-Point Functions 359
Function-like Macros 361
Pragmas for Arithmetic Operations 362

Table of Contents ix
The Floating-Point Environment 363
Error Handling 365
Character Classification and Conversion 366
Character Classification 367
Case Mapping 368
String Processing 369
Multibyte Characters 370
Converting Between Numbers and Strings 371
Searching and Sorting 373
Memory Block Handling 373
Dynamic Memory Management 374
Date and Time 374
Process Control 376
Communication with the Operating System 376
Signals 376
Internationalization 377
Nonlocal Jumps 378
Multithreading (C11) 378
Thread Functions 379
Atomic Operations 380
Debugging 382
Error Messages 383

3. Standard Library Functions. . . . . . . . . . . . . . . . . . . . 385

• Part I. Basic Tools

1. Compiling with GCC. . . . . . . . . . . . . . . . . . . . . . . . . . 835


The GNU Compiler Collection 835
Obtaining and Installing GCC 836
Compiling C Programs with GCC 837
Step by Step 838
Multiple Input Files 846
Dynamic Linking and Shared Object Files 848
Freestanding Programs 848
C Dialects 849
Compiler Warnings 850
Optimization 852
The -O Levels 852
The -f Flags 854
Floating-Point Optimization 854
Architecture-Specific Optimization 855
Why Not Optimize? 856
Debugging 857

x Table of Contents
Profiling 857
Option and Environment Variable Summary 858
Command-Line Options 858
Environment Variables 862

2. Using make to Build C Programs. . . . . . . . . . . . . . . . 863


Targets, Prerequisites, and Commands 864
The Makefile 864
Rules 865
The Command Script 866
Pattern Rules 867
Suffix Rules 868
Built-in Rules 869
Implicit Rule Chains 870
Double-Colon Rules 871
Comments 872
Variables 873
Assignment Operators 873
Variables and Whitespace 875
Target-Specific Variable Assignments 876
The Automatic Variables 878
Other Built-in Variables 879
Environment Variables 881
Phony Targets 881
Other Target Attributes 883
Macros 884
Functions 885
Built-in Functions 886
User-Defined Functions 889
Directives 890
Conditionals 890
Includes 892
Other Directives 892
Running make 894
Generating Header Dependencies 894
Recursive make Commands 895
Command-Line Options 897
Special Targets Used as Runtime Options 900
GCC Options for Generating Makefile Rules 901

3. Debugging C Programs with GDB. . . . . . . . . . . . . . . . 903


Installing GDB 904
A Sample Debugging Session 904
Symbol Information 905
Finding a Bug 905

Table of Contents xi
Starting GDB 909
Command-Line Arguments 909
Command-Line Options 910
Initialization Files 913
Using GDB Commands 914
Command Completion 915
Displaying Help for Commands 915
Status Information 916
Running a Program in the Debugger 918
Displaying Source Code 920
Working with Breakpoints 921
Resuming Execution After a Break 925
Analyzing the Stack 928
Displaying Data 931
Watchpoints: Observing Operations on Variables 936
Analyzing Core Files in GDB 939

xii Table of Contents


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, reliable 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 inter‐
national C standard, ISO/IEC 9899:1999, including the Technical Cor‐
rigenda, 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 ab‐
breviation C99.
This book is not an introduction to programming in C. Although it cov‐
ers 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 re‐
lated 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

xiii
standard library; and the third part describes the process of compiling
and testing programs with the popular tools in the GNU software col‐
lection.

Part I
Part I, which deals with the C language, includes Chapter 1 through
14. After Chapter 1, which describes the general concepts and ele‐
ments of the language, each chapter is devoted to a specific topic,
such as types, statements, or pointers. Although the topics are or‐
dered so that the fundamental concepts for each new topic have been
presented in an earlier chapter—types, for example, are described be‐
fore 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 ar‐
rays is necessary in Chapter 5 (which covers expressions and opera‐
tors), even though pointers and arrays are not described in full detail
until Chapter 8 and 9.
Chapter 1
Describes the characteristics of the language and how C programs
are structured and compiled. This chapter introduces basic con‐
cepts such as the translation unit, character sets, and identifiers.
Chapter 2
Provides an overview of types in C and describes the basic types,
the type void, and enumerated types.
Chapter 3
Describes numeric constants, character constants, and string liter‐
als, including escape sequences.
Chapter 4
Describes implicit and explicit type conversions, including integer
promotion and the usual arithmetic conversions.
Chapter 5
Describes the evaluation of expressions, all the operators, and
their compatible operands.
Chapter 6
Describes C statements such as blocks, loops, and jumps.
Chapter 7
Describes function definitions and function calls, including recur‐
sive and inline functions.

xiv Preface
Chapter 8
Describes fixed-length and variable-length arrays, including
strings, array initialization, and multidimensional arrays.
Chapter 9
Describes the definition and use of pointers to objects and func‐
tions.
Chapter 10
Describes the organization of data in these user-defined derived
types.
Chapter 11
Describes the general syntax of a declaration, identifier linkage,
and the storage duration of objects.
Chapter 12
Describes the standard library’s dynamic memory management
functions, illustrating their use in a sample implementation of a
generalized binary tree.
Chapter 13
Describes the C concept of input and output, with an overview of
the use of the standard I/O library.
Chapter 14
Describes the definition and use of macros, conditional compiling,
and all the other preprocessor directives and operators.

Part II
Part II, consisting of Chapter 15, 16, and 17, is devoted to the C stan‐
dard library. It provides an overview of standard headers and also
contains a detailed function reference.
Chapter 15
Describes contents of the headers and their use. The headers con‐
tain all of the standard library’s macros and type definitions.
(to come)
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
Describes each standard library function in detail, in alphabetical
order, and contains examples to illustrate the use of each function.

Preface xv
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 de‐
bugger. The tools described here are those in the GNU software col‐
lection.
Chapter 18
Describes the principal capabilities that the widely used compiler
offers for C programmers.
Chapter 19
Describes how to use the make program to automate the compiling
process for large programs.
(to come)
Describes how to run a program under the control of the GNU de‐
bugger and how to analyze programs’ runtime behavior to find log‐
ical errors.

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 http://www.open-
std.org/jtc1/sc22/wg14, 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 pro‐
cess. 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, http://cm.bell-
labs.com/cm/cs/who/dmr.
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 http://docs.sun.com/source/
806-3568/ncg_goldberg.html.

xvi Preface
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, vari‐
ables, functions, macros, types, parameters, and literals. Also used
for console commands and options, and the output from such com‐
mands.
Constant width bold
Highlights the function or statement under discussion in code ex‐
amples. In compiler, make, and debugger sessions, this font indi‐
cates 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.

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 sig‐
nificant 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
significant amount of example code from this book into your product’s
documentation does require permission.

Preface xvii
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 <permissions@oreil
ly.com>.

Safari® Books Online

Safari Books Online is an on-demand digital library that


delivers expert content in both book and video form from
the world’s leading authors in technology and business.

Technology professionals, software developers, web designers, and


business and creative professionals use Safari Books Online as their
primary resource for research, problem solving, learning, and certifi‐
cation training.
Safari Books Online offers a range of product mixes and pricing pro‐
grams for organizations, government agencies, and individuals. Sub‐
scribers have access to thousands of books, training videos, and pre‐
publication manuscripts in one fully searchable database from pub‐
lishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley
Professional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press,
Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM
Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Rid‐
ers, McGraw-Hill, Jones & Bartlett, Course Technology, and dozens
more. For more information about Safari Books Online, please visit us
online.

How to Contact Us
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)

xviii Preface
We have a web page for this book, where we list errata, examples, and
any additional information. You can access this page at http://
www.oreilly.com/catalog/<catalog page>.
To comment or ask technical questions about this book, send email to
<[email protected]>.
For more information about our books, courses, conferences, and
news, see our website at http://www.oreilly.com.
Find us on Facebook: http://facebook.com/oreilly
Follow us on Twitter: http://twitter.com/oreillymedia
Watch us on YouTube: http://www.youtube.com/oreillymedia

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 criti‐
cism 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 Jea‐
nette—both of them now students of computer science—who strength‐
ened 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.

Preface xix
PART I
Language
Chapter 1
Language Basics

This chapter describes the basic characteristics and elements of the C


programming 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 Mur‐
ray Hill, New Jersey, for the purpose of implementing the Unix operat‐
ing system and utilities with the greatest possible degree of independ‐
ence 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 op‐
erating system in C, leaving only a minimum of system-specific hard‐
ware manipulation to be coded in assembler.
C’s ancestors are the typeless programming languages BCPL (the Ba‐
sic Combined Programming Language), developed by Martin Ri‐
chards; 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 lan‐
guage in 1978. As the first de facto standard, their description is com‐

3
monly referred to simply as “K&R.”1 C owes its high degree of porta‐
bility to a compact core language that contains few hardware-
dependent elements. For example, the C language proper has no file
access or dynamic memory management statements. 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 run‐
ning on a new system, you can compile most of the functions in the
standard library with no further modification, because they are in turn
written in portable C. As a result, C compilers are available for practi‐
cally every computer system.
Because C was expressly designed for system programming, it is hard‐
ly surprising that one of its major uses today is in programming em‐
bedded 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, or blocks. 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 addi‐
tion 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 pro‐
gram 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

1. 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


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)

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;
}

Output:
Areas of Circles

Radius Area
-------------------------

The Structure of C Programs 5


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 information 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 di‐
rective #include <stdio.h> declares the function indirectly by di‐
recting the compiler’s preprocessor to insert the contents of that file.
(See also the section “How the C Compiler Works” (page 20) 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 circular
Area() before the function main(). If we had, then the prototype dec‐
laration of circularArea() would be superfluous, because the defini‐
tion of the function is also a declaration.
Function definitions cannot be nested inside one another: you can de‐
fine a local variable within a function block, but not a local function.

Source Files
The function definitions, global declarations and preprocessing direc‐
tives 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 gener‐
ally 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 pro‐


gram 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 func‐
tions. It is customary to label C source files with the filename suf‐
fix .c .
Example 1-2 and 1-3 show the same program as Example 1-1, but divi‐
ded into two source files.

6 Chapter 1: Language Basics


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... */
}

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 refer‐
ence 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.
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” (page 23) at the end of this chapter for more de‐
tail.
Any number of whitespace characters can occur between two succes‐
sive 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 it‐

Source Files 7
self, 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 formatting. 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 state‐
ments.

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 with‐
in 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 ex‐
plains 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 standard, but most compilers already supported them even be‐
fore C99. They are sometimes called “C++-style” comments, although
they originated in C’s forerunner, BCPL.
Inside the quotation marks that delimit a character constant or a
string literal, the characters /* and // do not start a comment. For ex‐
ample, the following statement contains no comments:
printf( "Comments in C begin with /* or //.\n" );

The only thing that the preprocessor looks for in examining the char‐
acters in a comment is the end of the comment; thus it is not possible
to nest block comments. However, you can insert /* and */ to com‐
ment out part of a program that contains line comments:

8 Chapter 1: Language Basics


/* Temporarily removing two lines:
const double pi = 3.1415926536; // Pi is constant
area = pi * r * r // Calculate the area
Temporarily removed up to here */

If you want to comment out part of a program that contains block


comments, you can use a conditional preprocessor directive (de‐
scribed in Chapter 14):
#if 0
const double pi = 3.1415926536; /* Pi is constant */
area = pi * r * r /* Calculate the area */
#endif

The preprocessor replaces each comment with a space. The character


sequence min/*max*/Value thus becomes the two tokens min Value.

Character Sets
C makes a distinction between the environment in which the compiler
translates the source files of a program—the translation environment
—and the environment in which the compiled program is executed,
the execution environment. Accordingly, C defines two character sets:
the source character set is the set of characters that may be used in C
source code, and the execution character set is the set of characters
that can be interpreted by the running program. In many C implemen‐
tations, the two character sets are identical. If they are not, then the
compiler converts the characters in character constants and string lit‐
erals in the source code into the corresponding elements of the execu‐
tion character set.
Each of the two character sets includes both a basic character set and
extended characters. The C language does not specify the extended
characters, which are usually dependent on the local language. The
extended characters together with the basic character set make up
the extended character set.
The basic source and execution character sets both contain the follow‐
ing types of characters:
The 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 decimal digits
0 1 2 3 4 5 6 7 8 9
The following 29 punctuation marks
! " # % & ' () * + , − . / : ; < = > ? [ \ ] ^ _ { | } ~

Character Sets 9
The five whitespace characters
Space, horizontal tab, vertical tab, new line, and form feed
The basic execution character set also includes four nonprintable
characters : the null character, which acts as the termination mark in
a character string; alert; backspace; and carriage return. To represent
these characters in character and string literals, type the correspond‐
ing escape sequences beginning with a backslash: \0 for the null char‐
acter, \a for alert, \b for backspace, and \r for carriage return. See
Chapter 3 for more details.
The actual numeric values of characters—the character codes —may
vary from one C implementation to another. The language itself impo‐
ses only the following conditions:

• Each character in the basic character set must be representable in


one byte.
• The null character is a byte in which all bits are 0.
• The value of each decimal digit after 0 is greater by one than that
of the preceding digit.

Wide Characters and Multibyte Characters


C was originally developed in an English-speaking environment where
the dominant character set was the 7-bit ASCII code. Since then, the
8-bit byte has become the most common unit of character encoding,
but software for international use generally has to be able to repre‐
sent more different characters than can be coded in one byte. Fur‐
thermore, a variety of multibyte character encoding schemes have
long been in use internationally to represent non-Latin alphabets and
the nonalphabetic Chinese, Japanese, and Korean writing systems. In
1994, with the adoption of “Normative Addendum 1,” ISO C standar‐
dized two ways of representing larger character sets:

• wide characters, in which the same bit width is used for every
character in a character set, and
• multibyte characters, in which a given character can be represent‐
ed by one or several bytes, and the character value of a given byte
sequence can depend on its context in a string or stream.

10 Chapter 1: Language Basics


Although C now provides abstract mechanisms to manipu‐
late and convert the different kinds of encoding schemes,
the language itself doesn’t define or specify any encoding
scheme, or any character set except the basic source and
execution character sets described in the previous section.
In other words, it is left up to individual implementations
to specify how to encode wide characters, and what multi‐
byte encoding schemes to support.

Wide Characters
Since the 1994 addendum, C has provided not only the type char, but
also wchar_t, the wide character type. This type, defined in the head‐
er file stddef.h, is large enough to represent any element of the given
implementation’s extended character sets.
Although the C standard does not require support for Unicode charac‐
ter sets, many implementations use the Unicode transformation for‐
mats UTF-16 and UTF-32 (see http://www.unicode.org/) for wide char‐
acters. The Unicode standard is largely identical with the ISO/IEC
10646 standard, and is a superset of many previously existing charac‐
ter sets, including the 7-bit ASCII code. When the Unicode standard is
implemented, the type wchar_t is at least 16 or 32 bits wide, and a
value of type wchar_t represents one Unicode character. For example,
the following definition initializes the variable wc with the Greek letter
α.
wchar_t wc = '\x3b1';

The escape sequence beginning with \x indicates a character code in


hexadecimal notation to be stored in the variable—in this case, the
code for a lowercase alpha.
For better Unicode support, C11 introduced the additional wide-
character types char16_t and char32_t, which are defined as un‐
signed integer types in the header file uchar.h. Characters of the type
char16_t are encoded in UTF-16 in C implementations that define the
macro __STDC_UTF_16__. Similarly, in implementations that define the
macro __STDC_UTF_32__, characters of the type char32_t are enco‐
ded in UTF-32.
Multibyte Characters
In multibyte character sets, each character is coded as a sequence of
one or more bytes. Both the source and execution character sets may
contain multibyte characters. If they do, then each character in the

Character Sets 11
basic character set occupies only one byte, and no multibyte character
except the null character may contain any byte in which all bits are 0.
Multibyte characters can be used in character constants, string liter‐
als, identifiers, comments, and header filenames. Many multibyte
character sets are designed to support a certain language, such as the
Japanese Industrial Standard character set (JIS). The multibyte UTF-8
character set, defined by the Unicode Consortium, is capable of repre‐
senting all Unicode characters. UTF-8 uses from one to four bytes to
represent a character.
The key difference between multibyte characters and wide characters
(that is, characters of the type wchar_t, char16_t or char32_t) is that
wide characters are all the same size, and multibyte characters are
represented by varying numbers of bytes. This representation makes
multibyte strings more complicated to process than strings of wide
characters. For example, even though the character A can be repre‐
sented in a single byte, finding it in a multibyte string requires more
than a simple byte-by-byte comparison, because the same byte value
in certain locations could be part of a different character. Multibyte
characters are well suited for saving text in files, however (see Chap‐
ter 13). Furthermore, the encoding of multibyte characters is inde‐
pendent of the system architecture, while encoding of wide characters
is dependent on the given system’s byte order: that is, the bytes of a
wide character may be in big-endian or little-endian order, depending
on the system.
Conversion
C provides standard functions to obtain the wchar_t value of any mul‐
tibyte character, and to convert any wide character to its multibyte
representation. For example, if the C compiler uses the Unicode
standards UTF-16 and UTF-8, then the following call to the function
wctomb() (read: “wide character to multibyte”) obtains the multibyte
representation of the character α:
wchar_t wc = L'\x3B1'; // Greek lower-case alpha,α
char mbStr[10] = "";
int nBytes = 0;
nBytes = wctomb( mbStr, wc );
if( nBytes < 0)
puts("Not a valid multibyte character in your locale.");

After a successful function call, the array mbStr contains the multibyte
character, which in this example is the sequence "\xCE\xB1". The
wctomb() function’s return value, assigned here to the variable
nBytes, is the number of bytes required to represent the multibyte
character, namely 2.

12 Chapter 1: Language Basics


The standard library also provides conversion functions for char16_t
and char32_t, the new wide-character types introduced in C11, such
as the function c16rtomb(), which returns the multibyte character
that corresponds to a given wide character of the type char16_t (see
the section “Multibyte Characters” in Chapter 17).

Universal Character Names


C also supports universal character names as a way to use the exten‐
ded character set regardless of the implementation’s encoding. You
can specify any extended character by its universal character name,
which is its Unicode value in the form:
\uXXXX

or:
\UXXXXXXXX

where XXXX or XXXXXXXX is a Unicode code point in hexadecimal nota‐


tion. Use the lowercase u prefix followed by four hexadecimal digits,
or the uppercase U followed by exactly eight hex digits. If the first four
hexadecimal digits are zero, then the same universal character name
can be written either as \uXXXX or as \U0000XXXX.
Universal character names are permissible in identifiers, character
constants, and string literals. However, they must not be used to rep‐
resent characters in the basic character set.
When you specify a character by its universal character name, the
compiler stores it in the character set used by the implementation.
For example, if the execution character set in a localized program is
ISO 8859-7 (8-bit Greek), then the following definition initializes the
variable alpha with the code \xE1:
char alpha = '\u03B1';

However, if the execution character set is UTF-16, then you need to


define the variable as a wide character:
wchar_t alpha = '\u03B1'; // or char16_t alpha = u'\u03B1';

In this case, the character code value assigned to alpha is hexadeci‐


mal 3B1, the same as the universal character name.

Not all compilers support universal character names.

Character Sets 13
Digraphs and Trigraphs
C provides alternative representations for a number of punctuation
marks that are not available on all keyboards. Six of these are the di‐
graphs, or two-character tokens, which represent the characters
shown in Table 1-1.
Table 1-1. Digraphs
Digraph Equivalent
<: [
:> ]
<% {
%> }
%: #
%:%: ##

These sequences are not interpreted as digraphs if they occur within


character constants or string literals. In all other positions, they be‐
have exactly like the single-character tokens they represent. For ex‐
ample, the following code fragments are perfectly equivalent, and pro‐
duce the same output. With digraphs:
int arr<::> = <% 10, 20, 30 %>;
printf( "The second array element is <%d>.\n", arr<:1:> );

Without digraphs:
int arr[] = { 10, 20, 30 };
printf( "The second array element is <%d>.\n", arr[1] );

Output:
The second array element is .

C also provides trigraphs, three-character representations, all of them


beginning with two question marks. The third character determines
which punctuation mark a trigraph represents, as shown in Table 1-2.
Table 1-2. Trigraphs
Trigraph Equivalent
??( [
??) ]
??< {
??> }
??= #
??∕ \

14 Chapter 1: Language Basics


Trigraph Equivalent
??! |
??' ^
??- ~

Trigraphs allow you to write any C program using only the characters
defined in ISO/IEC 646, the 1991 standard corresponding to 7-bit AS‐
CII. The compiler’s preprocessor replaces the trigraphs with their
single-character equivalents in the first phase of compilation. This
means that the trigraphs, unlike digraphs, are translated into their
single-character equivalents no matter where they occur, even in
character constants, string literals, comments, and preprocessing di‐
rectives. For example, the preprocessor interprets the statement’s
second and third question marks below as the beginning of a trigraph:
printf("Cancel???(y/n) ");

Thus the line produces the following unintended preprocessor output:


printf("Cancel?[y/n) ");

If you need to use one of these three-character sequences and do not


want it to be interpreted as a trigraph, you can write the question
marks as escape sequences:
printf("Cancel\?\?\?(y/n) ");

If the character following any two question marks is not one of those
shown in Table 1-2, then the sequence is not a trigraph, and remains
unchanged.

As another substitute for punctuation characters in addi‐


tion to the digraphs and trigraphs, the header file iso646.h
contains macros that define alternative representations of
C’s logical operators and bitwise operators, such as and
for && and xor for ^. For details, see (to come).

Identifiers
The term identifier refers to the names of variables, functions, mac‐
ros, structures and other objects defined in a C program. Identifiers
can contain the following characters:

• The letters in the basic character set, a-z and A-Z. Identifiers are
case-sensitive.

Identifiers 15
• The underscore character, _.
• The decimal digits 0-9, although the first character of an identifier
must not be a digit.
• Universal character names that represent the letters and digits of
other languages.

The permissible universal characters are defined in Annex D of the C


standard, and correspond to the characters defined in the ISO/IEC TR
10176 standard, minus the basic character set.
Multibyte characters may also be permissible in identifiers. However,
it is up to the given C implementation to determine exactly which mul‐
tibyte characters are permitted and what universal character names
they correspond to.
The following 44 keywords are reserved in C, each having a specific
meaning to the compiler, and must not be used as identifiers:
auto extern short while
break float signed _Alignas
case for sizeof _Alignof
char goto static _Atomic
const if struct _Bool
continue inline switch _Complex
default int typedef _Generic
do long union _Imaginary
double register unsigned _Noreturn
else restrict void _Static_assert
enum return volatile _Thread_local

The following examples are valid identifiers:


x dollar Break error_handler scale64

The following are not valid identifiers:


1st_rank switch y/n x-ray

If the compiler supports universal character names, then α is also an


example of a valid identifier, and you can define a variable by that
name:
double α = 0.5;

Your source code editor might save the character α in the source file
as the universal character \u03B1.

16 Chapter 1: Language Basics


When choosing identifiers in your programs, remember that many
identifiers are already used by the C standard library. These include
the names of standard library functions, which you cannot use for
functions you define or for global variables. See Chapter 15 for de‐
tails.
The C compiler provides the predefined identifier __func__, which
you can use in any function to access a string constant containing the
name of the function. This is useful for logging or for debugging out‐
put; for example:
#include <stdio.h>
int test_func( char *s )
{
if( s == NULL) {
fprintf( stderr,
"%s: received null pointer argument\n", __func__ );
return -1;
}
/* ... */
}

In this example, passing a null pointer to the function test_func()


generates the following error message:
test_func: received null pointer argument

There is no limit on the length of identifiers. However, most compilers


consider only a limited number of characters in identifiers to be signif‐
icant. In other words, a compiler might fail to distinguish between two
identifiers that start with a long identical sequence of characters. To
conform to the C standard, a compiler must treat at least the first 31
characters as significant in the names of functions and global vari‐
ables (that is, identifiers with external linkage), and at least the first
63 characters in all other identifiers.

Identifier Name Spaces


All identifiers fall into exactly one of the following four categories,
which constitute separate name spaces:

• Label names.
• Tags, which identify structure, union and enumeration types.
• Names of structure or union members. Each structure or union
constitutes a separate name space for its members.
• All other identifiers, which are called ordinary identifiers.

Identifiers 17
Identifiers that belong to different name spaces may be the same
without causing conflicts. In other words, you can use the same name
to refer to different objects, if they are of different kinds. For example,
the compiler is capable of distinguishing between a variable and a la‐
bel with the same name. Similarly, you can give the same name to a
structure type, an element in the structure, and a variable, as the fol‐
lowing example shows:
struct pin { char pin[16]; /* ... */ };
_Bool check_pin( struct pin *pin )
{
int len = strlen( pin->pin );
/* ... */
}

The first line of the example defines a structure type identified by the
tag pin, containing a character array named pin as one of its mem‐
bers. In the second line, the function parameter pin is a pointer to a
structure of the type just defined. The expression pin->pin in the
fourth line designates the member of the structure that the function’s
parameter points to. The context in which an identifier appears always
determines its name space with no ambiguity. Nonetheless, it is gen‐
erally a good idea to make all identifiers in a program distinct, in or‐
der to spare human readers unnecessary confusion.

Identifier Scope
The scope of an identifier refers to that part of the translation unit in
which the identifier is meaningful. Or to put it another way, the identi‐
fier’s scope is that part of the program that can “see” that identifier.
The type of scope is always determined by the location at which you
declare the identifier (except for labels, which always have function
scope ). Four kinds of scope are possible:
File scope
If you declare an identifier outside all blocks and parameter lists,
then it has file scope. You can then use the identifier anywhere af‐
ter the declaration and up to the end of the translation unit.
Block scope
Except for labels, identifiers declared within a block have block
scope. You can use such an identifier only from its declaration to
the end of the smallest block containing that declaration. The
smallest containing block is often, but not necessarily, the body of
a function definition. In C99, declarations do not have to be placed
before all statements in a function block. The parameter names in
the head of a function definition also have block scope, and are
valid within the corresponding function block.

18 Chapter 1: Language Basics


Function prototype scope
The parameter names in a function prototype have function proto‐
type scope. Because these parameter names are not significant
outside the prototype itself, they are meaningful only as com‐
ments, and can also be omitted. See Chapter 7 for further informa‐
tion.
Function scope
The scope of a label is always the function block in which the label
occurs, even if it is placed within nested blocks. In other words,
you can use a goto statement to jump to a label from any point
within the same function that contains the label. (Jumping into
nested blocks is not a good idea, though: see Chapter 6 for de‐
tails.)
The scope of an identifier generally begins after its declaration. How‐
ever, the type names, or tags, of structure, union, and enumeration
types and the names of enumeration constants are an exception to
this rule: their scope begins immediately after their appearance in the
declaration, so that they can be referenced again in the declaration it‐
self. (Structures and unions are discussed in detail in Chapter 10; enu‐
meration types are described in Chapter 2.) For example, in the fol‐
lowing declaration of a structure type, the last member of the struc‐
ture, next, is a pointer to the very structure type that is being de‐
clared:
struct Node { /* ... */
struct Node *next; }; // Define a
structure type
void printNode( const struct Node *ptrNode); // Declare a func‐
tion

int printList( const struct Node *first ) // Begin a func‐


tion definition
{
struct Node *ptr = first;

while( ptr != NULL ) {


printNode( ptr );
ptr = ptr->next;
}
}

In this code snippet, the identifiers Node, next, printNode, and print
List all have file scope. The parameter ptrNode has function proto‐
type scope, and the variables first and ptr have block scope.
It is possible to use an identifier again in a new declaration nested
within its existing scope, even if the new identifier does not have a dif‐

Identifiers 19
ferent name space. If you do so, then the new declaration must have
block or function prototype scope, and the block or function prototype
must be a true subset of the outer scope. In such cases, the new decla‐
ration of the same identifier hides the outer declaration, so that the
variable or function declared in the outer block is not visible in the in‐
ner scope. For example, the following declarations are permissible:
double x; // Declare a variable x with file scope
long calc( double x ); // Declare a new x with function proto‐
type scope

int main()
{
long x = calc( 2.5 ); // Declare a long variable x with
block scope

if( x < 0 ) // Here x refers to the long variable


{ float x = 0.0F; // Declare a new float variable x with
block scope
/*...*/
}
x *= 2; // Here x refers to the long variable
again
/*...*/
}

In this example, the long variable x delcared in the main() function


hides the global variable x with type double. Thus there is no direct
way to access the double variable x from within main(). Furthermore,
in the conditional block that depends on the if statement, x refers to
the newly declared float variable, which in turn hides the long vari‐
able x.

How the C Compiler Works


Once you have written a source file using a text editor, you can invoke
a C compiler to translate it into machine code. The compiler operates
on a translation unit consisting of a source file and all the header files
referenced by #include directives. If the compiler finds no errors in
the translation unit, it generates an object file containing the corre‐
sponding machine code. Object files are usually identified by the file‐
name suffix .o or .obj . In addition, the compiler may also generate an
assembler listing (see Chapter 19).
Object files are also called modules. A library, such as the C standard
library, contains compiled, rapidly accessible modules of the standard
functions.

20 Chapter 1: Language Basics


The compiler translates each translation unit of a C program—that is,
each source file with any header files it includes—into a separate ob‐
ject file. The compiler then invokes the linker, which combines the ob‐
ject files, and any library functions used, in an executable file.
Figure 1-1 illustrates the process of compiling and linking a program
from several source files and libraries. The executable file also con‐
tains any information that the target operating system needs to load
and start it.

Figure 1-1. From source code to executable file

The C Compiler’s Translation Phases


The compiling process takes place in eight logical steps. A given com‐
piler may combine several of these steps, as long as the results are
not affected. The steps are:

1. Characters are read from the source file and converted, if necessa‐
ry, into the characters of the source character set. The end-of-line
indicators in the source file, if different from the new line charac‐
ter, are replaced. Likewise, any trigraph sequences are replaced

How the C Compiler Works 21


with the single characters they represent. (Digraphs, however are
left alone; they are not converted into their single-character equiv‐
alents.)
2. Wherever a backslash is followed immediately by a newline char‐
acter, the preprocessor deletes both. Since a line end character
ends a preprocessor directive, this processing step lets you place a
backslash at the end of a line in order to continue a directive, such
as a macro definition, on the next line.

Every source file, if not completely empty, must end with a


new line character.

3. The source file is broken down into preprocessor tokens (see the
next section, “Tokens” (page 23)) and sequences of whitespace
characters. Each comment is treated as one space.
4. The preprocessor directives are carried out and macro calls are
expanded.

Steps 1 through 4 are also applied to any files inserted by


#include directives. Once the compiler has carried out
the preprocessor directives, it removes them from its
working copy of the source code.

5. The characters and escape sequences in character constants and


string literals are converted into the corresponding characters in
the execution character set.
6. Adjacent string literals are concatenated into a single string.
7. The actual compiling takes place: the compiler analyzes the se‐
quence of tokens and generates the corresponding machine code.
8. The linker resolves references to external objects and functions,
and generates the executable file. If a module refers to external
objects or functions that are not defined in any of the translation
units, the linker takes them from the standard library or another
specified library. External objects and functions must not be de‐
fined more than once in a program.

For most compilers, either the preprocessor is a separate program, or


the compiler provides options to perform only the preprocessing
(steps 1 through 4 in the preceding list). This setup allows you to veri‐

22 Chapter 1: Language Basics


fy that your preprocessor directives have the intended effects. For a
more practically oriented look at the compiling process, see Chap‐
ter 19.

Tokens
A token is either a keyword, an identifier, a constant, a string literal,
or a symbol. Symbols in C consist of one or more punctuation charac‐
ters, and function as operators or digraphs, or have syntactic impor‐
tance, like the semicolon that terminates a simple statement, or the
braces { } that enclose a block statement. For example, the following
C statement consists of five tokens:
printf("Hello, world.\n");

The individual tokens are:


printf
(
"Hello, world.\n"
)
;

The tokens interpreted by the preprocessor are parsed in the third


translation phase. These are only slightly different from the tokens
that the compiler interprets in the seventh phase of translation:

• Within an #include directive, the preprocessor recognizes the ad‐


ditional tokens <filename> and "filename".
• During the preprocessing phase, character constants and string
literals have not yet been converted from the source character set
to the execution character set.
• Unlike the compiler proper, the preprocessor makes no distinction
between integer constants and floating-point constants.

In parsing the source file into tokens, the compiler (or preprocessor)
always applies the following principle: each successive non-
whitespace character must be appended to the token being read, un‐
less appending it would make a valid token invalid. This rule resolves
any ambiguity in the following expression, for example:
a+++b

Because the first + cannot be part of an identifier or keyword starting


with a, it begins a new token. The second + appended to the first
forms a valid token—the increment operator—but a third + does not.
Hence the expression must be parsed as:
a ++ + b

How the C Compiler Works 23


See Chapter 19 for more information on compiling C programs.

24 Chapter 1: Language Basics


Other documents randomly have
different content
Ind., and thence by wagon, arrived in Decatur. The wagon was
backed up to the steps at the front door of the Macon House
and the question of how to unload it and get it into the house
was a puzzling one. Not a man except the landlord was to be
found, but he soon solved the problem. "Court will soon adjourn
and there will be plenty of men," and almost as he spoke the
crowd began to appear. They gathered curiously around the
wagon that blocked the entrance. Landlord Krone explained:
"'There is a piano in that box that this woman here wants
someone to help unload. Who will lend a hand?'
"A tall gentleman stepped forward and, throwing off a big gray
Scotch shawl, exclaimed, 'Come on, Swett, you are the next
biggest man.'
"That was my first meeting with Abraham Lincoln.
"After a few moments' consultation with the driver of the
wagon, Mr. Lincoln went into the basement where Mr. Krone had
a carpenter shop, and returned with two heavy timbers across
his shoulders. With them he established communication
between the wagon and the front door steps. The piano was
unloaded with the assistance of Mr. Linder and Mr. Swett, amid
jokes and jeers galore, most of the jeers coming from little
Judge Logan.
"Before the legs had been screwed into place, dinner was
announced, and the men hurried to the back porch where two
tin wash basins, a long roller towel and a coarse comb, fastened
to the wall by a long string, afforded toilet accommodations for
all guests. When dinner was served, 'Mother Krone' placed a
roast of beef in front of Dr. Trowbridge to be carved and
exclaimed, 'Men, if you can't get your teeth through this beef
you will have to fall back on the sausage. I agreed to try
roasting it without parboiling it, and I am afraid it will be
tougher than it was yesterday, and that was bad enough.'
"The beef, however, proved to be tender and juicy and was
highly praised by the guests. I recall this incident because Mr.
Lincoln once reminded me of it, saying that 'that was the time
he learned that roast beef ought not to be boiled.'
"After dinner, Mr. Lincoln superintended the setting up of the
piano, even to seeing that it stood squarely in the center of the
wall space allotted it, and then received my thanks with a polite
bow and asked: 'Are you expecting to follow the court and give
concerts?' The immense relief expressed on his countenance,
when he was assured that he would not be called upon to
repeat the performance was very laughable.
"'Then may we have one tune before we go?' he asked, and I
played 'Rosin the Bow,' with variations.
"Someone shouted, 'Come on, boys, the judge will be waiting,'
and after I had assured them that if they desired it, I would give
my 'first and only concert on this circuit' when they returned to
the hotel in the evening, the crowd dispersed.
"Here I wish to note that in the crowd that had assembled to
watch the unloading of the piano, the members of the bar, Mr.
Lincoln's friends and equals, always addressed him as 'Mr.
Lincoln,' while to the rabble and hangers-on he was often 'Abe.'
"The piano was a 'Gilbert,' made in Boston, and its fame
extended far and wide. It was visited by people from all over
the state, stage coach passengers frequently 'holding the stage'
while they went down to the other tavern (the Harrell House
was the stage office) to see and hear the novel instrument.
"That evening a notable crowd assembled in the parlor of the
Macon House. Judge Davis, who did not put up with Landlord
Krone but was the guest of Mrs. A. A. Powers, came in after
supper; and practically all of the bar of the Eighth Judicial
District was present at what I suppose we would now call a
recital. I found that Mr. Charles Brown, a wealthy landowner and
stock dealer of McLean County, not only sang but played a little
and I called on him for assistance.
"The program, as I remember it, will illustrate the style of music
in vogue at that period.
"For show pieces, I played the 'Battle of Prague' and the
'Carnival of Venice,' then followed with 'Washington's March,'
'Come Haste to the Wedding,' and 'Woodup Quick Step' to
convince the audience that I did know a tune or two. For
tragedy, I sang Henry Russel's 'Maniac' and 'The Ship on Fire,'
and then made their blood run cold with the wild wail of the
'Irish Mother's Lament.' For comic, we sang 'The Widdy McGee'
and 'I Won't Be a Nun,' topping off with 'Old Dan Tucker,' 'Lucy
Long,' and 'Jim Crow,' the crowd joining in the chorus. These
were followed by more serious music. Mr. Brown and Mr. Swett
joined me in the duet 'Moonlight, Music, Love, and Flowers,'
'Rocked in the Cradle of the Deep,' 'Pilgrim Fathers,'
'Bonaparte's Grave,' and 'Kathleen Mavourneen.' Each and all
met with applause.
"As a finale, I sang 'He Doeth All Things Well,' after which Mr.
Lincoln, in a very grave manner, thanked me for the evening's
entertainment, and said: 'Don't let us spoil that song by any
other music tonight.' Many times afterwards I sang that song for
Mr. Lincoln and for Governor Oglesby, with whom it was also a
favorite."

Another limitation must be found in Lincoln's morbid cautiousness.


Herndon tells us that his very walk gave the impression of craftiness;
that it was not the product of deceit, but only of a caution so
excessive that it became something more than second nature. He
was secretive to a marked degree. When he seemed to be
confidential it was in minor matters, or matters on which he had
already made up his mind and intended soon to make a public
statement. Whatever may be the true story of his engagement to
Mary Todd and of those stormy and obscure months between "that
fatal first of January, 1840," and the date of their wedding,
November 4, 1842, Lincoln's letters to Speed show an excess of
caution that was positively abnormal. That it was a mark of insanity
has been vigorously denied and with much apparent reason; but if it
was not the mark of acute mental aberration, it was the
manifestation of a permanent mental trait. Such a nature, which
debated like Hamlet the question of suicide and actually printed a
brief article which was later cut from the files of the Springfield
paper—probably by Lincoln himself—which lingered shivering on the
brink of matrimony like the "timorous mortal" of whom Lincoln was
taught to sing, must have hesitated long before coming to such a
confident poise between alternating faith and doubt as that he could
have stood before the altar of a Presbyterian church in Springfield or
in Washington and taken upon him the vows of church membership.
Different writers have attempted to account for Lincoln's failure to
affiliate with the church wholly on the basis of his being greater than
the churches. I quote from one of these characteristic addresses,
and one that is in many respects excellent:

"Perhaps his religious nature was so broad that it could not be


compassed within the limits of any particular creed or system of
doctrines. Perhaps he saw the soul of truth so clearly that he
could not accept any one of them as a complete and final
revelation of truth. Perhaps he so clearly realized that all
religious creeds and systems have their roots in human nature
that he could look upon the Christian system as the only deposit
of truth committed to the children of men. Perhaps his
conception of Deity was so vast that he could not see all the
Divine attributes manifest in the historic Christ. Perhaps he felt
that some of the doctrines of Christianity, as they were
formulated and preached in his day, would be a hindrance
rather than a help to his religious faith, so clear was his vision of
the things which are unseen and eternal, and so close was his
relation to the Author of his being. Perhaps he felt no need of a
daysman or mediator, because he himself knew the Lord face to
face."—Milton R. Scott: Lincoln, Was He an Inspired Prophet?,
pp. 55-57.

There is a measure of truth in this presentation of one side of the


case, but it is not the whole truth. Lincoln did not possess this
supposed clarity of vision of all spiritual truth. Some things he saw
clearly, but his faith and vision had each of them marked and
undeniable limitations.
In his widely popular and in many respects excellent oration on
Lincoln, Bishop Fowler said:

"Let us analyze Mr. Lincoln if we are able. This task is difficult on


account of his symmetry. He was so much like a sphere that he
projected farthest in every direction. His comprehension is to us
impossible on account of his immensity, for a man can be
comprehended only by his peers" (p. 28).

He found the same difficulty in estimating Grant. "It is difficult to


analyze General Grant, because he is so simple and complete. Like
Lincoln, he is like a sphere; approached from any side he seems to
project farthest toward you. Try to divide, and each section is like all
the rest. Cut him through, and he is all the way through alike" (p.
127).
I do not think that this is correct concerning Grant, and it certainly is
not true concerning Lincoln. He was not a sphere; he was angular or
he was nothing.[57] In endeavoring to assess his religious
convictions, we are liable to encounter contradictions. But there is a
certain inconsistent consistency in those contradictions. There are
certain kinds of contradictions which we do not encounter, and
certain which, encountering, may be interpreted in the light of
certain underlying agreements.
For instance, the Calvinism which he inherited and heard through his
childhood and which he accepted in a kind of semi-fatalistic
philosophy might seem the reverse of scientific. But the natural
science which Lincoln learned from Vestiges of Creation, while it
would have been repudiated by every Baptist preacher whom Lincoln
ever heard in his youth, was capable of being grafted upon that very
root.
I suggest one more limitation in the character of Abraham Lincoln,
which had its possible relation to his hypothetical church
membership. He was possessed in marked degree of the obstinacy
of irresolution. That genial good-nature of his had behind it
stubbornness, irony, and a sullen but mighty temper which rarely
broke the bounds of self-control, but sometimes manifested itself on
very slight provocation. Just when men thought they had discovered
in Abraham Lincoln a nose of wax which they could shape to their
own liking, they encountered in him a wholly unexpected element of
passive inertia and of active obstinacy. When he did not know what
to do, he would not do anything. It was this quality in him which
enabled him to rule a rampant Cabinet and which justified the
qualities set forth in such books as Major Putnam's Abraham Lincoln
the Leader, Richard Watson Gilder's Lincoln the Leader, and Alonzo
Rothschild's Lincoln, Master of Men. It was this which enabled
Herndon to write of him: "I know Abraham Lincoln better than he
knows himself.... You and I must keep the people right; God will
keep Lincoln right."
Those do greatly err who see in Lincoln only genial good humor and
teachableness; there was a point at which his good humor became
withering scorn or towering passion and his gentle and tractable
disposition became adamantine inertia. His successor, Andrew
Johnson, quoted as characterizing himself the lines from Sir Walter
Scott:

Come one, come all; this rock shall fly


From its firm base as soon as I."

Lincoln might with much more appropriateness have quoted it of


himself.
Mary Todd Lincoln united with the First Presbyterian Church of
Springfield on April 13, 1852, upon profession of her faith. The
church records contain no record of her dismissal, but only the word
"Deceased" without a date. She remained a member until her death,
though, after her return to Springfield in an unhappy state of mind,
she was not a very active one. The only other Lincoln record on the
books of this church is the baptism of Thomas Lincoln—"Tad," "son
of Abraham and Mary"—on April 4, 1855. The records of the
financial secretary, not very complete, show Abraham Lincoln to
have been a pew-holder from 1852 to 1861, and he departed for
Washington with his pew rent paid to the date of his departure. This
is all that is to be learned from the church records in Springfield.
Mary Todd Lincoln was a member in good and regular standing of
the Episcopal Church when she united with the Presbyterian, but she
united on profession of her faith. She affirmed that she did not
believe that she had ever previously been converted. This statement
is one of several indications that she, and with her her husband,
came into a new religious experience after the death of Willie in
Washington, as earlier he had been profoundly impressed after the
death of Eddie in Springfield.
We learn through sources outside the records, but wholly credible
sources, that her uniting with the Presbyterian Church was preceded
by a revival in the church, and she and her husband attended the
revival meetings regularly. Not only so, but many of Lincoln's
associates, including Major Stuart and other influential men of
Springfield, were present almost every night and were deeply
interested. The letter of Thomas Lewis, already cited, refers to the
general expectation that Lincoln would have united with the church
with his wife. A similar and wholly independent report comes to
us[58] from Lincoln's associates outside the church. They, also,
expected him to go in with his wife. But Lincoln was not fully
persuaded. The logic of Dr. Smith demolished all the arguments of
the infidels and did it over again:
"And thrice he vanquished all his foes,
And thrice he slew the slain."

But doubts, though logically answered, still rose in Lincoln's mind.


On the other hand, and more important, Lincoln did not find himself
able to accept the rigid Calvinism of the Presbyterian Church of that
day. The evangelist made strong appeals, and Lincoln was not
unmoved. But he said to his friends that "he couldn't quite see it."
Lincoln was a man of mighty courage when his convictions were
assured. But he was also a man of more than normal caution. He
could meet an issue which he was fully convinced was right with all
needful heroism. But he was capable of evading an issue about
which he was uncertain.
We know what Lincoln did just after his State Fair speech in
Springfield on October 3, 1854. He was roused "as never before," to
quote his own words, by the repeal of the Missouri Compromise, and
he came out in a four hours' speech following Douglas, and
committed himself unqualifiedly to the anti-Nebraska program. The
Abolitionists were overjoyed, and Lovejoy wanted him to address
that body that very night. Lincoln was in a quandary. To offend the
Abolitionists meant political death, for they were now strong and
growing stronger; but, on the other hand, to become an Abolitionist
meant political death also at that stage of the fight. Herndon, who
was himself an Abolitionist, and not much given to compromise, fully
realized that Lincoln was in grave political danger.[59] With Herndon's
approval, Lincoln took Bob in his buggy and drove off out into the
country till the crisis was over.[60]
We know something also, though probably not the whole truth,
about Lincoln's wavering indecision with respect to his marriage to
Mary Todd. Whether he ran away from his own wedding, as he ran
away from the offer of the leadership of the Abolition movement,
and if so, whether he was sane or insane at the time, are questions
which I prefer not, at this time, to undertake to answer. But that
incident may be cited as another reminder that Lincoln had times of
great mental uncertainty, and that at such times he sometimes did
unexpected things.
It is my firm conviction that, after the death of Eddie, Lincoln was
profoundly stirred in his own spiritual life; that the arguments of Dr.
Smith went far toward answering the arguments of Paine, Volney,
and his freethinking friends; that bereavement and spiritual comfort
had done their work of grace; that the desire for a home more truly
united in its religious relations and spiritual sympathies made a
strong appeal to him; and that the atmosphere of the revival
seemed to make it easy and natural for him to enter the church with
Mrs. Lincoln. But, though a Calvinist in his early training, he was not
ready to accept Calvinism as a complete and articulated system as
presented in the Westminster Confession and in the preaching of Dr.
Smith.
He wavered. Whether he left town to avoid pressure to attend the
meeting of the Session at which his wife made her application for
church membership, we do not know. It is not improbable. Certainly
if his absence had been unavoidable he could have joined at the
next opportunity. I think that he did not join because he was still in
some measure of intellectual uncertainty with reference to doctrinal
matters. I am only sorry that someone did not tell him that these
were no sufficient reasons for his declining to unite with the church.
It would be possible to carry this study further, but it is not
necessary. An explanation of Lincoln's failure to unite with a
Christian church in that time of bitter sectarianism when to have
joined one church would have made him a target for criticism from
others and when his mind was intent rather upon the application of
his Christian principles than the proclamation of his religious
opinions, is partly to be attributed to the faults of the churches; but
a portion of the explanation is to be found also in qualities inherent
in the life of Abraham Lincoln.
CHAPTER XXII
THE CONSTRUCTIVE ARGUMENT
We are ready now to undertake the difficult task of determining with
some approach to certainty the essential content and character of
Abraham Lincoln's religious belief.
We must not be surprised if we find ourselves unable to construct a
perfectly symmetrical and consistent confession of faith. The
material is much more abundant and explicit and much better
attested in some departments than in others. Not only so, but we
must never forget the mighty elements of contradiction in Lincoln's
personality.
Mediocre men have this in their favor, that it is relatively easy to
classify them. Not only may they be readily assigned to their several
occupations, and conveniently pigeon-holed as butchers, bakers, and
candlestick makers, but it is a comparatively simple task to group
them under single adjectives, as good and bad, black and white, tall
and short, fat and lean, old and young, intelligent and stupid. The
process is less easy with really great men. There is always an
admirable element of human inconsistency in men of large mold
which would be intolerable in lesser personalities. It has been truly
said that no man becomes really great and influential who is not a
good subject for caricature. The sublime is own sister to the
ridiculous. Genius is next akin to insanity. The men who do really
great things are a perpetual puzzle to those who possess only
commonplace standards of classification. A commonplace villain is a
villain, first, last, and all the time; but a villain like Milton's Satan,
Napoleon, or the late German Kaiser is so great a villain as to be half
a hero. The two hundred seventy-six dripping men who struggled
through the surf at Malta one stormy morning rather more than
eighteen hundred years ago and gathered shivering round the fire,
were quickly classified, for the most part, into four convenient
companies, of sailors, soldiers, passengers, and prisoners; but when
one of them shook off a viper into the fire and showed no sign of
hurt, it was quite certain that he was either a murderer or a god.
Opinions might differ and did differ as to which of the two extremes
might properly be claimed for him, but no one proposed to find a
place for him in middle ground.
The strength of great men lies in their possession and their
counterpoise of opposing qualities. Over against the monotonous
uniformity, the stupid consistency, of those common people whom
Lincoln said God must love because He made so many of them, this
quality displays itself as a peculiar possession of genius. Now and
then it is given to a great man sufficiently so to subordinate the
inconsistencies without which real greatness could not exist as to
incarnate some outstanding principle of which he becomes the
exponent. Abraham Lincoln did this; and the world, or that small
part of the world which can lay claim to any considerable measure of
moral discernment, has redefined its conception of certain high
qualities, its measure of the moral significance of certain notable
achievements, in terms of his personality. This process is highly
desirable as well as inevitable; but the elements of inconsistency are
not thereby removed from the character itself. Of him we might say:

"His life was gentle, and the elements


So mixed in him, that Nature might stand up,
And say to all the world: This was a man!"
—Julius Caesar, V, 5.

It has often been affirmed that "'Lincoln knew his Bible better than
any minister," and large claims have been made concerning his use
of it in public addresses. Mr. Lincoln did know and use the Bible, and
his style is saturated with it; but it would be easy to exaggerate both
his knowledge and use of it.
Prof. Daniel Kilham Dodge of the University of Illinois examined
twenty-five of Lincoln's extended and carefully prepared addresses
with this result:[61]
In five speeches from 1839 to 1852 he found six Biblical quotations,
of which four were in his temperance address.
In his reply to Douglas in 1852 there were two Biblical quotations,
both from the Old Testament.
In 1856 he found one, and that most notable of all—the "house
divided against itself."
In his "lost speech" at Bloomington, as recorded by Whitney, there
were six Biblical quotations, four from the Old Testament and two
from the New—the largest number in any single speech.
In his ten speeches in the Lincoln and Douglas debates there were
two Biblical references, besides a number of allusions to the "house
divided against itself."
There were no Biblical quotations in the Cooper Union address or in
the First Inaugural or in the Gettysburg address; none in the two
messages to Congress in 1861.
His Second Inaugural was itself a kind of leaf out of the books of the
prophets.
In the whole of the twenty-five speeches, there were found twenty-
two Biblical references, eight in the Old Testament and fourteen in
the New. This notwithstanding the impression of many who knew
him that Lincoln preferred the Old Testament to the New, as
recorded by Noah Brooks.
But this rather meager use of direct quotations and allusions need
not disappoint us. Nor does it militate against the essentially Biblical
substratum of his style. When we come to the study of Lincoln's
literary and oratorical method, we find more striking contradictions
and evolutions than we have here. Lincoln's oratory was not of the
same style at all periods of his career, nor were his methods uniform
at any one period.
He was a ready stump-speaker, yet he became so cautious while in
the White House that he was timid about responding even to a
serenade without having first written out his address, and on
occasion could appear rude in declining to utter even a simple word
of greeting and appreciation, as on the night before his address in
Gettysburg, when he was very abrupt to the company that
serenaded him.
He had been accustomed to large use of gesture, swinging his great
arms, and sometimes, even in the Douglas debates, bending his
knees till they almost touched the platform, and then rising suddenly
almost with a whoop, but he became very quiet and self-restrained
in his oratory.
He is alleged to have loved Burns more than any other poet, yet his
speeches have been searched in vain for a single quotation from
Burns. It is said that next to Burns he loved Byron, and he is not
known ever to have quoted Byron in any speech or paper. It is said
that his favorite Shakspeare play was Richard III., but his
Shakspeare quotations are from Hamlet, Lear, Macbeth, the
Merchant of Venice; and there is one allusion to Falstaff.
Besides Shakspeare, whom he quoted next to the Bible, his literary
allusions are to T. H. Bayley, Dickens, Robert Herrick, Pope and
Scott, and they are not numerous. The total number of his
quotations, as listed by Professor Dodge, including Shakspeare, but
not including the Bible, is thirty.
What is more surprising, Lincoln was known as a great story teller.
But his addresses contain hardly a single anecdote. He told stories in
jury trials and to illustrate points in conversation, but he rarely told
them in his addresses.[62]
No man who knew Lincoln intimately studied him so long, so
industriously, or, in spite of many limitations, so appreciatively, as
William H. Herndon. He was a profound believer in the mental and
spiritual evolution of Lincoln.
In 1887, while Herndon, after many years of interruption, began
again the preparation of his Life of Lincoln, he had an extended
correspondence, partly from Springfield, and partly from
Greencastle, Indiana, where Mr. Jesse W. Weik was at work with him
on his book, and with a Boston sculptor, Mr. Truman H. Bartlett, who
was planning a statue of Lincoln. Herndon's letters went more and
more into detail as the correspondence proceeded, and he gave in
some respects the very best affirmation of the development of
Lincoln on the higher side of his nature that Herndon wrote at any
time.
Herndon seemed to have some apprehension that a study of
photographs and life-masks and other evidences of the physical
appearance of Lincoln would not reveal the man himself. He said
that a person studying his physical nature would say "that his
physical nature was low, coarse, and not high and fine." Before he
sent this letter he re-read it, and inserted the word "comparatively"
before "low." Mr. Bartlett asked him further about this, and Herndon
went into detail as to Lincoln's body. "His blood ran slowly. He was of
a low or slow mechanical power, within him. I did not intend to say
that Lincoln's organization was a low, animal organization. What I
meant to say was that it was a slow-working machine. Lincoln's flesh
was coarse, pimply, dry, hard, harsh; color of his flesh saffron
brown; no blood seemingly in it; flesh wrinkled."
Mr. Bartlett apparently inquired whether the abnormal qualities of
frontier life produced these effects, and whether Herndon had
known other men of the Lincoln type. Apparently he alluded to the
presence of malaria and the large use of pork in frontier diet.
Herndon did not accept the pork and malaria theories. He said that
all such theories must give way to facts, and he dealt with facts. The
men of the frontier had the best meat in the world, "venison, bear,
turkey, and of course some hog."
"You ask me if I ever saw in this great wild west many men of
Lincoln's type, and to which I answer, Yes. The first settlers of
central and southern Illinois were men of that type. They came
from the limestone regions of Virginia, Kentucky, and
Tennessee, and were men of giant strength, physical force, and
by nature mentally strong. They were original, were
individualists. The strong alone from 1818 to 1830 could get
here, and the strong alone could survive here.... No one was
like Lincoln, and yet many were of his type.... He was, as you
say, 'a man of extraordinary contrasts.' You would not look for a
well-rounded man in such a description."

Lincoln was, then, as Herndon saw him, and as the world must see
him, a legitimate product of his environment. Herndon had read
Buckle and Spencer and Darwin, and was a thoroughgoing believer
in evolution, as was Lincoln, from a far narrower reading, but a very
thoughtful study of Vestiges of Creation.
Physically, Lincoln was akin to the strong pioneers of early Illinois,
and it was not difficult to find each several trait of Lincoln
reduplicated in many of them. But Lincoln himself was never
duplicated. He was a product of his environment, but he was also an
evolution which in terms of an individual personality went beyond
environment, and was still going forward when death came to him.
This evolution of Lincoln, the spiritual Lincoln, as portrayed in these
letters to a sculptor, who must not be permitted to forget, if he was
in danger of forgetting, that the real man Lincoln had in him more
than his bodily measurements could portray, is one of the most
suggestive studies disclosed by Herndon, and it is sound, both as
approached from the standpoint of science, and as considered in the
personal study of Lincoln in his growth from year to year.
Like St. Paul, Lincoln had a warfare in his members. He was an
embodiment of forces mutually antagonistic. He would not have
been the man he was had either of them been lacking, and the
growth of either at the total expense of the other would have given
us a man abnormal, which Mr. Lincoln came perilously near to being.
But his real development was mental and spiritual.
In another place St. Paul says that "The first man is of the earth,
earthy, and the second man is from heaven." It has been assumed
without due warrant that what he had in mind was a contrast
between Adam and Christ, and this view is strengthened by the
intrusion of the words "the Lord" in the authorized English text. But
it is quite possible that St. Paul, even if Adam and Christ were a part
of his contrast, had really in mind the evolution of any man's life; he
being himself in his bodily nature the first man and in the birth and
growth of his higher nature the second and contrasting man. "First is
that which is natural, and after, that which is spiritual."
This was Herndon's thought of Lincoln, as disclosed in these letters,
[63] and it is true of Lincoln. Lincoln was more than an embodiment
of contrasts; the solar system is that, and it is more. In the solar
system the opposing forces do not neutralize each other, but
together hold the earth and planets in their orbits. So it was with
Lincoln. But with him the higher and nobler forces became
increasingly dominant.
Herndon resented it when anyone said that Lincoln had died at the
right time. He believed that, great as Lincoln was, his nobler
qualities had not yet come to their full maturity, and that a longer-
lived Lincoln would have been an even nobler Lincoln. Here are
some of the things he says of him in these letters:

"I said to you once that Mr. Lincoln had not arrived at maturity
in 1865, and I say so now. His blood ran slowly—had low or
slow circulation and consequently a slow build-up. As he had a
slow build-up, so he had a slow development; he grew up like
the forest oak, tough, solid, knotty, gnarled, standing out with
power against the storm, and almost defying the lightning.
Hence I conclude that he had not arrived at his highest
development in 1865.... The convolutions of his brain were long;
they did not snap off quickly like a short, thick man's brain....
The enduring power of Mr. Lincoln's thought and brain was
wonderful. He could sit and think without food or rest longer
than any man I ever saw."

He goes into detail concerning Mr. Lincoln's bodily lethargy and its
effect on body and mind, the sluggishness of all his functions, and
affirms that this must be taken into account in any right estimate of
the man; but that steadily, and the more surely because slowly, his
mind and soul developed and became more and more dominant.

"His flesh looked dry and leathery, tough and everlasting; his
eyes were small and gray; head small and forehead receding;
but when this great man was moved by some great and good
feeling, by some idea of Liberty, or Justice, or Right, then he
seemed an inspired man. It was just then that Lincoln's nature
was beautiful, and in complete harmony with the laws of the
Great Eternal. I have seen him in this inspired condition, and
thought he was molded in the Spirit's best mold. Lincoln was a
great man, a good man, and a pure man; and beneath his
rough bodily exterior, Nature wove her fine network of nerve....
Lincoln was a gloomy man at one moment and a joyous man
the next; he was conscious that a terrible fate awaited him. He
said to me, 'I cannot help but believe that I shall meet with
some terrible end.' This idea seized him and made him gloomy.
At times his better nature would get the mastery of him, and he
would be happy till the shadow of his fate flitted before him. In
philosophy Lincoln was a fatalist.... In my poor opinion, Lincoln
had not arrived, when he was assassinated, at the meridian of
his intellectual power.... Were you to read his early speeches
thoroughly you would see his then coarse nature. He gradually
rose up, more spiritualistic. This is one of the reasons why I say
that Lincoln was not fully developed in mind at the last. When a
great Boston man said, 'Lincoln died at the right time,' he did
not know what he was talking about."
In these and like paragraphs Herndon testified to the mental and
spiritual evolution of Lincoln; and he was probably correct when he
opined that that evolution was still in process, and that Lincoln was,
up to the very hour of his death, a growing man in all that meant
most to America and the world.
The religion of Abraham Lincoln was part and parcel of his life; and
his life was an evolution whose successive stages can be measured
with reasonable certainty. Not only did his religious convictions
develop and broaden under the stimuli of Lincoln's constantly
broadening intellectual and spiritual environment, but they
broadened in the growth of his own personality.
There was an evolution in his apprehension of the ethical
implications of public office. The Lincoln who re-entered politics after
the repeal of the Missouri Compromise was a changed man from the
Lincoln who, with the other members of the "Long Nine," earned by
political log-rolling the severe but not wholly unmerited name
applied to them by one of Illinois' best governors, "spared
monuments of popular wrath." That Lincoln did not in this earlier
period commit any personally dishonorable act is not an argument
against the theory here advocated. He had, in his later political
career, a far higher ideal of political honor, a greatly nobler
conception of the dignity of public office—which he always sought—
as a field of popular service. His political career was an evolution,
and it developed nobler characteristics than that which characterized
his earlier political life.
Lincoln's emancipation policy was an evolution. The successive
stages of that policy were worthily set forth by Paul Selby in an
address before the Historical Society of Chicago.[64] There never was
a time when Abraham Lincoln did not believe slavery to be wrong,
but there was a time when he was not an Abolitionist. The moral
aspect of the slavery question grew in his mind and conscience till
he promised his God to free the slaves.
On Sunday evening, September 7, 1862, a public meeting was held
in Bryan Hall, Chicago, to urge upon the President the desire of
Christian people that he should free the slaves. A petition was
circulated, and was signed by all the Congregational and nearly all
the Methodist and Baptist ministers of that city, courteously
requesting the President to give the matter his earnest attention.
The petition was sent to Washington by the hand of Rev. William W.
Patton and Rev. John Dempster, who met the President by
appointment on Saturday afternoon, September 13, the interview
being arranged by Hon. Gideon Welles.
The story of that meeting has often been told in part, with undue
emphasis upon Mr. Lincoln's statement then made that if God had a
message for him on this subject He would be more likely to
communicate it directly to Mr. Lincoln than to others for him. The
latest book to misuse this incident is one just from the press in Great
Britain, the Short Life of Lincoln, by Hon. Ralph Shirley, who says:

"Some of the ministers in this deputation even went so far as to


assure him that they had authority in God's name to command
him to emancipate the slaves."

Inasmuch as there were but two of the ministers, and neither of


them assumed any such authority to speak the mind of God, such
statements ought to cease, especially as the true story, from which
all these accounts are garbled, is available for inspection in the files
of the Maryland Historical Society.
Mr. Lincoln did say to them that he hoped it would not appear
irreverent in him to say that if God were to reveal this duty of his to
others, it was probable that He would reveal it also directly to Mr.
Lincoln. At the beginning of the interview he was guarded; but as he
found common ground with his visitors, he threw first one leg and
then the other over the arm of his chair, and talked to them with the
utmost freedom, and asked them concerning the opinion of ministers
and churches, and assured them that he desired to know the will of
God, and whatever seemed to him to be God's will he would do.
The next week occurred the battle of Antietam, and on Saturday,
September 20, exactly a week after his interview with the Chicago
ministers, Mr. Lincoln called the Cabinet together and read to them
the Emancipation Proclamation, which was signed and published on
the following Monday. We know now that Lincoln had promised God
that if that battle resulted in the success of the Union cause he
would issue the proclamation. We also know that the meeting with
the Chicago ministers was very timely, and gave him an added
assurance of moral support from the churches, if not added
confidence in the help of God.
Some time after, Joseph Medill, editor of the Chicago Tribune,
returning from Washington, said, "Secretary Stanton told me to say
to those Chicago clergymen who waited on the President about the
Proclamation of Emancipation, that their interview finished the
business. After that there was no manifestation of doubt or talk of
delay. Mr. Lincoln's mind was fully made up."—Proceedings of the
Maryland Historical Society, Baltimore, 1888.
Lincoln's literary style was an evolution.[65] His spread-eagle stump-
speeches, with their florid rhetoric and grandiloquent figures of
speech evolved into the calm, dignified, and forceful English of his
maturer years.[66] An able monograph in which this evolution is
traced is cited elsewhere in this volume.[67] That change of style
was the outward and visible sign of an inward and spiritual as well
as intellectual grace.
In like manner Lincoln's religion was an evolution, both in its
intellectual and its spiritual qualities. Up to the time of his residence
in New Salem he had heard only the dogmatic sectarianism of
unlettered preachers, proclaiming a creed which furnished him
certain lifelong tenets but which as a whole he could not accept. At
New Salem he read the negative arguments which confuted the
dogmas he had heard, and perhaps unwittingly made room for a
more intelligent faith.
He was deeply impressed by the argument of Dr. Smith in his The
Christian's Defence. It was the first time he had heard the Christian
apologetic rationally presented, and it made a lasting impression
upon him without, however, fully satisfying him. He was, however, a
much more religious man when he left Springfield than he was when
he came to it, whether he knew it or not.
The solemn responsibilities of his office, the daily contemplation of
death as it menaced him and came into the homes of the people of
his country, the profound conviction that God was working His
infinite purpose through the war, and through the human agency of
Lincoln himself, took hold of the deepest impulses of his nature, and
became the controlling forces of his policy.
Lincoln was no theologian, but I do not find any authority for the
statement of Mr. Binns that Lincoln said, "the more a man knew of
theology, the farther he got away from the Spirit of Christ." It is
possible, of course, for a man to learn theology as an intellectual
system and to have little religion as a spiritual experience, and to
lose that little in the process of his logical subtleties: but Lincoln was
too just a man to make so sweeping and unjust an affirmation of
something of which he would certainly have admitted he knew very
little.
The rock-bottom foundation of Abraham Lincoln's religious faith was
the ultra-Calvinism of his boyhood. He was reared a Predestinarian
Baptist; and while he never became a Baptist he never ceased to be
a Predestinarian. To this he added a strong rationalistic tendency,
inherent in his nature, and strengthened by his study of Paine and
Volney. This also he never wholly outgrew. As a lawyer who was not
well read, pleading before juries that cared little for the letter of the
law, he was accustomed to reduce his cases to simple principles of
elementary justice, and to rest all upon these principles. This habit
of thought and practice he applied also to his theology. His early
recollection of the epitaph of Johnny Kongapod was nothing less
than the application of the Golden Rule to theology—the assurance
of an eternal justice throned in heaven and intelligible on earth.
Thus, when he argued in favor of universal salvation he did it upon
the basis of the old Calvinistic theology with which he had been
familiar all his life. If God was, indeed, absolute sovereign, and as
good as He was great, and willed not that any should perish, then
no one could finally perish. Universal salvation became logically and
ethically compulsory. The Christ who tasted death for every man, did
so as the necessary means to the efficiency of a plan of salvation
whereby the curse of the fall was fully offset by the sacrifice of
Christ, at the instance of the sovereign will of God. As in Adam all
died, even so in Christ were all made alive. His theory of universal
salvation was the logical expression of his determinism, influenced
by his rationalism and confirmed by his appeal to a justice that
would not accept a fall more universal than the atonement of Christ.
This was not because Lincoln approached the theme from the
direction of the grace of Christ, but of the irresistibility of a divine
decree. He profoundly believed himself an instrument of the divine
will, believing that will to be right, and creation's final law.
If it were asked, where in such a system as his he found a place for
the forgiveness of sins, the answer would be first that he had no
system, and secondly that he found no place for the doctrine; but it
would then be necessary to add that he found the doctrine,
nevertheless. He had no system. He thought without logical method.
But his thinking was in right lines. He followed simple paths, "blazed"
through technicalities and in quite thorough disregard of them. As
his office desk was in confusion, and he kept a package marked,
"When you don't find it anywhere else, look here," so he had in his
thinking a parcel of unassorted first principles to which he recurred
when he needed them. Forgiveness and law were to him two
unreconciled postulates; but law he had to assume, even though he
denied forgiveness. But if he did not admit belief in forgiveness, he
did believe in mercy, for he himself was merciful, and he believed
that he would be merciful to God if he were God and God were man.
Stanton could argue him down as to the necessity for shooting a
soldier who slept on duty, but Lincoln injected an intuitive, and from
Stanton's point of view, an unreasonable and a certainly
unarticulated, element of mercy that forbade the killing of this
particular boy.
His theory of governmental forgiveness was as irreconcilable with his
theory of military discipline as his theory of divine mercy was with
his system of inexorable law. He did not harmonize the
contradictions: he was merciful, and let his system take the
consequences, and he believed in a divine mercy while holding a
theory with which the exercise of mercy was irreconcilable.
To such a mind as that of Abraham Lincoln, it was not necessary to
prove the fact of immortality. If God possessed immortality and
intended it for man, then God would make His decree effective in
man. Adam's fall could not hopelessly lose to man what God
designed; and, whether he accepted for himself or not the theory of
the fall and of redemption, he accepted both in meeting an
argument which by reason of the fall could have deprived man of his
birthright of immortality. He believed in the immortality of the soul.
Did he harmonize that doctrine with the rest of his creed? Probably
not. He was no theologian, in the strict and formal sense, no
logician. He reasoned on the basis of very simple and elementary
principles, whose lines of direction were determined by the early
Calvinistic preaching to which he listened, the rationalistic method
which he learned from Paine, and his simple sense of justice and
right.
His was not wholly an optimistic faith. He knew that man was sinful
and sad and that "the spirit of mortal" had little occasion for pride;
but he believed in an eternal justice and an unconquerable
goodness, regnant above the perplexities and contradictions of this
life, and triumphant in the life everlasting.
Abraham Lincoln believed in God. Save in his moments of deepest
gloom when everything turned black, he appears never seriously to
have questioned this fundamental article of belief. It is not easy to
see how he could have done so. His idea of causation forbade it,
and, what was more, his profound supernaturalism affirmed it as
incontrovertible. This element of supernaturalism went the full
length of orthodox preaching, as Lincoln heard it and accepted it. It
was in accord with the teachings both of the Baptists, whom he
heard in Indiana and rural Illinois, and the Presbyterians, to whom
he listened in Springfield and in Washington. In a great God, a
mighty Creator, a Sovereign Ruler, he was taught to believe by all
the forms of Calvinism to which throughout his life he listened, and it
was in full essential accord with his own native tendency. His
supernaturalism was not only ultra-orthodox; it went the full length
of current superstition. The frontiersman of that day had superstition
wrought into him by the vastness of the wilderness, the solemnity of
the immeasurable forest and plain, and the insignificance of man;
the haunting tales of savagery and witchcraft; the presence in every
frontier community of some person supposed to be possessed of
second sight or other supernatural qualities. The rationalism of his
mature years modified but did not in any degree eradicate his
supernaturalism.
It must be remembered that Paine and Volney, whose works he
read, were far from being atheists. Thomas Paine, whatever he
denied, believed as strongly as Peter Cartwright or James Smith in a
personal God. So far as we know, Lincoln was never under any
strong influence that might have made him an atheist, his doubts
and questionings were all within the sphere of an expressed or
implicit theism.
The names by which Lincoln referred to God are many and
suggestive. The following is a partial list:[68]
Almighty, Almighty Architect, Almighty Arm, Almighty Father,
Almighty God, Almighty Hand, Almighty Power, Almighty Ruler of
Nations, Creator, Disposer, Divine Author, Divine Being, Divine
Majesty, Divine Providence, Divine Will, Eternal God, Father, Father in
Heaven, Father of Mercies, God, God Almighty, God of Battles, God
of Hosts, God of Nations, Governor, Heavenly Father, Higher Being,
Higher Power, Holy Spirit, Judge, Lord, Maker, Maker of the Universe,
Master, Most High, Most High God, Omniscient Mind, Power,
Providence, Ruler of the Universe, Supreme Being.
Lincoln believed in the Bible. I am not sure that he accepted the
whole content of the positive arguments set forth so cogently by his
pastor, Dr. Smith. When he called this argument "unanswerable," it
need not imply that his every doubt was satisfied, his every
misgiving reassured. It is entirely possible that there lingered in his
mind some vestiges of what he had read in writers opposed to the
doctrine of the inspiration of the Scriptures as it was then taught;
indeed, that doctrine in the form in which it was currently stated was
not one by which a modern man's orthodoxy ought to be tested. But
he read the Bible, honored it, quoted it freely, and it became so
much a part of him as visibly and permanently to give shape to his
literary style and to his habits of thought. When Mrs. Speed
presented him an Oxford Bible in 1841, he declared his intention to
read it regularly, believing it to be "the best cure for the blues"; and
he kept and loved and constantly used his mother's Bible. How he
would have defined his theory of its transmission and of the relation
of its divine and human elements we do not know, and we need not
be too curious to inquire. It is more than possible that Mr. Lincoln
never made this definition in his own mind. His attitude toward the
Bible was a thoroughly practical one. We do not know that he ever
heard Coleridge's pragmatic affirmation, but we have every reason
to believe that he would have accepted it, namely, that he valued
the Bible because "it finds me as no other book."
Concerning his opinion of Jesus Christ our material for constructive
hypothesis is exceedingly scanty.[69] Herndon says he does not
believe the name of Jesus can be found in any of Lincoln's authentic
writings. I have found it in his writings but I must confess that I
have not found it frequently in any which I count to be certainly
genuine.[70] There are, however, a number of references to Jesus
Christ in his writings and published addresses, and they are both
positive and reverent.
On July 4, 1864, the colored people of Baltimore presented him a
beautiful copy of the Bible of the usual pulpit size, bound in violet-
colored velvet. The corners were bands of solid gold and there was a
thick plate of gold upon the cover, bearing this inscription:
"To Abraham Lincoln, President of the United States, the friend
of universal freedom. From the loyal colored people of
Baltimore, as a token of respect and gratitude. Baltimore, July 4,
1864."

In accepting this gift, which was presented in person by a committee


of five, the President said:

"In regard to this great book, I have only to say it is the best
gift which God has ever given man. All the good from the
Saviour of the world is communicated to us through this
book."—Carpenter: Six Months in the White House, p. 199; also
Nicolay and Hay: Works of Lincoln, twelve volume edition, X,
217-18.

Such references as this show to us the instinctive place which he


accorded Jesus Christ in his own unpremeditated thinking. This was
the best thing he had to say about the Bible, that through it alone
we have knowledge of the Saviour of the world.
Herndon tells us that Lincoln ridiculed the doctrine of the virgin birth
of Jesus. If this is true, I am very sorry. But Abraham Lincoln's faith
in Christ did not depend wholly or even primarily upon his
interpretation of the mystery of our Lord's birth. I approach a
discussion of this question with some hesitation, for it is one which,
as related to Lincoln we do not know very much about, but it is a
subject which we are not free to pass over in silence.
It is a sad fact that the argument for the divinity of our Lord Jesus
Christ should ever have been based on the mystery of his birth. Not
thus does the New Testament establish the doctrine of his divinity.
The wonderful story of the birth of Jesus is told in two places only,—
in the introduction to the two Gospels of Matthew and Luke, and
these are the very two that contain genealogies tracing his descent
through Joseph. The theory that one of these gives the family tree
of Mary is unsupported by any evidence. So far as we know, Jesus
never referred to the mystery of his birth, or attached any
importance to it. His two brothers, James and Jude, each wrote a
book which we have in the New Testament, and there is no
reference in either of them to this doctrine. Peter preached his
mighty sermons at Pentecost and afterwards, proclaiming the faith
on which the Church was established, and he grounded his
argument for the divinity of Jesus not upon his birth, but upon his
resurrection from the dead. Paul preached the gospel of Christ
throughout the Roman world, and neither in any recorded sermon
nor in any letter did he make any reference to that dogma. Mark,
earliest of the gospels, and for we know not how long a period the
only one, is silent as to the birth of Jesus; and John, the most
definitely spiritual of them all, begins and concludes his profound
philosophy of the person of Christ without a word concerning the
manner of his birth.
It is, therefore, a wholly unwarranted dogmatism which grounds the
divinity of Jesus in a question of the domestic relations of Joseph
and Mary. Jesus Christ is to be accepted for what He was and is, not
for some opinion as to how He became what He was.
We do not know whether Abraham Lincoln ever considered the
question of the birth of Christ in any personal thought he may have
had concerning his own birth. We may not forget, however, that if
Herndon is right, Lincoln lived and died without knowing all the facts
about his own mother which later research has made certain. The
marriage certificate of his parents was recorded in another county
than that in which he supposed it would have been recorded, and he
appears never to have been certain that he himself was begotten in
lawful wedlock. We know that Nancy Hanks and Thomas Lincoln
were married a year before the birth of their eldest daughter, who
was older than Abraham Lincoln, but he is believed not to have
known that.
What then? Should a man in 1860 or 1864 refuse to vote for
Abraham Lincoln because he did not feel certain when or whether
his parents were married?
The man who said, "I believe in Abraham Lincoln," did not
commonly have in mind any question of his parentage, but believed
in his integrity, his patriotism, his moral leadership. Even so the man
who believes in Jesus Christ may believe in Him without ever asking,
much less ever answering, any dubitable question in metaphysics.
Scant as are the references to Jesus in the authentic utterances of
Abraham Lincoln, they do not seem to me unimportant. They testify
to a faith that was valid as far as it went. They manifest a spirit
which is fundamentally Christian.
Unable to define his own views in terms that would have been
acceptable to those who believed themselves the rightful guardians
of orthodoxy in his day, it is not surprising that Lincoln was guarded
in his references to a dogma which might have involved him in
greater difficulties than he was prepared to meet. It was true in that
day unhappily as it was in the days of Paul, "Some indeed preach
Christ even of envy and strife; and some also of good-will." It is
occasion for profound sorrow that Christ has been so preached as
that men have sometimes found it difficult to confess their faith in
Him without provoking strife and envy.
That Lincoln was unwilling to make his doubt the occasion of
dogmatic negation is evident from one or more of the acquaintances
of Lincoln, whom Herndon interviewed in an effort to adduce
testimony against his faith, and whom Lamon quoted in that part of
his book in which he made his attack upon the religion of Lincoln.
The following from I. W. Keys, the man who loaned to him Vestiges
of Creation, is interesting in itself and especially interesting in its
relation to the group of testimonies which these two men
assembled:

"In my intercourse with Mr. Lincoln, I learned that he believed in


a Creator of all things, who had neither beginning nor end, and,
possessing all power and wisdom, established a principle, in
obedience to which worlds move, and are upheld, and animal
and vegetable life come into existence. A reason he gave for his
belief was that, in view of the order and harmony of all nature
which we behold, it would have been created and arranged by
some great thinking power. As to the Christian theory, that
Christ is God, or equal to the Creator, he said that it had better
be taken for granted; for, by the test of reason, we might
become infidels on that subject, for evidence of Christ's divinity
came to us in a somewhat doubtful shape; but that the system
of Christianity was an ingenious one at least, and perhaps was
calculated to do good."—Lamon: Life of Lincoln, p. 490.

Emphatic proof of Mr. Lincoln's faith is to be found in the positive


declaration of the two men who have done most to destroy the
world's confidence in it, Lamon and Herndon. In Lamon's later book
of Reminiscences, he did much to counteract the harsh and to my
mind incorrect impression given in his earlier book. But even in that
book he affirmed that while Lincoln rejected the New Testament as a
book of divine authority, he accepted its precepts as binding upon
him and was a believer in the supernatural even to credulity (p. 503,
504).
In that same work Herndon set forth that Lincoln was a firm believer
in God and attempted, as he said, "to put at rest forever the charge
that Mr. Lincoln was an atheist." He declared, however, that Lincoln
did not believe in a special creation, but in an "evolution under law";
not in special revelation, "but in miracles under law"; and that "all
things both matter and mind were governed by laws universal,
absolute, and eternal" (p. 494).
To this Herndon gives even more emphatic testimony in his own
book. It must then be remembered that while in the loose
nomenclature of these authors Mr. Lincoln was an "infidel" it is these
same authors that assure us, as Lamon does, that "his theological
opinions were substantially those expounded by Theodore Parker."—
Lamon: Life of Lincoln, p. 486.
The question whether Lincoln's views underwent any substantial
change after leaving Springfield, has been answered in the negative
by John G. Nicolay, his private secretary at the White House; who
affirmed that "Mr. Lincoln did not, to my knowledge, in any way
change his religious views, opinions, or beliefs, from the time he left
Springfield to the day of his death."
This probably is correct. Mr. Lincoln was not conscious of any radical
change; but Mrs. Lincoln noticed a change in him after Willie's
death, which grew more pronounced after his visit to Gettysburg,
and his own faith, while undergoing no sudden and radical
transformation, manifests a consistent evolution.
But we are not sure how much Mr. Nicolay believed Lincoln's views
to have been in need of change. He said in another place:

"Benevolence and forgiveness were the very basis of his


character. His nature was deeply religious, but he belonged to
no denomination; he had faith in the eternal justice and
boundless mercy of Providence, and made the Golden Rule of
Christ his practical creed."—John G. Nicolay, in article "Abraham
Lincoln" in Encyclopedia Britannica, ninth edition, XIV, 662.

Lincoln believed in divine destiny. He could hardly have believed


otherwise. The preaching to which he listened was such as to make
it all but impossible for him to hold any other views. He believed so
strongly that his own life was under divine guidance that Lamon and
Herndon speak of it in a thinly veiled scorn as though it were in
Lincoln's mind a mark of conscious superiority. Whether it was such
a mark or not does not now concern us. Lincoln believed in divine
guidance. He had faith in prayer and his practice of prayer is
attested by many and credible witnesses. A man of his temperament
and training and sense of responsibility could not well have been
kept from praying. Prayer was a necessary part of his life.
Lincoln not only had faith in prayer considered as a means of
obtaining results from God; he believed in it as establishing a
relation with God, a covenant relation, such as Abraham of old
established. If such a faith seems inconsistent with any other
elements in the faith or doubt of Abraham Lincoln, then the
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookgate.com

You might also like