0% found this document useful (0 votes)
44 views45 pages

Beej S Guide To C Programming Brian Beej Jorgensen Hall PDF Download

Beej's Guide to C Programming by Brian Beej Jorgensen Hall is a comprehensive resource for learning C programming, covering topics from basic syntax to advanced concepts like pointers and functions. The document includes detailed sections on variables, flow control, and compilation details, making it suitable for both beginners and experienced programmers. It also provides links to download the book and additional resources related to programming and other subjects.

Uploaded by

zakiulduban
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views45 pages

Beej S Guide To C Programming Brian Beej Jorgensen Hall PDF Download

Beej's Guide to C Programming by Brian Beej Jorgensen Hall is a comprehensive resource for learning C programming, covering topics from basic syntax to advanced concepts like pointers and functions. The document includes detailed sections on variables, flow control, and compilation details, making it suitable for both beginners and experienced programmers. It also provides links to download the book and additional resources related to programming and other subjects.

Uploaded by

zakiulduban
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Beej s Guide to C Programming Brian Beej

Jorgensen Hall download

https://ebookmeta.com/product/beej-s-guide-to-c-programming-
brian-beej-jorgensen-hall-2/

Download more ebook from https://ebookmeta.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookmeta.com
to discover even more!

Beej s Guide to C Programming Brian Beej Jorgensen Hall

https://ebookmeta.com/product/beej-s-guide-to-c-programming-
brian-beej-jorgensen-hall-5/

Beej s Guide to C Programming Brian Beej Jorgensen Hall

https://ebookmeta.com/product/beej-s-guide-to-c-programming-
brian-beej-jorgensen-hall-6/

Beej s Guide to C Programming Brian Beej Jorgensen Hall

https://ebookmeta.com/product/beej-s-guide-to-c-programming-
brian-beej-jorgensen-hall/

Summary of a Mind of Your Own by Kelly Brogan with


Kristin Loberg Instaread

https://ebookmeta.com/product/summary-of-a-mind-of-your-own-by-
kelly-brogan-with-kristin-loberg-instaread/
Human Relations: Strategies for Success Lowell
Lamberton

https://ebookmeta.com/product/human-relations-strategies-for-
success-lowell-lamberton/

DK Eyewitness Top 10 Greek Islands Pocket Travel Guide


Dk Eyewitness

https://ebookmeta.com/product/dk-eyewitness-top-10-greek-islands-
pocket-travel-guide-dk-eyewitness/

The Ethics Of Social Punishment: The Enforcement Of


Morality In Everyday Life 1st Edition Linda Radzik

https://ebookmeta.com/product/the-ethics-of-social-punishment-
the-enforcement-of-morality-in-everyday-life-1st-edition-linda-
radzik/

The Boss s Secret Bossy Billionaires 1 1st Edition


Layla Valentine Ana Sparks

https://ebookmeta.com/product/the-boss-s-secret-bossy-
billionaires-1-1st-edition-layla-valentine-ana-sparks/

Food Microbiology Laboratory for the Food Science


Student: A Practical Approach 2nd Edition Cangliang
Shen

https://ebookmeta.com/product/food-microbiology-laboratory-for-
the-food-science-student-a-practical-approach-2nd-edition-
cangliang-shen/
Managing Infodemics in the 21st Century: Addressing New
Public Health Challenges in the Information Ecosystem
Tina D. Purnat

https://ebookmeta.com/product/managing-infodemics-in-the-21st-
century-addressing-new-public-health-challenges-in-the-
information-ecosystem-tina-d-purnat/
Beej’s Guide to C Programming

Brian “Beej Jorgensen” Hall

v0.9.13, Copyright © March 29, 2023


Contents

1 Foreword 1
1.1 Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.2 How to Read This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.3 Platform and Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.4 Official Homepage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.5 Email Policy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.6 Mirroring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.7 Note for Translators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.8 Copyright and Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.9 Dedication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

2 Hello, World! 5
2.1 What to Expect from C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Hello, World! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 Compilation Details . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.4 Building with gcc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.5 Building with clang . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.6 Building from IDEs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.7 C Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

3 Variables and Statements 11


3.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.1.1 Variable Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.1.2 Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.1.3 Boolean Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.2 Operators and Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.2.1 Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.2.2 Ternary Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
3.2.3 Pre-and-Post Increment-and-Decrement . . . . . . . . . . . . . . . . . . . . . . 15
3.2.4 The Comma Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.2.5 Conditional Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.2.6 Boolean Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.2.7 The sizeof Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.3 Flow Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.3.1 The if-else statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.3.2 The while statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.3.3 The do-while statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.3.4 The for statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.3.5 The switch Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

4 Functions 25
4.1 Passing by Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.2 Function Prototypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
4.3 Empty Parameter Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28

ii
CONTENTS iii

5 Pointers—Cower In Fear! 29
5.1 Memory and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
5.2 Pointer Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.3 Dereferencing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
5.4 Passing Pointers as Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.5 The NULL Pointer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
5.6 A Note on Declaring Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.7 sizeof and Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

6 Arrays 37
6.1 Easy Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
6.2 Getting the Length of an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
6.3 Array Initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
6.4 Out of Bounds! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
6.5 Multidimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
6.6 Arrays and Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
6.6.1 Getting a Pointer to an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
6.6.2 Passing Single Dimensional Arrays to Functions . . . . . . . . . . . . . . . . . . 42
6.6.3 Changing Arrays in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
6.6.4 Passing Multidimensional Arrays to Functions . . . . . . . . . . . . . . . . . . . . 44

7 Strings 47
7.1 String Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
7.2 String Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
7.3 String Variables as Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
7.4 String Initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
7.5 Getting String Length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
7.6 String Termination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
7.7 Copying a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

8 Structs 53
8.1 Declaring a Struct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
8.2 Struct Initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
8.3 Passing Structs to Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
8.4 The Arrow Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
8.5 Copying and Returning structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
8.6 Comparing structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

9 File Input/Output 57
9.1 The FILE* Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
9.2 Reading Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
9.3 End of File: EOF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
9.3.1 Reading a Line at a Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
9.4 Formatted Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
9.5 Writing Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
9.6 Binary File I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
9.6.1 struct and Number Caveats . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

10 typedef: Making New Types 65


10.1 typedef in Theory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
10.1.1 Scoping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
10.2 typedef in Practice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
10.2.1 typedef and structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
10.2.2 typedef and Other Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
10.2.3 typedef and Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
iv CONTENTS

10.2.4 typedef and Capitalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67


10.3 Arrays and typedef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

11 Pointers II: Arithmetic 69


11.1 Pointer Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
11.1.1 Adding to Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
11.1.2 Changing Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
11.1.3 Subtracting Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
11.2 Array/Pointer Equivalence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
11.2.1 Array/Pointer Equivalence in Function Calls . . . . . . . . . . . . . . . . . . . . 73
11.3 void Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

12 Manual Memory Allocation 79


12.1 Allocating and Deallocating, malloc() and free() . . . . . . . . . . . . . . . . . . . 79
12.2 Error Checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
12.3 Allocating Space for an Array . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
12.4 An Alternative: calloc() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
12.5 Changing Allocated Size with realloc() . . . . . . . . . . . . . . . . . . . . . . . . 82
12.5.1 Reading in Lines of Arbitrary Length . . . . . . . . . . . . . . . . . . . . . . . 83
12.5.2 realloc() with NULL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
12.6 Aligned Allocations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

13 Scope 89
13.1 Block Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
13.1.1 Where To Define Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
13.1.2 Variable Hiding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
13.2 File Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
13.3 for-loop Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
13.4 A Note on Function Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

14 Types II: Way More Types! 93


14.1 Signed and Unsigned Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
14.2 Character Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
14.3 More Integer Types: short, long, long long . . . . . . . . . . . . . . . . . . . . . . 95
14.4 More Float: double and long double . . . . . . . . . . . . . . . . . . . . . . . . . . 97
14.4.1 How Many Decimal Digits? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
14.4.2 Converting to Decimal and Back . . . . . . . . . . . . . . . . . . . . . . . . . . 100
14.5 Constant Numeric Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
14.5.1 Hexadecimal and Octal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
14.5.2 Integer Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
14.5.3 Floating Point Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

15 Types III: Conversions 105


15.1 String Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
15.1.1 Numeric Value to String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
15.1.2 String to Numeric Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
15.2 char Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
15.3 Numeric Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
15.3.1 Boolean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
15.3.2 Integer to Integer Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
15.3.3 Integer and Floating Point Conversions . . . . . . . . . . . . . . . . . . . . . . 110
15.4 Implicit Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
15.4.1 The Integer Promotions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
15.4.2 The Usual Arithmetic Conversions . . . . . . . . . . . . . . . . . . . . . . . . . 110
15.4.3 void* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
CONTENTS v

15.5 Explicit Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111


15.5.1 Casting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

16 Types IV: Qualifiers and Specifiers 113


16.1 Type Qualifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
16.1.1 const . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
16.1.2 restrict . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
16.1.3 volatile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
16.1.4 _Atomic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
16.2 Storage-Class Specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
16.2.1 auto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
16.2.2 static . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
16.2.3 extern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
16.2.4 register . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
16.2.5 _Thread_local . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

17 Multifile Projects 121


17.1 Includes and Function Prototypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
17.2 Dealing with Repeated Includes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
17.3 static and extern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
17.4 Compiling with Object Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

18 The Outside Environment 125


18.1 Command Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
18.1.1 The Last argv is NULL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
18.1.2 The Alternate: char **argv . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
18.1.3 Fun Facts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
18.2 Exit Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
18.2.1 Other Exit Status Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
18.3 Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
18.3.1 Setting Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
18.3.2 Unix-like Alternative Environment Variables . . . . . . . . . . . . . . . . . . . . 132

19 The C Preprocessor 135


19.1 #include . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
19.2 Simple Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
19.3 Conditional Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
19.3.1 If Defined, #ifdef and #endif . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
19.3.2 If Not Defined, #ifndef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
19.3.3 #else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
19.3.4 General Conditional: #if, #elif . . . . . . . . . . . . . . . . . . . . . . . . . 138
19.3.5 Losing a Macro: #undef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
19.4 Built-in Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
19.4.1 Mandatory Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
19.4.2 Optional Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
19.5 Macros with Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
19.5.1 Macros with One Argument . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
19.5.2 Macros with More than One Argument . . . . . . . . . . . . . . . . . . . . . . . 143
19.5.3 Macros with Variable Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
19.5.4 Stringification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
19.5.5 Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
19.6 Multiline Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
19.7 Example: An Assert Macro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
19.8 The #error Directive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
19.9 The #pragma Directive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
vi CONTENTS

19.9.1 Non-Standard Pragmas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148


19.9.2 Standard Pragmas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
19.9.3 _Pragma Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
19.10 The #line Directive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
19.11 The Null Directive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150

20 structs II: More Fun with structs 151


20.1 Initializers of Nested structs and Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 151
20.2 Anonymous structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
20.3 Self-Referential structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
20.4 Flexible Array Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
20.5 Padding Bytes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
20.6 offsetof . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
20.7 Fake OOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
20.8 Bit-Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
20.8.1 Non-Adjacent Bit-Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
20.8.2 Signed or Unsigned ints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
20.8.3 Unnamed Bit-Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
20.8.4 Zero-Width Unnamed Bit-Fields . . . . . . . . . . . . . . . . . . . . . . . . . . 160
20.9 Unions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
20.9.1 Unions and Type Punning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
20.9.2 Pointers to unions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
20.9.3 Common Initial Sequences in Unions . . . . . . . . . . . . . . . . . . . . . . . 163
20.10 Unions and Unnamed Structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
20.11 Passing and Returning structs and unions . . . . . . . . . . . . . . . . . . . . . . . 166

21 Characters and Strings II 169


21.1 Escape Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
21.1.1 Frequently-used Escapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
21.1.2 Rarely-used Escapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
21.1.3 Numeric Escapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172

22 Enumerated Types: enum 173


22.1 Behavior of enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
22.1.1 Numbering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
22.1.2 Trailing Commas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
22.1.3 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
22.1.4 Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
22.2 Your enum is a Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174

23 Pointers III: Pointers to Pointers and More 177


23.1 Pointers to Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
23.1.1 Pointer Pointers and const . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
23.2 Multibyte Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
23.3 The NULL Pointer and Zero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
23.4 Pointers as Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
23.5 Casting Pointers to other Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
23.6 Pointer Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
23.7 Pointers to Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185

24 Bitwise Operations 189


24.1 Bitwise AND, OR, XOR, and NOT . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
24.2 Bitwise Shift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189

25 Variadic Functions 191


CONTENTS vii

25.1 Ellipses in Function Signatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191


25.2 Getting the Extra Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
25.3 va_list Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
25.4 Library Functions That Use va_lists . . . . . . . . . . . . . . . . . . . . . . . . . . . 194

26 Locale and Internationalization 195


26.1 Setting the Localization, Quick and Dirty . . . . . . . . . . . . . . . . . . . . . . . . . 195
26.2 Getting the Monetary Locale Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
26.2.1 Monetary Digit Grouping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
26.2.2 Separators and Sign Position . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
26.2.3 Example Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
26.3 Localization Specifics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198

27 Unicode, Wide Characters, and All That 201


27.1 What is Unicode? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
27.2 Code Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
27.3 Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
27.4 Source and Execution Character Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
27.5 Unicode in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
27.6 A Quick Note on UTF-8 Before We Swerve into the Weeds . . . . . . . . . . . . . . . 205
27.7 Different Character Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
27.7.1 Multibyte Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
27.7.2 Wide Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
27.8 Using Wide Characters and wchar_t . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
27.8.1 Multibyte to wchar_t Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . 207
27.9 Wide Character Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
27.9.1 wint_t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
27.9.2 I/O Stream Orientation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
27.9.3 I/O Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
27.9.4 Type Conversion Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
27.9.5 String and Memory Copying Functions . . . . . . . . . . . . . . . . . . . . . . 209
27.9.6 String and Memory Comparing Functions . . . . . . . . . . . . . . . . . . . . . 210
27.9.7 String Searching Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
27.9.8 Length/Miscellaneous Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 210
27.9.9 Character Classification Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 211
27.10 Parse State, Restartable Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
27.11 Unicode Encodings and C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
27.11.1 UTF-8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
27.11.2 UTF-16, UTF-32, char16_t, and char32_t . . . . . . . . . . . . . . . . . . . . . 214
27.11.3 Multibyte Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
27.11.4 Third-Party Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215

28 Exiting a Program 217


28.1 Normal Exits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
28.1.1 Returning From main() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
28.1.2 exit() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
28.1.3 Setting Up Exit Handlers with atexit() . . . . . . . . . . . . . . . . . . . . . 218
28.2 Quicker Exits with quick_exit() . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
28.3 Nuke it from Orbit: _Exit() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
28.4 Exiting Sometimes: assert() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
28.5 Abnormal Exit: abort() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220

29 Signal Handling 221


29.1 What Are Signals? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
29.2 Handling Signals with signal() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
viii CONTENTS

29.3 Writing Signal Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222


29.4 What Can We Actually Do? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
29.5 Friends Don’t Let Friends signal() . . . . . . . . . . . . . . . . . . . . . . . . . . . 226

30 Variable-Length Arrays (VLAs) 227


30.1 The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227
30.2 sizeof and VLAs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
30.3 Multidimensional VLAs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
30.4 Passing One-Dimensional VLAs to Functions . . . . . . . . . . . . . . . . . . . . . . 229
30.5 Passing Multi-Dimensional VLAs to Functions . . . . . . . . . . . . . . . . . . . . . . 230
30.5.1 Partial Multidimensional VLAs . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
30.6 Compatibility with Regular Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
30.7 typedef and VLAs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
30.8 Jumping Pitfalls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
30.9 General Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232

31 goto 235
31.1 A Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
31.2 Labeled continue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
31.3 Bailing Out . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
31.4 Labeled break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
31.5 Multi-level Cleanup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
31.6 Tail Call Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
31.7 Restarting Interrupted System Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
31.8 goto and Thread Preemption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
31.9 goto and Variable Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
31.10 goto and Variable-Length Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242

32 Types Part V: Compound Literals and Generic Selections 245


32.1 Compound Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
32.1.1 Passing Unnamed Objects to Functions . . . . . . . . . . . . . . . . . . . . . . 246
32.1.2 Unnamed structs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
32.1.3 Pointers to Unnamed Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
32.1.4 Unnamed Objects and Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
32.1.5 Silly Unnamed Object Example . . . . . . . . . . . . . . . . . . . . . . . . . . 248
32.2 Generic Selections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248

33 Arrays Part II 253


33.1 Type Qualifiers for Arrays in Parameter Lists . . . . . . . . . . . . . . . . . . . . . . . 253
33.2 static for Arrays in Parameter Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
33.3 Equivalent Initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254

34 Long Jumps with setjmp, longjmp 257


34.1 Using setjmp and longjmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
34.2 Pitfalls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
34.2.1 The Values of Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
34.2.2 How Much State is Saved? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
34.2.3 You Can’t Name Anything setjmp . . . . . . . . . . . . . . . . . . . . . . . . . 259
34.2.4 You Can’t setjmp() in a Larger Expression . . . . . . . . . . . . . . . . . . . . 259
34.2.5 When Can’t You longjmp()? . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
34.2.6 You Can’t Pass 0 to longjmp() . . . . . . . . . . . . . . . . . . . . . . . . . . 260
34.2.7 longjmp() and Variable Length Arrays . . . . . . . . . . . . . . . . . . . . . . 260

35 Incomplete Types 261


35.1 Use Case: Self-Referential Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
CONTENTS ix

35.2 Incomplete Type Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262


35.3 Other Incomplete Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
35.4 Use Case: Arrays in Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
35.5 Completing Incomplete Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263

36 Complex Numbers 265


36.1 Complex Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
36.2 Assigning Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
36.3 Constructing, Deconstructing, and Printing . . . . . . . . . . . . . . . . . . . . . . . . 266
36.4 Complex Arithmetic and Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
36.5 Complex Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268
36.5.1 Trigonometry Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
36.5.2 Exponential and Logarithmic Functions . . . . . . . . . . . . . . . . . . . . . . 269
36.5.3 Power and Absolute Value Functions . . . . . . . . . . . . . . . . . . . . . . . . 269
36.5.4 Manipulation Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269

37 Fixed Width Integer Types 271


37.1 The Bit-Sized Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
37.2 Maximum Integer Size Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
37.3 Using Fixed Size Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
37.4 Limits of Fixed Size Integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
37.5 Format Specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273

38 Date and Time Functionality 275


38.1 Quick Terminology and Information . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
38.2 Date Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
38.3 Initialization and Conversion Between Types . . . . . . . . . . . . . . . . . . . . . . . 276
38.3.1 Converting time_t to struct tm . . . . . . . . . . . . . . . . . . . . . . . . . . 277
38.3.2 Converting struct tm to time_t . . . . . . . . . . . . . . . . . . . . . . . . . . 277
38.4 Formatted Date Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
38.5 More Resolution with timespec_get() . . . . . . . . . . . . . . . . . . . . . . . . . 279
38.6 Differences Between Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280

39 Multithreading 281
39.1 Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
39.2 Things You Can Do . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
39.3 Data Races and the Standard Library . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
39.4 Creating and Waiting for Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
39.5 Detaching Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
39.6 Thread Local Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
39.6.1 _Thread_local Storage-Class . . . . . . . . . . . . . . . . . . . . . . . . . . 289
39.6.2 Another Option: Thread-Specific Storage . . . . . . . . . . . . . . . . . . . . . 289
39.7 Mutexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
39.7.1 Different Mutex Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
39.8 Condition Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
39.8.1 Timed Condition Wait . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
39.8.2 Broadcast: Wake Up All Waiting Threads . . . . . . . . . . . . . . . . . . . . . 299
39.9 Running a Function One Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299

40 Atomics 301
40.1 Testing for Atomic Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
40.2 Atomic Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
40.3 Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
40.4 Acquire and Release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
40.5 Sequential Consistency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
x CONTENTS

40.6 Atomic Assignments and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307


40.7 Library Functions that Automatically Synchronize . . . . . . . . . . . . . . . . . . . . 308
40.8 Atomic Type Specifier, Qualifier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
40.9 Lock-Free Atomic Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
40.9.1 Signal Handlers and Lock-Free Atomics . . . . . . . . . . . . . . . . . . . . . . . 311
40.10 Atomic Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
40.11 Atomic structs and unions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
40.12 Atomic Pointers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
40.13 Memory Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
40.13.1 Sequential Consistency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
40.13.2 Acquire . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
40.13.3 Release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
40.13.4 Consume . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
40.13.5 Acquire/Release . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
40.13.6 Relaxed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
40.14 Fences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
40.15 References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315

41 Function Specifiers, Alignment Specifiers/Operators 317


41.1 Function Specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
41.1.1 inline for Speed—Maybe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
41.1.2 noreturn and _Noreturn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320
41.2 Alignment Specifiers and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
41.2.1 alignas and _Alignas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
41.2.2 alignof and _Alignof . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
Chapter 1

Foreword

C is not a big language, and it is not well served by a big book.


–Brian W. Kernighan, Dennis M. Ritchie
No point in wasting words here, folks, let’s jump straight into the C code:
E((ck?main((z?(stat(M,&t)?P+=a+'{'?0:3:
execv(M,k),a=G,i=P,y=G&255,
sprintf(Q,y/'@'-3?A(*L(V(%d+%d)+%d,0)

And they lived happily ever after. The End.


What’s this? You say something’s still not clear about this whole C programming language thing?
Well, to be quite honest, I’m not even sure what the above code does. It’s a snippet from one of the entries in
the 2001 International Obfuscated C Code Contest1 , a wonderful competition wherein the entrants attempt
to write the most unreadable C code possible, with often surprising results.
The bad news is that if you’re a beginner in this whole thing, all C code you see probably looks obfuscated!
The good news is, it’s not going to be that way for long.
What we’ll try to do over the course of this guide is lead you from complete and utter sheer lost confusion
on to the sort of enlightened bliss that can only be obtained through pure C programming. Right on.
In the old days, C was a simpler language. A good number of the features contained in this book and a lot
of the features in the Library Reference volume didn’t exist when K&R wrote the famous second edition of
their book in 1988. Nevertheless, the language remains small at its core, and I hope I’ve presented it here in
a way that starts with that simple core and builds outward.
And that’s my excuse for writing such a hilariously large book for such a small, concise language.

1.1 Audience
This guide assumes that you’ve already got some programming knowledge under your belt from another
language, such as Python2 , JavaScript3 , Java4 , Rust5 , Go6 , Swift7 , etc. (Objective-C8 devs will have a par-
1
https://www.ioccc.org/
2
https://en.wikipedia.org/wiki/Python_(programming_language)
3
https://en.wikipedia.org/wiki/JavaScript
4
https://en.wikipedia.org/wiki/Java_(programming_language)
5
https://en.wikipedia.org/wiki/Rust_(programming_language)
6
https://en.wikipedia.org/wiki/Go_(programming_language)
7
https://en.wikipedia.org/wiki/Swift_(programming_language)
8
https://en.wikipedia.org/wiki/Objective-C

1
2 Chapter 1. Foreword

ticularly easy time of it!)


We’re going to assume you know what variables are, what loops do, how functions work, and so on.
If that’s not you for whatever reason the best I can hope to provide is some honest entertainment for your
reading pleasure. The only thing I can reasonably promise is that this guide won’t end on a cliffhanger… or
will it?

1.2 How to Read This Book


The guide is in two volumes, and this is the first: the tutorial volume!
The second volume is the library reference9 , and it’s far more reference than tutorial.
If you’re new, go through the tutorial part in order, generally. The higher you get in chapters, the less
important it is to go in order.
And no matter your skill level, the reference part is there with complete examples of the standard library
function calls to help refresh your memory whenever needed. Good for reading over a bowl of cereal or
other time.
Finally, glancing at the index (if you’re reading the print version), the reference section entries are italicized.

1.3 Platform and Compiler


I’ll try to stick to Plain Ol’-Fashioned ISO-standard C10 . Well, for the most part. Here and there I might go
crazy and start talking about POSIX11 or something, but we’ll see.
Unix users (e.g. Linux, BSD, etc.) try running cc or gcc from the command line–you might already have a
compiler installed. If you don’t, search your distribution for installing gcc or clang.
Windows users should check out Visual Studio Community12 . Or, if you’re looking for a more Unix-like
experience (recommended!), install WSL13 and gcc.
Mac users will want to install XCode14 , and in particular the command line tools.
There are a lot of compilers out there, and virtually all of them will work for this book. And a C++ compiler
will compile a lot of (but not all!) C code. Best use a proper C compiler if you can.

1.4 Official Homepage


This official location of this document is https://beej.us/guide/bgc/15 . Maybe this’ll change in the future, but
it’s more likely that all the other guides are migrated off Chico State computers.

1.5 Email Policy


I’m generally available to help out with email questions so feel free to write in, but I can’t guarantee a
response. I lead a pretty busy life and there are times when I just can’t answer a question you have. When
that’s the case, I usually just delete the message. It’s nothing personal; I just won’t ever have the time to give
the detailed answer you require.
9
https://beej.us/guide/bgclr/
10
https://en.wikipedia.org/wiki/ANSI_C
11
https://en.wikipedia.org/wiki/POSIX
12
https://visualstudio.microsoft.com/vs/community/
13
https://docs.microsoft.com/en-us/windows/wsl/install-win10
14
https://developer.apple.com/xcode/
15
https://beej.us/guide/bgc/
1.6. Mirroring 3

As a rule, the more complex the question, the less likely I am to respond. If you can narrow down your
question before mailing it and be sure to include any pertinent information (like platform, compiler, error
messages you’re getting, and anything else you think might help me troubleshoot), you’re much more likely
to get a response.
If you don’t get a response, hack on it some more, try to find the answer, and if it’s still elusive, then write
me again with the information you’ve found and hopefully it will be enough for me to help out.
Now that I’ve badgered you about how to write and not write me, I’d just like to let you know that I fully
appreciate all the praise the guide has received over the years. It’s a real morale boost, and it gladdens me to
hear that it is being used for good! :-) Thank you!

1.6 Mirroring
You are more than welcome to mirror this site, whether publicly or privately. If you publicly mirror the site
and want me to link to it from the main page, drop me a line at [email protected].

1.7 Note for Translators


If you want to translate the guide into another language, write me at [email protected] and I’ll link to your
translation from the main page. Feel free to add your name and contact info to the translation.
Please note the license restrictions in the Copyright and Distribution section, below.

1.8 Copyright and Distribution


Beej’s Guide to C is Copyright © 2021 Brian “Beej Jorgensen” Hall.
With specific exceptions for source code and translations, below, this work is licensed under the Creative
Commons Attribution-Noncommercial-No Derivative Works 3.0 License. To view a copy of this license,
visit https://creativecommons.org/licenses/by-nc-nd/3.0/ or send a letter to Creative Commons,
171 Second Street, Suite 300, San Francisco, California, 94105, USA.
One specific exception to the “No Derivative Works” portion of the license is as follows: this guide may
be freely translated into any language, provided the translation is accurate, and the guide is reprinted in its
entirety. The same license restrictions apply to the translation as to the original guide. The translation may
also include the name and contact information for the translator.
The C source code presented in this document is hereby granted to the public domain, and is completely free
of any license restriction.
Educators are freely encouraged to recommend or supply copies of this guide to their students.
Contact [email protected] for more information.

1.9 Dedication
The hardest things about writing these guides are:
• Learning the material in enough detail to be able to explain it
• Figuring out the best way to explain it clearly, a seemingly-endless iterative process
• Putting myself out there as a so-called authority, when really I’m just a regular human trying to make
sense of it all, just like everyone else
• Keeping at it when so many other things draw my attention
4 Chapter 1. Foreword

A lot of people have helped me through this process, and I want to acknowledge those who have made this
book possible.
• Everyone on the Internet who decided to help share their knowledge in one form or another. The free
sharing of instructive information is what makes the Internet the great place that it is.
• The volunteers at cppreference.com16 who provide the bridge that leads from the spec to the real world.
• The helpful and knowledgeable folks on comp.lang.c17 and r/C_Programming18 who got me through
the tougher parts of the language.
• Everyone who submitted corrections and pull-requests on everything from misleading instructions to
typos.
Thank you! ♥

16
https://en.cppreference.com/
17
https://groups.google.com/g/comp.lang.c
18
https://www.reddit.com/r/C_Programming/
Chapter 2

Hello, World!

2.1 What to Expect from C


“Where do these stairs go?”
“They go up.”
—Ray Stantz and Peter Venkman, Ghostbusters
C is a low-level language.
It didn’t use to be. Back in the day when people carved punch cards out of granite, C was an incredible way
to be free of the drudgery of lower-level languages like assembly1 .
But now in these modern times, current-generation languages offer all kinds of features that didn’t exist in
1972 when C was invented. This means C is a pretty basic language with not a lot of features. It can do
anything, but it can make you work for it.
So why would we even use it today?
• As a learning tool: not only is C a venerable piece of computing history, but it is connected to the bare
metal2 in a way that present-day languages are not. When you learn C, you learn about how software
interfaces with computer memory at a low level. There are no seatbelts. You’ll write software that
crashes, I assure you. And that’s all part of the fun!
• As a useful tool: C still is used for certain applications, such as building operating systems3 or in
embedded systems4 . (Though the Rust5 programming language is eyeing both these fields!)
If you’re familiar with another language, a lot of things about C are easy. C inspired many other languages,
and you’ll see bits of it in Go, Rust, Swift, Python, JavaScript, Java, and all kinds of other languages. Those
parts will be familiar.
The one thing about C that hangs people up is pointers. Virtually everything else is familiar, but pointers are
the weird one. The concept behind pointers is likely one you already know, but C forces you to be explicit
about it, using operators you’ve likely never seen before.
It’s especially insidious because once you grok6 pointers, they’re suddenly easy. But up until that moment,
they’re slippery eels.
1
https://en.wikipedia.org/wiki/Assembly_language
2
https://en.wikipedia.org/wiki/Bare_machine
3
https://en.wikipedia.org/wiki/Operating_system
4
https://en.wikipedia.org/wiki/Embedded_system
5
https://en.wikipedia.org/wiki/Rust_(programming_language)
6
https://en.wikipedia.org/wiki/Grok

5
Exploring the Variety of Random
Documents with Different Content
an Asiatic foe. We may also see in our own British Museum how the
birth of Athênê was recorded in a marble group on one pediment of
the Parthenon, and the foundation of her chosen city on the other.
The very temple which these majestic sculptures once adorned was
a petrified memorial of antiquity, and, by the mere form of its
architecture, must have carried back men’s thoughts to the earliest
Hellenic habitation, the simple structure in which a gabled roof was
supported by cross-beams on a row of upright wooden posts.
Turning back once more from art and literature to philosophy, is it
not abundantly clear that if the Greeks speculated at all, they must
at first have speculated according to some such method as that
which history proves them to have actually followed? They must
have begun by fixing their thoughts, as Thales and his successors
did, on the world’s remotest past; they must have sought for a first
cause of things, and conceived it, not as any spiritual power, but as
a kind of natural ancestor homogeneous with the forms which issued
from it, although greater and more comprehensive than they were;
in short, as an elemental body—water, air, fire, or, more vaguely, as
an infinite substance. Did not the steady concatenation of cause and
effect resemble the unrolling of a heroic genealogy? And did not the
reabsorption of every individual existence in a larger whole translate
into more general terms that subordination of personal to family and
civic glory which is the diapason of Pindar’s music?
Nor was this all. Before philosophising, the Greeks did not think
only in the order of time; they learned at a very early period to think
also in the order of space, their favourite idea of a limit being made
especially prominent here. Homer’s geographical notions, however
erroneous, are, for his age, singularly well defined. Aeschylus has a
wide knowledge of the earth’s surface, and exhibits it with perhaps
unnecessary readiness. Pindar delights to follow his mythological
heroes about on their travels. The same tendency found still freer
scope when prose literature began. Hecataeus, one of the earliest
prose-writers, was great both as a genealogist and as a geographer;
and in this respect also Herodotus carried out on a great scale the
enquiries most habitually pursued by his countrymen. Now, it will be
remembered that we have had occasion to characterise early Ionian
speculation as being, to a great extent, cosmography. The element
from which it deduced all things was, in fact, that which was
supposed to lie outside and embrace the rest. The geographical limit
was conceived as a genealogical ancestor. Thus, the studies which
men like Hecataeus carried on separately, were combined, or rather
confused, in a single bold generalisation by Anaximenes and
Heracleitus.
Yet, however much may be accounted for by these considerations,
they still leave something unexplained. Why should one thinker after
another so unhesitatingly assume that the order of Nature as we
know it has issued not merely from a different but from an exactly
opposite condition, from universal confusion and chaos? Their
experience was far too limited to tell them anything about those vast
cosmic changes which we know by incontrovertible evidence to have
already occurred, and to be again in course of preparation. We can
only answer this question by bringing into view what may be called
the negative moment of Greek thought. The science of contraries is
one, says Aristotle, and it certainly was so to his countrymen. Not
only did they delight to bring together the extremes of weal and
woe, of pride and abasement, of security and disaster, but whatever
they most loved and clung to in reality seemed to interest their
imagination most powerfully by its removal, its reversal, or its
overthrow. The Athenians were peculiarly intolerant of regal
government and of feminine interference in politics. In Athenian
tragedy the principal actors are kings and royal ladies. The Athenian
matrons occupied a position of exceptional dignity and seclusion.
They are brought upon the comic stage to be covered with the
coarsest ridicule, and also to interfere decisively in the conduct of
public affairs. Aristophanes was profoundly religious himself, and
wrote for a people whose religion, as we have seen, was pushed to
the extreme of bigotry. Yet he shows as little respect for the gods as
for the wives and sisters of his audience. To take a more general
example still, the whole Greek tragic drama is based on the idea of
family kinship, and that institution was made most interesting to
Greek spectators by the violation of its eternal sanctities, by
unnatural hatred, and still more unnatural love; or by a fatal
misconception which causes the hands of innocent persons, more
especially of tender women, to be armed against their nearest and
dearest relatives in utter unconsciousness of the awful guilt about to
be incurred. By an extension of the same psychological law to
abstract speculation we are enabled to understand how an early
Greek philosopher who had come to look on Nature as a cosmos, an
orderly whole, consisting of diverse but connected and
interdependent parts, could not properly grasp such a conception
until he had substituted for it one of a precisely opposite character,
out of which he reconstructed it by a process of gradual evolution.
And if it is asked how in the first place did he come by the idea of a
cosmos, our answer must be that he found it in Greek life, in
societies distinguished by a many-sided but harmonious
development of concurrent functions, and by voluntary obedience to
an impersonal law. Thus, then, the circle is complete; we have
returned to our point of departure, and again recognise in Greek
philosophy a systematised expression of the Greek national genius.
We must now bring this long and complicated, but it is hoped not
uninteresting, study to a close. We have accompanied philosophy to
a point where it enters on a new field, and embraces themes
sufficiently important to form the subject of a separate chapter. The
contributions made by its first cultivators to our positive knowledge
have already been summarised. It remains to mention that there
was nothing of a truly transcendental character about their
speculations. Whatever extension we may give to that terrible
bugbear, the Unknowable, they did not trespass on its domain.
Heracleitus and his compeers, while penetrating far beyond the
horizon of their age and country, kept very nearly within the limits of
a possible experience. They confused some conceptions which we
have learned to distinguish, and separated others which we have
learned to combine; but they were the lineal progenitors of our
highest scientific thought; and they first broke ground on a path
where we must continue to advance, if the cosmos which they won
for us is not to be let lapse into chaos and darkness again.
CHAPTER II.
THE GREEK HUMANISTS: NATURE AND LAW.

I.
In the preceding chapter we traced the rise and progress of
physical philosophy among the ancient Greeks. We showed how a
few great thinkers, borne on by an unparalleled development of
intellectual activity, worked out ideas respecting the order of nature
and the constitution of matter which, after more than two thousand
years, still remain as fresh and fruitful as ever; and we found that, in
achieving these results, Greek thought was itself determined by
ascertainable laws. Whether controlling artistic imagination or
penetrating to the objective truth of things, it remained always
essentially homogeneous, and worked under the same forms of
circumscription, analysis, and opposition. It began with external
nature, and with a far distant past; nor could it begin otherwise, for
only so could the subjects of its later meditations be reached. Only
after less sacred beliefs have been shaken can ethical dogmas be
questioned. Only when discrepancies of opinion obtrude themselves
on man’s notice is the need of an organising logic experienced. And
the mind’s eye, originally focussed for distant objects alone, has to
be gradually restricted in its range by the pressure of accumulated
experience before it can turn from past to present, from successive
to contemporaneous phenomena. We have now to undertake the not
less interesting task of showing how the new culture, the new
conceptions, the new power to think obtained through those earliest
speculations, reacted on the life from which they sprang,
transforming the moral, religious, and political creeds of Hellas, and
preparing, as nothing else could prepare, the vaster revolution which
has given a new dignity to existence, and substituted, in however
imperfect a form, for the adoration of animalisms which lie below
man, the adoration of an ideal which rises above him, but only
personifies the best elements of his own nature, and therefore is
possible for a perfected humanity to realise.
While most educated persons will admit that the Greeks are our
masters in science and literature, in politics and art, some even
among those who are free from theological prejudices will not be
prepared to grant that the principles which claim to guide our
conduct are only a wider extension or a more specific application of
Greek ethical teaching. Hebraism has been opposed to Hellenism as
the educating power whence our love of righteousness is derived,
and which alone prevents the foul orgies of a primitive nature-
worship from being still celebrated in the midst of our modern
civilisation. And many look on old Roman religion as embodying a
sense of duty higher than any bequeathed to us by Greece. The
Greeks have, indeed, suffered seriously from their own sincerity.
Their literature is a perfect image of their life, reflecting every blot
and every flaw, unveiled, uncoloured, undisguised. It was, most
fortunately, never subjected to the revision of a jealous priesthood,
bent on removing every symptom inconsistent with the hypothesis of
a domination exercised by themselves through all the past. Nor yet
has their history been systematically falsified to prove that they
never wrongfully attacked a neighbour, and were invariably obliged
to conquer in self-defence. Still, even taking the records as they
stand, it is to Greek rather than to Hebrew or Roman annals that we
must look for examples of true virtue; and in Greek literature, earlier
than in any other, occur precepts like those which are now held to be
most distinctively characteristic of Christian ethics. Let us never
forget that only by Stoical teaching was the narrow and cruel
formalism of ancient Roman law elevated into the ‘written reason’ of
the imperial jurists; only after receiving successive infiltrations of
Greek thought was the ethnic monotheism of Judaea expanded into
a cosmopolitan religion. Our popular theologians are ready enough
to admit that Hellenism was providentially the means of giving
Christianity a world-wide diffusion; they ignore the fact that it gave
the new faith not only wings to fly, but also eyes to see and a soul to
love. From very early times there was an intuition of humanity in
Hellas which only needed dialectical development to become an all-
sufficient law of life. Homer sympathises ardently with his own
countrymen, but he never vilifies their enemies. He did not, nor did
any Greek, invent impure legends to account for the origin of hostile
tribes whose kinship could not be disowned; unlike Samuel, he
regards the sacrifice of prisoners with unmixed abhorrence. What
would he, whose Odysseus will not allow a shout of triumph to be
raised over the fallen, have said to Deborah’s exultation at the
murder of a suppliant fugitive? Courage was, indeed, with him the
highest virtue, and Greek literature abounds in martial spirit-stirring
tones, but it is nearly always by the necessities of self-defence that
this enthusiasm is invoked; with Pindar and Simonides, with
Aeschylus and Sophocles, it is resistance to an invader that we find
so proudly commemorated; and the victories which make Greek
history so glorious were won in fighting to repel an unjust
aggression perpetrated either by the barbarians or by a tyrant state
among the Greeks themselves. There was, as will be shown
hereafter, an unhappy period when right was either denied, or, what
comes to the same thing, identified with might; but this offensive
paradox only served to waken true morality into a more vivid self-
consciousness, and into the felt need of discovering for itself a
stronger foundation than usage and tradition, a loftier sanction than
mere worldly success could afford. The most universal principle of
justice, to treat others as we should wish to be treated ourselves,
seems before the Rabbi Hillel’s time to have become almost a
common-place of Greek ethics;43 difficulties left unsolved by the
Book of Job were raised to a higher level by Greek philosophy; and
long before St. Paul, a Plato reasoned of righteousness, temperance,
and judgment to come.
No one will deny that the life of the Greeks was stained with foul
vices, and that their theory sometimes fell to the level of their
practice. No one who believes that moral truth, like all truth, has
been gradually discovered, will wonder at this phenomenon. If moral
conduct is a function of social life, then, like other functions, it will
be subject, not only to growth, but also to disease and decay. An
intense and rapid intellectual development may have for its condition
a totally abnormal state of society, where certain vices, unknown to
ruder ages, spring up and flourish with rank luxuriance. When men
have to take women along with them on every new path of enquiry,
progress will be considerably retarded, although its benefits will
ultimately be shared among a greater number, and will be better
insured against the danger of a violent reaction. But the work that
Hellas was commissioned to perform could not wait; it had to be
accomplished in a few generations, or not at all. The barbarians
were forcing their way in on every side, not merely with the weight
of invading armies, but with the deadlier pressure of a benumbing
superstition, with the brute-worship of Egypt and the devil-worship
of Phoenicia, with their delirious orgies, their mutilations, their
crucifixions, and their gladiatorial contests. Already in the later
dramas of Euripides and in the Rhodian school of sculpture, we see
the awful shadow coming nearer, and feel the poisonous breath of
Asia on our faces. Reason, the reason by which these terrors have
been for ever exorcised, could only arrive at maturity under the
influence of free and uninterrupted discussion carried on by men
among themselves in the gymnasium, the agora, the ecclêsia, and
the dicastery. The resulting and inevitable separation of the sexes
bred frightful disorders, which through all changes of creed have
clung like a moral pestilence to the shores of the Aegean, and have
helped to complicate political problems by joining to religious hatred
the fiercer animosity of physical disgust. But whatever were the
corruptions of Greek sentiment, Greek philosophy had the power to
purge them away. ‘Follow nature’ became the watchword of one
school after another; and a precept which at first may have meant
only that man should not fall below the brutes, was finally so
interpreted as to imply an absolute control of sense by reason. No
loftier standard of sexual purity has ever been inculcated than that
fixed by Plato in his latest work, the Laws. Isocrates bids husbands
set an example of conjugal fidelity to their wives. Socrates had
already declared that virtue was the same for both sexes. Xenophon
interests himself in the education of women. Plato would give them
the same training, and everywhere associate them in the same
functions with men. Equally decisive evidence of a theoretical
opposition to slavery is not forthcoming, and we know that it was
unfortunately sanctioned by Plato and Aristotle, in this respect no
better inspired than the early Christians; nevertheless, the germ of
such an opposition existed, and will hereafter be pointed out.
It has been said that the Greeks only worshipped beauty; that
they cultivated morality from the aesthetic side; that virtue was with
them a question, not of duty, but of taste. Some very strong texts
might be quoted in support of this judgment. For example, we find
Isocrates saying, in his encomium on Helen, that ‘Beauty is the first
of all things in majesty, and honour, and divineness. It is easy to see
its power: there are many things which have no share of courage, or
wisdom, or justice, which yet will be found honoured above things
which have each of these, but nothing which is devoid of beauty is
prized; all things are scorned which have not been given their part of
that attribute; the admiration for virtue itself comes to this, that of
all manifestations of life virtue is the most beautiful.’44 And Aristotle
distinguishes the highest courage as willingness to die for the καλόν.
So also Plato describes philosophy as a love ‘that leads one from fair
forms to fair practices, and from fair practices to fair notions, until
from fair notions he arrives at the notion of absolute beauty, and at
last knows what the essence of beauty is. And this is that life beyond
all others which man should live in the contemplation of beauty
absolute.’45 Now, first of all, we must observe that, while loveliness
has been worshipped by many others, none have conceived it under
a form so worthy of worship as the Greeks. Beauty with them was
neither little, nor fragile, nor voluptuous; the soul’s energies were
not relaxed but exalted by its contemplation; there was in it an
element of austere and commanding dignity. The Argive Hêrê,
though revealed to us only through a softened Italian copy, has
more divinity in her countenance than any Madonna of them all; and
the Melian Aphroditê is distinguished by majesty of form not less
than by purity and sweetness of expression. This beauty was the
unreserved information of matter by mind, the visible rendering of
absolute power, wisdom, and goodness. Therefore, what a Greek
worshipped was the perpetual and ever-present energising of mind;
but he forgot that beauty can only exist as a combination of spirit
with sense; and, after detaching the higher element, he continued to
call it by names and clothe it in attributes proper to its earthly
manifestations alone. Yet such an extension of the aesthetic
sentiment involved no weakening of the moral fibre. A service
comprehending all idealisms in one demanded the self-effacement of
a laborious preparation and the self-restraint of a gradual
achievement. They who pitched the goal of their aspiration so high,
knew that the paths leading up to it were rough, and steep, and
long; they felt that perfect workmanship and perfect taste, being
supremely precious, must be supremely difficult as well; χαλεπὰ τὰ
καλά they said, the beautiful is hard—hard to judge, hard to win,
and hard to keep. He who has passed through that stern discipline
need tremble at no other task; nor has duty anything to fear from a
companionship whose ultimate requirements are coincident with her
own, and the abandonment of which for a joyless asceticism can
only lead to the reappearance as an invading army of forces that
should have been cherished as indispensable allies.
It may be urged that beauty, however difficult of attainment or
severe in form, is, after all, essentially superficial; and that a
morality elaborated on the same principles will be equally superficial
—will, in fact, be little more than the art of keeping up appearances,
of displaying fine sentiments, of avoiding those actions the
consequences of which are immediately felt to be disagreeable, and,
above all, of not needlessly wounding anyone’s sensibilities. Such an
imitation of morality—which it would be a mistake to call hypocrisy—
has no doubt been common enough among all civilised nations; but
there is no reason to believe that it was in any way favoured by the
circumstances of Greek life. There is even evidence of a contrary
tendency, as, indeed, might be expected among a people whose
most important states were saved from the corrupting influences of
a court. Where the sympathetic admiration of shallow and excitable
spectators is the effect chiefly sought after, the showy virtues will be
preferred to the solid, and the appearance to the reality of all virtue;
while brilliant and popular qualities will be allowed to atone for the
most atrocious crimes. But, among the Greeks of the best period,
courage and generosity rank distinctly lower than temperance and
justice; their poets and moralists alike inculcate the preference of
substance to show; and in no single instance, so far as we can
judge, did they, as modern nations often do, for the sake of great
achievements condone great wrongs. It was said of a Greek and by
a Greek that he did not wish to seem but to be just.46 We follow the
judgment of the Greeks themselves in preferring Leonidas to
Pausanias, Aristeides to Themistocles, and Socrates to Alcibiades.
And we need only compare Epameinondas with David or Pericles
with Solomon as national heroes, to perceive at once how much
nearer the two Greeks come to our own standard of perfection, and
how futile are the charges sometimes brought against those from
whose traditions we have inherited their august and stainless fame.
Moreover, we have not here to consider what was the average
level of sentiment and practice among the Greeks; we have to study
what alone was of importance for the races which came under their
tuition, and that is the highest moral judgment to which they rose.
Now, the deliberate verdict of their philosophy on the relation
between beauty and virtue is contained in the following passage
from Plato’s Laws:—

‘When anyone prefers beauty to virtue, what is this but the


real and utter dishonour of the soul? For such a preference
implies that the body is more honourable than the soul; and this
is false, for there is nothing of earthly birth which is more
honourable than the heavenly, and he who thinks otherwise of
the soul has no idea how greatly he undervalues this wonderful
possession.’47
II.
Thus much for the current prejudices which seemed likely to
interfere with a favourable consideration of our subject. We have
next to study the conditions by which the form of Greek ethical
philosophy was originally determined. Foremost among these must
be placed the moral conceptions already current long before
systematic reflection could begin. What they were may be partly
gathered from some wise saws attributed by the Greeks themselves
to their Seven Sages, but probably current at a much earlier period.
The pith of these maxims, taken collectively, is to recommend the
qualities attributed by our own philosophic poet to his perfect
woman:—
‘The reason firm, the temperate will,
Endurance, foresight, strength, and skill.’
We may say almost as briefly that they inculcate complete
independence both of our own passions and of external
circumstances, with a corresponding respect for the independence of
others, to be shown by using persuasion instead of force. Their tone
will perhaps be best understood by contrast with that collection of
Hebrew proverbs which has come down to us under the name of
Solomon, but which Biblical critics now attribute to a later period and
a divided authorship. While these regularly put forward material
prosperity as the chief motive to good conduct, Hellenic wisdom
teaches indifference to the variations of fortune. To a Greek, ‘the
power that makes for righteousness,’ so far from being, ‘not
ourselves,’ was our own truest self, the far-seeing reason which
should guard us from elation and from depression, from passion and
from surprise. Instead of being offered old age as a reward, we are
told to be equally prepared for a long and for a short life.
Two precepts stand out before all others, which, trivial as they
may seem, are uttered from the very soul of Greek experience, ‘Be
moderate,’ and, ‘Know thyself.’ Their joint observance constitutes the
characteristic virtue of Sôphrosynê, which means all that we
understand by temperance, and a great deal more besides; so much,
in fact, that very clever Greeks were hard set to define it, and very
wise Greeks could pray for it as the fairest gift of the gods.48 Let us
suppose that each individual has a sphere of activity marked out for
him by his own nature and his special environment; then to discern
clearly the limits of that sphere and to keep within them would be
Sôphrosynê, while the discernment, taken alone, would be wisdom.
The same self-restraint operating as a check on interference with
other spheres would be justice; while the expansive force by which a
man fills up his entire sphere and guards it against aggressions may
be called courage. Thus we are enabled to comprehend the many-
sided significance of Sôphrosynê, to see how it could stand both for
a particular virtue and for all virtuousness whatever. We need only
glance at Homer’s poems, and in particular at the Iliad—a much
deeper as well as a more brilliant work than the Odyssey—to
perceive how very early this demand for moderation combined with
self-knowledge had embodied itself in Greek thought. Agamemnon
violates the rights of Achilles under the influence of immoderate
passion, and through ignorance of how little we can accomplish
without the hero’s assistance. Achilles, again, carries his
vindictiveness too far, and suffers in consequence. But his self-
knowledge is absolutely perfect; conscious that he is first in the field
while others are better in council, he never undertakes a task to
which his powers are not fully adequate; nor does he enter on his
final work of vengeance without a clear consciousness of the speedy
death which its completion will entail on himself. Hector, too,
notwithstanding ominous forebodings, knows his duty and does it,
but with much less just an estimate of his own powers, leading him
to pursue his success too far, and then, when the tide has turned,
not permitting him to make a timely retreat within the walls of Troy.
So with the secondary characters. Patroclus also oversteps the limits
of moderation, and pays the penalty with his life. Diomed silently
bears the unmerited rebuke of Agamemnon, but afterwards recalls it
at a most effective moment, when rising to oppose the craven
counsels of the great king. This the Greeks called observing
opportunity, and opportunism was with them, as with French
politicians, a form of moderation.49 Down at the very bottom of the
scale Thersites and Dolon are signal examples of men who do not
know their sphere and suffer for their folly. In the Odyssey,
Odysseus is a nearly perfect type of wisdom joined with self-control,
erring, if we remember rightly, only once, when he insults
Polyphemus before the ship is out of danger; while his comrades
perish from want of these same gifts.
So far, virtue was with the Greeks what it must inevitably be with
all men at first, chiefly self-regarding, a refined form of prudence.
Moreover, other-regarding virtues gave less scope for reflection,
being originally comprehended under obedience to the law. But
there were two circumstances which could not long escape their
notice; first, that fraud and violence are often, at least apparently,
profitable to those who perpetrate them, a fact bitterly remarked by
Hesiod;50 and secondly, that society cannot hold together without
justice. It was long before Governments grew up willing and able to
protect their subjects from mutual aggressions, nor does positive law
create morality, but implies it, and could not be worked without it.
Nor could international obligations be enforced by a superior
tribunal; hence they have remained down to the present day a fertile
theme for ethical discussion. It is at this point that morality forms a
junction with religion, the history of which is highly interesting, but
which can here be only briefly traced. The Olympian divinities, as
placed before us by Homer, are anything but moral. Their conduct
towards each other is that of a dissolute nobility; towards men it is
that of unscrupulous partisans and patrons. A loyal adherence to
friends and gratitude for sacrificial offerings are their most
respectable characteristics, raising them already a little above the
nature-powers whence they were derived. Now, mark how they first
become moralised. It is by being made witnesses to an oath. Any
one who is called in to testify to a promise feels aggrieved if it is
broken, looking on the breach as an insult to his own dignity. As the
Third Commandment well puts it, his name has been taken in vain.
Thus it happened that the same gods who left every other crime
unpunished, visited perjury with severe and speedy retribution,
continued even after the offender’s death.51 Respect for a contract is
the primary form of moral obligation, and still seems to possess a
peculiar hold over uneducated minds. We see every day how many
persons will abstain from actions which they know to be immoral
because they have given their word to that effect, not because the
actions themselves are wrong. And for that reason law courts would
be more willing to enforce contracts than to redress injuries. If, then,
one person inflicted damage on another, he might afterwards, in
order to escape retaliation from the injured party, or from his family,
engage to give satisfaction, and the court would compel him to
redeem his promise.52 Thus contract, by procuring redress for every
species of wrong, would gradually extend its own obligatory
character to abstinence from injury in general, and the divine
sanctions primarily invoked on behalf of oaths would be extended,
with them, over the whole domain of moral conduct.
Nor was this all. Laws and justice once established would require
to have their origin accounted for, and, according to the usual
genealogical method of the early Greeks, would be described as
children of the gods, who would thus be interested in their welfare,
and would avenge their violation—a stage of reflection already
reached in the Works and Days of Hesiod.
Again, when oracles like that at Delphi had obtained wide-spread
renown and authority, they would be consulted, not only on
ceremonial questions and matters of policy, but also on debateable
points of morality. The divine responses, being unbiassed by
personal interest, would necessarily be given in accordance with
received rules of rectitude, and would be backed by all the terrors of
a supernatural sanction. It might even be dangerous to assume that
the god could possibly give his support to wrong-doing. A story told
by Herodotus proves that such actually was the case.E There lived
once at Sparta a certain man named Glaucus, who had acquired so
great a reputation for probity that, during the troublous times of the
Persian conquest, a wealthy Milesian thought it advisable to deposit
a large sum of money with him for safe keeping. After a considerable
time the money was claimed by his children, but the honesty of
Glaucus was not proof against temptation. He pretended to have
forgotten the whole affair, and required a delay of three months
before making up his mind with regard to the validity of their
demand. During that interval he consulted the Delphic oracle to
know whether he might possess himself of the money by a false
oath. The answer was that it would be for his immediate advantage
to do so; all must die, the faithful and the perjured alike; but Horcus
(oath) had a nameless son swift to pursue without feet, strong to
grasp without hands, who would destroy the whole race of the
sinner. Glaucus craved forgiveness, but was informed that to tempt
the god was equivalent to committing the crime. He went home and
restored the deposit, but his whole family perished utterly from the
land before three generations had passed by.
Yet another step remained to take. Punishment must be
transferred from a man’s innocent children to the man himself in a
future life. But the Olympian theology was, originally at least,
powerless to effect this revolution. Its gods, being personifications of
celestial phenomena, had nothing to do with the dark underworld
whither men descended after death. There existed, however, side by
side with the brilliant religion of courts and camps which Greek
poetry has made so familiar to us, another religion more popular
with simple country-folk,53 to whom war meant ruin, courts of
justice a means invented by kings for exacting bribes, sea-voyages a
senseless imprudence, chariot-racing a sinful waste of money, and
beautiful women drones in the human hive, demons of extravagance
invented by Zeus for the purpose of venting his spite against
mankind. What interest could these poor people take in the
resplendent guardians of their hereditary oppressors, in Hêrê and
Athênê, Apollo and Poseidôn, Artemis and Aphroditê? But they had
other gods peculiar to themselves, whose worship was wrapped in
mystery, partly that its objects need not be lured away by the
attraction of richer offerings elsewhere, partly because the activity of
these Chthonian deities, as they were called, was naturally
associated with darkness and secresy. Presiding over birth and
death, over seed-time and harvest and vintage, they personified the
frost-bound sleep of vegetation in winter and its return from a dark
underworld in spring. Out of their worship grew stories which told
how Persephonê, the fair daughter of Dêmêtêr, or Mother Earth, was
carried away by Pluto to reign with him over the shades below, but
after long searching was restored to her mother for eight months in
every year; and how Dionysus, the wine-god, was twice born, first
from the earth burned up and fainting under the intolerable fire of a
summer sky, respectively personified as Semelê and her lover Zeus,
then from the protecting mist wrapped round him by his divine
father, of whom it formed a part. Dionysus, too, was subject to
alternations of depression and triumph, from the recital of which
Attic drama was developed, and gained a footing in the infernal
regions, whither we accompany him in the Frogs of Aristophanes.
Another country god was Hermês, who seems to have been
associated with planting and possession as well as with the
demarcation and exchange of property, and who was also a
conductor of souls to Hades. Finally, there were the Erinyes, children
of night and dwellers in subterranean darkness; they could breed
pestilence and discord, but could also avert them; they could blast
the produce of the soil or increase its luxuriance and fertility; when
blood was spilt on the ground, they made it blossom up again in a
harvest of retributive hatred; they pursued the guilty during life, and
did not relax their grasp after death; all law, whether physical or
moral, was under their protection; the same Erinyes who, in the
Odyssey, avenge on Oedipus the suicide of his mother, in the Iliad
will not allow the miraculous speaking of a horse to continue; and
we have seen in the last chapter how, according to Heracleitus, it is
they who also prevent the sun from transgressing his appointed
limits.54 Dêmêtêr and Persephonê, too, seem to have been law-
giving goddesses, as their great festival, celebrated by women alone,
was called the Thesmophoria, while eternal happiness was promised
to those who had been initiated into their mysteries at Eleusis; and
we also find that moral maxims were graven on the marble busts of
Hermês placed along every thoroughfare in Athens. We can thus
understand why the mutilation of these Hermae caused such rage
and terror, accompanied, as it was rumoured to be, by a profanation
of the Eleusinian mysteries; for any attack on the deities in question
would seem to prefigure an attack on the settled order of things, the
popular rights which they both symbolised and protected.
Here, then, we find, chiefly among the rustic population, a religion
intimately associated with morality, and including the doctrine of
retribution after death. But this simple faith, though well adapted to
the few wants of its original votaries, could not be raised to the
utmost expansion and purity of which it was susceptible without
being brought into vivifying contact with that other Olympian religion
which, as we have seen, belonged more peculiarly to the ruling
aristocracy. The poor may be more moral than the rich, and the
country than the town; nevertheless it is from dwellers in cities, and
from the higher classes, including as they do a large percentage of
educated, open-minded individuals, that the impulses to moral
progress always proceed. If the narrowness and hardness of
primitive social arrangements were overcome; if justice was
disengaged from the ties of blood-relationship, and tempered with
consideration for inevitable error; if deadly feuds were terminated by
a habitual appeal to arbitration; if the worship of one supreme ideal
was substituted for a blind sympathy with the ebb and flow of life on
earth; if the numerical strength of states was increased by giving
shelter to fugitives; if a Hellenic nation was created and held
together by a common literature and a common civilisation, by
oracles accessible to all, and by periodical games in which every
free-born Greek could take part; and, lastly, if a brighter abode than
the slumberous garden of Persephonê was assigned after death to
the godlike heroes who had come forth from a thrice repeated
ordeal with souls unstained by sin;55—all this was due to the military
rather than to the industrial classes, to the spirit that breathes
through Homer rather than to the tamer inspiration of Hesiod’s
muse. But if justice was raised to an Olympian throne; if righteous
providence, no less than creative power, became an inalienable
attribute of Zeus; if lyric poetry, from Archilochus to Simonides and
Pindar, is one long hymn of prayer and praise ever turned upward in
adoring love to the Divine; we must remember that Themis was a
synonyme for Earth, and that Prometheus, the original friend of
humanity, for whose benefit he invented every useful art, augury
included, was her son. The seeds of immortal hope were first
planted in the fructifying bosom of Dêmêtêr, and life, a forsaken
Ariadnê, took refuge in the mystical embraces of Dionysus from the
memory of a promise that had allured her to betray. Thus, we may
conjecture that between hall and farm-house, between the Olympian
and the Chthonian religions, there was a constant reaction going on,
during which ethical ideas were continually expanding, and
extricating themselves from the superstitious elements associated
with their earliest theological expression.

III.
This process was conceived by Aeschylus as a conflict between
two generations of gods, ending with their complete reconciliation.
In the Prometheus Bound we have the commencement of the
conflict, in the Eumenides its close. Our sympathies are apparently
at first intended to be enlisted on behalf of the older divinities, but
at last are claimed exclusively by the younger. As opposed to
Prometheus, Zeus is evidently in the wrong, and seeks to make up
for his deficiencies by arbitrary violence. In the Oresteia he is the
champion of justice against iniquity, and through his interpreter,
Apollo, he enforces a revised moral code against the antiquated
claims of the Erinyes; these latter, however, ultimately consenting to
become guardians of the new social order. The Aeschylean drama
shows us Greek religion at the highest level it could reach, unaided
by philosophical reflection. With Sophocles a perceptible decline has
already begun. We are loth to say anything that may sound like
disparagement of so noble a poet. We yield to none in admiration for
one who has combined the two highest qualities of art—sweetness
and strength—more completely than any other singer, Homer alone
excepted, and who has given the primordial affections their definitive
expression for all time. But we cannot help perceiving an element of
superstition in his dramas, which, so far, distinguishes them
unfavourably from those of his Titanic predecessor. With Sophocles,
when the gods interfere, it is to punish disrespect towards
themselves, not to enforce justice between man and man. Ajax
perishes by his own hand because he has neglected to ask for divine
assistance in battle. Laius and Jocastê come to a tragic end through
disobedience to a perfectly arbitrary oracle; and as a part of the
same divine purpose Oedipus encounters the most frightful
calamities by no fault of his own. The gods are, moreover,
exclusively objects of fear; their sole business is to enforce the
fulfilment of enigmatic prophecies; they give no assistance to the
pious and virtuous characters. Antigonê is allowed to perish for
having performed the last duties to her brother’s corpse.
Neoptolemus receives no aid in that struggle between ambition on
the one hand with truthfulness and pity on the other which makes
his character one of the most interesting in all imaginative literature.
When Athênê bids Odysseus exult over the degradation of Ajax, the
generous Ithacan refuses to her face, and falls back on the
consciousness of a common humanity uniting him in sympathy with
his prostrate foe.
The rift within the lute went on widening till all its music was
turned to jarring discord. With the third great Attic dramatist we
arrive at a period of complete dissolution. Morality is not only
separated from mythological tradition, but is openly at war with it.
Religious belief, after becoming almost monotheistic, has relapsed
into polytheism. With Euripides the gods do not, as with his
predecessors, form a common council. They lead an independent
existence, not interfering with each other, and pursuing private ends
of their own—often very disreputable ones. Aphrodite inspires
Phaedra with an incestuous passion for her stepson. Artemis is
propitiated by human sacrifices. Hêrê causes Heraclês to kill his
children in a fit of delirium. Zeus and Poseidôn are charged with
breaking their own laws, and setting a bad example to mortals.
Apollo, once so venerated, fares the worst of any. He outrages a
noble maiden, and succeeds in palming off her child on the man
whom she subsequently marries. He instigates the murder of a
repentant enemy who has come to seek forgiveness at his shrine. He
fails to protect Orestes from the consequences of matricide,
committed at his own unwise suggestion. Political animosity may
have had something to do with these attacks on a god who was
believed to side with the Dorian confederacy against Athens.
Doubtless, also, Euripides disbelieved many of the scandalous stories
which he selected as appropriate materials for dramatic
representation. But a satire on immoral beliefs would have been
unnecessary had they not been generally accepted. Nor was the
poet himself altogether a freethinker. One of his latest and most
splendid works, the Bacchae, is a formal submission to the orthodox
creed. Under the stimulus of an insane delusion, Pentheus is torn to
pieces by his mother Agavê and her attendant Maenads, for having
presumed to oppose the introduction of Dionysus-worship into
Thebes. The antecedents of the new divinity are questionable, and
the nature of his influence on the female population extremely
suspicious. Yet much stress is laid on the impiety of Pentheus, and
we are clearly intended to consider his fate as well-deserved.
Euripides is not a true thinker, and for that very reason fitly
typifies a period when religion had been shaken to its very
foundation, but still retained a strong hold on men’s minds, and
might at any time reassert its ancient authority with unexpected
vigour. We gather, also, from his writings, that ethical sentiment had
undergone a parallel transformation. He introduces characters and
actions which the elder dramatists would have rejected as unworthy
of tragedy, and not only introduces them, but composes elaborate
speeches in their defence. Side by side with examples of devoted
heroism we find such observations as that everyone loves himself
best, and that those are most prosperous who attend most
exclusively to their own interests. It so happens that in one instance
where Euripides has chosen a subject already handled by Aeschylus,
the difference of treatment shows how great a moral revolution had
occurred in the interim. The conflict waged between Eteoclês and
Polyneicês for their father’s throne is the theme both of the Seven
against Thebes and of the Phoenician Women. In both, Polyneicês
bases his claim on grounds of right. It had been agreed that he and
his brother should alternately hold sway over Thebes. His turn has
arrived, and Eteoclês refuses to give way. Polyneicês endeavours to
enforce his pretensions by bringing a foreign army against Thebes.
Aeschylus makes him appear before the walls with an allegorical
figure of Justice on his shield, promising to restore him to his
father’s seat. On hearing this, Eteoclês exclaims:—
‘Aye, if Jove’s virgin daughter Justice shared
In deed or thought of his, then it might be.
But neither when he left the darkling womb,
Nor in his childhood, nor in youth, nor when
The clustering hair first gathered round his chin,
Hath Justice turned approving eyes on him;
Nor deem I that she comes as his ally,
Now that he wastes his native land with war,
Or Justice most unjustly were she called
If ruthless hearts could claim her fellowship.’56
Euripides, with greater dramatic skill, brings the two brothers
together in presence of their mother, Jocastê. When Polyneicês has
spoken, Eteoclês replies:—
‘Honour and wisdom are but empty names
That mortals use, each with a different meaning,
Agreeing in the sound, not in the sense.
Hear, mother, undisguised my whole resolve!
Were Sovereignty, chief goddess among gods,
Far set as is the rising of a star,
Or buried deep in subterranean gloom,
There I would seek and win her for mine own.

Come fire, come sword, yoke horses to the car,


And fill the plain with armed men, for I
Will not give up my royalty to him!
Let all my life be guiltless save in this:
I dare do any wrong for sovereign power—
The splendid guerdon of a splendid sin.’57
The contrast is not only direct, but designed, for Euripides had the
work of his predecessor before him, and no doubt imagined that he
was improving on it.
We perceive a precisely similar change of tone on comparing the
two great historians who have respectively recorded the struggle of
Greece against Persia, and the struggle of imperial Athens against
Sparta and her allies. Though born within fifteen years of one
another, Herodotus and Thucydides are virtually separated by an
interval of two generations, for while the latter represents the most
advanced thought of his time, the former lived among traditions
inherited from the age preceding his own. Now, Herodotus is not
more remarkable for the earnest piety than for the clear sense of
justice which runs through his entire work. He draws no distinction
between public and private morality. Whoever makes war on his
neighbours without provocation, or rules without the consent of the
governed, is, according to him, in the wrong, although he is well
aware that such wrongs are constantly committed. Thucydides
knows nothing of supernatural interference in human affairs. After
relating the tragical end of Nicias, he observes, not without a
sceptical tendency, that of all the Greeks then living, this unfortunate
general least deserved such a fate, so far as piety and respectability
of character went. If there are gods they hold their position by
superior strength. That the strong should enslave the weak is a
universal and necessary law of Nature. The Spartans, who among
themselves are most scrupulous in observing traditional obligations,
in their dealings with others most openly identify gain with honour,
and expediency with right. Even if the historian himself did not share
these opinions, it is evident that they were widely entertained by his
contemporaries, and he expressly informs us that Greek political
morality had deteriorated to a frightful extent in consequence of the
civil discords fomented by the conflict between Athens and Sparta;
while, in Athens at least, a similar corruption of private morality had
begun with the great plague of 430, its chief symptom being a mad
desire to extract the utmost possible enjoyment from life, for which
purpose every means was considered legitimate. On this point
Thucydides is confirmed and supplemented by the evidence of
another contemporary authority. According to Aristophanes, the
ancient discipline had in his time become very much relaxed. The
rich were idle and extravagant; the poor mutinous; young men were
growing more and more insolent to their elders; religion was
derided; all classes were animated by a common desire to make
money and to spend it on sensual enjoyment. Only, instead of
tracing back this profound demoralisation to a change in the social
environment, Aristophanes attributes it to demagogues, harassing
informers, and popular poets, but above all to the new culture then
coming into vogue. Physical science had brought in atheism;
dialectic training had destroyed the sanctity of ethical restraints.
When, however, the religious and virtuous Socrates is put forward as
a type of both tendencies, our confidence in the comic poet’s
accuracy, if not in his good faith, becomes seriously shaken; and his
whole tone so vividly recalls the analogous invectives now hurled
from press and pulpit against every philosophic theory, every
scientific discovery, every social reform at variance with traditional

You might also like