Why Learn C Go Behind the Curtain of Modern Systems with C23 (Paul J. Lucas) (Z-Library)

Author: Paul J. Lucas

技术

No Description

📄 File Format: PDF
💾 File Size: 17.5 MB
47
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
Why Learn C Go Behind the Curtain of Modern Systems with C23 — Paul J. Lucas Apress
📄 Page 2
Why Learn C
📄 Page 3
Paul J. Lucas Why Learn C Go Behind the Curtain of Modern Systems with C23 Apress®
📄 Page 4
Paul J. Lucas Oakland, CA, USA ISBN-13 (pbk): 979-8-8688-1596-6 ISBN-13 (electronic): 979-8-8688-1597-3 https://doi.org/10.1007/979-8-8688-1597-3 Copyright © 2025 by Paul J. Lucas This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image, we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Melissa Duffy Coordinating Editor: Gryffin Winkler Cover Photo by Pawel Czerwinski on Unsplash (unsplash.com) Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com . Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales . Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub. For more detailed information, please visit https://www.apress.com/gp/services/ source-code. If disposing of this product, please recycle the paper
📄 Page 5
To my mentors and colleagues throughout my career who taught me much and made the journey more fun: Richard Acevedo, Tameem Anwar, Mitch Blank, Andrew Brown, Mike Carey, Iuri Chaer, Thomas Chimento, James Coplien, Henry Corin, Kevin Densmore, Jon Detert, Jack Dixon, Steve Eick, Brad Euhus, Dana Florescu, Rich Gaushell, Bob Graham, Tom Green, Jon Handler, Chris Hillery, Joseph Huckaby, Jeff Isenberg, Ivan Jager, Gordon Kotik, Andrew Lippai, Nicky Masjedizadeh, Richard McKeethen, Abhinav Nekkanti, Mike Nelson, Tommy Nguyen, Fredrik Nygaard, John Oyston, Randy Paquette, Vishal Patel, Linda Pinck, Nathan Pope, Chris Pride, Fabio Riccardi, Sai Sajja, Jeff Schmidt, Pratiksha Shah, Logan Shaw, Helen Stewart, Igor Stojanovski, and Sundar Vasan.
📄 Page 6
Contents Part I Learning C 1 1 A Tour of C 3 1.1 A First Program .............................................................................. 3 1.2 Copying Input to Output .................................................................. 5 1.3 Strings ............................................................................................. 9 1.4 Functions .......................................................................................... 12 1.5 Memory .......................................................................................... 14 1.6 Pointers .......................................................................................... 15 1.7 const ............................................. 17 1.8 Dynamic Memory ........................................................................... 20 1.9 Structures ....................................................................................... 23 1.10 Epilogue .......................................................................................... 25 2 Comments, Names, and Types 27 2.1 Comments ....................................................................................... 27 2.2 Names ............................................................................................. 29 2.3 Namespaces .................................................................................... 30 2.4 Scope ................................................................................................ 30 2.5 Built-In Types ................................................................................. 31 2.5.1 Modifiers ............................................................................ 31 2.5.2 bool ......................................... 32 2.5.3 char ......................................... 33 2.5.4 int ......................................... 34 2.5.5 _BitInt ..................................... 34 2.5.6 float, double, and long double .................. 35 2.5.7 _Decimal32, _Decimal64, and _Decimal128 ......... 36 2.5.8 Complex Numbers ............................................................. 36 2.5.9 Imaginary Numbers ............................................................. 37 2.6 typedef ............................................ 37 2.7 Fixed-Width Integer Types ............................................................ 38 2.8 Unicode Character Types ............................................................... 38 2.9 Other Standard Types ..................................................................... 39 2.10 Numeric Limits .............................................................................. 39 2.11 Signed Integer Overflow ................................................................... 40 vii
📄 Page 7
viii CONTENTS 2.12 Choosing an Appropriate Integer Type .......................................... 41 2.13 Type Conversions ........................................................................... 42 2.14 Epilogue .......................................................................................... 43 3 Operators 45 3.1 Associativity vs. Evaluation Order ................................................. 45 3.2 Arithmetic Operators ..................................................................... 46 3.3 Unary Plus and Minus Operators ................................................... 47 3.4 Increment and Decrement Operators ............................................. 47 3.5 Relational Operators ........................................................................ 48 3.6 Logical Operators ........................................................................... 48 3.7 Conditional Operator ..................................................................... 48 3.8 Bitwise Operators ........................................................................... 49 3.9 Assignment Operators ..................................................................... 52 3.10 Function Call Operator .................................................................. 52 3.11 Array Indexing Operator .................................................................. 52 3.12 Address-of and Dereference Operators ........................................... 53 3.13 Member Access Operators ............................................................... 53 3.14 Casting Operator .............................................................................. 54 3.14.1 Casting to void ................................ 55 3.14.2 Casting Away const ............................ 55 3.14.3 Casting Pointers ............................................................... 56 3.15 Comma Operator ........................................................................... 56 3.16 sizeof Operator .............................................................................. 57 3.17 alignof Operator ........................................................................... 58 3.18 Epilogue .......................................................................................... 58 4 Declarations 61 4.1 Multiple Declarations ..................................................................... 62 4.2 auto ............................................... 62 4.3 Storage Classes .............................................................................. 63 4.3.1 auto ......................................... 64 4.3.2 extern ...................................... 65 4.3.3 static ...................................... 65 4.3.4 register ..................................... 66 4.4 constexpr ........................................... 67 4.5 const ............................................. 67 4.6 typeof ............................................. 67 4.6.1 Declarations without Initializers ........................................ 68 4.6.2 Clarifying Complicated Declarations ................................... 68 4.7 typeof_unqual ...................................... 69 4.8 alignas ............................................ 69 4.9 Attributes ....................................................................................... 70 4.9.1 deprecated .................................. 70 4.9.2 fallthrough .................................. 70
📄 Page 8
CONTENTS ix 4.9.3 maybe_unused ................................ 71 4.9.4 nodiscard ................................... 71 4.9.5 noreturn ..................................... 72 4.10 Epilogue .......................................................................................... 72 5 Statements 73 5.1 Expression Statement ..................................................................... 73 5.2 Compound Statement ..................................................................... 73 5.3 if-else ............................................ 74 5.4 while ............................................. 75 5.5 do-while ............................................ 75 5.6 for ................................................ 76 5.7 break and continue .................................. 76 5.8 switch ............................................. 77 5.9 return ............................................. 79 5.10 goto ............................................... 79 5.11 Empty Statement (;) ........................................................................ 80 5.12 Epilogue .......................................................................................... 80 6 Arrays and Pointers 83 6.1 Array Declaration ........................................................................... 83 6.2 Array Initialization ........................................................................... 83 6.3 Array Indexing ................................................................................. 84 6.4 Multidimensional Arrays ............................................................... 84 6.5 void Pointers ................................................................................. 86 6.6 Pointers to Pointers ........................................................................ 87 6.7 Arrays and Pointers ........................................................................ 88 6.8 Arrays vs. Pointers ........................................................................... 89 6.9 Arrays of Pointers ........................................................................... 89 6.10 Pointers to Function ........................................................................ 90 6.11 Array Compound Literals ............................................................... 92 6.11.1 Compound Literal Lifetime and Storage Class .................. 93 6.12 Multidimensional Arrays vs. Pointers ............................................. 93 6.13 Dynamically Allocating 2D Arrays ................................................ 94 6.14 Variable Length Arrays .................................................................. 96 6.15 Epilogue .......................................................................................... 97 7 Enumerations 101 7.1 Declarations .................................................................................... 102 7.2 Name Collisions .............................................................................. 102 7.3 Underlying Type .............................................................................. 103 7.4 Implicit Conversion ........................................................................ 103 7.5 Enumeration Constant Values ......................................................... 104 7.5.1 Externally Imposed Values ................................................ 104 7.5.2 Serializing Values ............................................................... 105
📄 Page 9
x CONTENTS 7 5 3 Duplicate Values 105 7 5 4 “None” Values 106 7 5 5 Checking Values 106 7 5 6 “Count” Values 107 7 5 7 Bit Flag Values 108 7 6 Epilogue 109 8 Preprocessor 111 8 1 Compilation Phases 111 8 2 Language 112 8 3 Object-Like Macros 112 8 4 Predefined Macros 113 8 5 Conditional Compilation 113 8 5 1 defined 115 8 5 2 __has_c_attribute 116 8 5 3 __has_include 116 8 6 File Inclusion 116 8 7 Function-Like Macros 117 8 7 1 Parameters 117 8 7 2 Arguments 117 8 7 3 Variable Numbers of Arguments 118 8 7 4 Stringification 119 8 7 5 Concatenation 120 8 7 6 # and ## Pitfalls 120 8 8 Multiple Statements 122 8 9 X Macros 122 8 9 1 Serializing Enumeration Values 123 8 9 2 Counting Enumeration Values 124 8 10 Filename and Line Information 124 8 11 Errors and Warnings 124 8 12 Not Expanding a Macro 125 8 13 Paste Avoidance 125 8 14 Undefining a Macro 126 8 15 Embedding 126 8 16 Pragmas 127 8 17 Useful Macros 128 8 18 Epilogue 132 9 Functions 135 9 1 Declarations vs Definitions 135 9 2 Parameters 135 9 3 No Overloading 136 9 4 “Array” Parameters 136 9 4 1 Non-Null Array Syntax for Parameters 138 9 4 2 Qualified Array Syntax for Parameters 138
📄 Page 10
CONTENTS xi 9.4.3 Variable Length Array Syntax for Parameters .................. 139 9.4.4 Multidimensional Array Syntax for Parameters ............... 139 9.4.5 Multidimensional VLA Parameters ................................. 140 9.4.6 Array Syntax for Parameters Pitfalls ................................. 141 9.5 Return Values ................................................................................. 141 9.6 Error Handling ................................................................................. 142 9.7 main ............................................... 143 9.7.1 Declaration and Parameters ............................................. 143 9.7.2 Return Value and Exit Status ............................................. 144 9.8 Static Functions .............................................................................. 144 9.9 Static Local Variables ..................................................................... 145 9.9.1 __func__ .................................... 145 9.10 Inline Functions .............................................................................. 146 9.10.1 Differences from Macros ................................................... 146 9.10.2 Only a Hint ........................................................................ 147 9.10.3 When (and When Not) to Inline ....................................... 147 9.10.4 Inline Definition ............................................................... 148 9.11 Variadic Functions ........................................................................... 149 9.11.1 Variadic Pitfalls .................................................................. 150 9.11.2 Calling Other Variadic Functions ....................................... 152 9.12 Epilogue .......................................................................................... 153 10 Structures 157 10.1 Definition ....................................................................................... 157 10.2 No Nesting ....................................................................................... 158 10.3 Initialization .................................................................................... 159 10.4 Structure Compound Literals ......................................................... 160 10.5 Padding .......................................................................................... 162 10.6 Flexible Array Members .................................................................. 162 10.7 Bit-Fields ....................................................................................... 165 10.8 Epilogue .......................................................................................... 167 11 Unions 169 11.1 Definition ....................................................................................... 169 11.2 Initialization .................................................................................... 170 11.3 Union Compound Literals ............................................................... 170 11.4 Which Member? .............................................................................. 171 11.5 Type Punning ................................................................................. 171 11.6 Restricted Class Hierarchies ............................................................ 172 11.6.1 Safeguards ........................................................................ 175 11.7 Epilogue .......................................................................................... 176 12 Input, Output, and Files 179 12.1 Output ............................................................................................. 179 12.1.1 Formatted Printing ............................................................ 181
📄 Page 11
xii CONTENTS 12.2 Files ................................................................................................ 183 12.2.1 Open Modes .................................................................... 186 12.2.2 File Information .............................................................. 186 12.2.3 File State .......................................................................... 187 12.2.4 File Position .................................................................... 188 12.2.5 Low-Level File I/O ........................................................... 189 12.2.6 Memory as a File .............................................................. 190 12.2.7 A File as Memory ........................................................... 191 12.2.8 Deletion ............................................................................ 191 12.2.9 Temporary Files .............................................................. 192 12.3 Directories ....................................................................................... 192 12.4 Input ................................................................................................ 194 12.4.1 Formatted Reading ........................................................... 194 12.4.2 String-to-Number Conversion ......................................... 197 12.4.3 Line Reading .................................................................... 198 12.4.4 Environment Variables ..................................................... 200 12.5 Epilogue .......................................................................................... 201 13 Program Organization 203 13.1 Include Guards ................................................................................. 203 13.2 Opaque Types ................................................................................. 205 13.3 Self Sufficient Headers .................................................................. 206 13.3.1 Including Headers in a Header .......................................... 206 13.3.2 Include Everything Necessary ........................................... 207 13.3.3 Interdependencies ............................................................... 207 13.4 Cooperating with C++ .................................................................................. 208 13.5 Including Headers in a .c File ......................................................... 209 13.6 Initialization and Clean-Up ............................................................. 210 13.7 Header Example .............................................................................. 211 13.8 File Organization ........................................................................... 212 13.9 Build Tools ....................................................................................... 213 13.10 Epilogue .......................................................................................... 214 14 Multithreading 215 14.1 Creating and Joining Threads ......................................................... 217 14.2 Detaching Threads ........................................................................... 218 14.3 “Atomic” .......................................................................................... 219 14.3.1 A Bad Example .................................................................. 219 14.4 Mutexes .......................................................................................... 221 14.4.1 Timed Mutexes .................................................................. 224 14.4.2 Deadlocks ........................................................................... 224 14.4.3 Recursive Mutexes ............................................................. 226 14.5 Condition Variables ........................................................................ 226 14.5.1 Timed Condition Variables ................................................ 229 14.6 Doing Something Once .................................................................. 229
📄 Page 12
CONTENTS xiii 14.7 thread_local ....................................... 230 14.8 Thread-Specific Storage ................................................................... 231 14.9 Epilogue .......................................................................................... 232 Part II Selected Topics 233 15 Undefined Behavior 235 15. 1 Implications and Example ................................................................ 236 15. 2 Two Parts to Undefined Behavior ............................................... 237 15. 3 Optimization Can Make Things Worse ...................................... 238 15. 4 Undefined Behavior in Other Languages ................................... 239 15. 5 Epilogue ...................................................................................... 240 16 Assertions 241 16. 1 Sample Implementation ................................................................... 241 16. 2 Assertions vs. Errors and Exceptions ......................................... 242 16. 3 Disabling Assertions in Production Code ................................... 243 16. 4 Adding a Message ....................................................................... 244 16.5 Static Assertions .............................................................................. 244 16.6 Epilogue .......................................................................................... 245 17 _Atomic 247 17.1 Alternative to a Mutex ..................................................................... 248 17.2 Atomic Functions ........................................................................... 248 17.3 Memory Barriers .............................................................................. 250 17.3.1 memory_order_seq_cst ......................... 250 17.3.2 memory_order_relaxed ......................... 251 17.3.3 memory_order_acquire and memory_order_release . 253 17.3.4 memory_order_consume ......................... 254 17.3.5 memory_order_acq_rel ......................... 255 17.4 Compare and Swap ........................................................................ 255 17.5 Lock-Free Operations ..................................................................... 258 17.6 The “ABA Problem” ........................................................................ 259 17.7 Versioned Pointers ........................................................................... 261 17.8 False Sharing ................................................................................. 262 17.9 Epilogue .......................................................................................... 263 18 Debugging 265 18.1 Printing Values ................................................................................. 265 18.2 Debug Information ........................................................................... 266 18.3 Optimization .................................................................................... 266 18.4 Core Dumps .................................................................................... 266 18.5 Signals ............................................................................................. 267 18.6 Common Bugs ................................................................................. 268 18.6.1 Array Bounds ..................................................................... 268
📄 Page 13
xiv CONTENTS 18.6.2 Buffer Overflow .............................................................. 268 18.6.3 Double Free ....................................................................... 269 18.6.4 Null Pointer Dereference .................................................. 269 18.6.5 Off-by-One ....................................................................... 269 18.6.6 Use After Free ................................................................. 269 18.6.7 Memory Leak .................................................................... 270 18.6.8 Uninitialized Variable ..................................................... 271 18.7 Warnings ......................................................................................... 272 18.7.1 Recommended Warnings .................................................. 272 18.7.2 Disabling Warnings ........................................................... 276 18.8 The Curious Case of the Disappearing if ................... 276 18.9 Profiling ......................................................................................... 281 18.1 0 Epilogue ...................................................................................... 281 19 _Generic 283 19.1 Motivating Example ....................................................................... 283 19.2 A printf Example ....................................................................... 284 19.3 const Overloading ....................................................................... 286 19.4 Static if ........................................... 287 19.5 No SFINAE (Substitution Failure is not an Error) ....................... 288 19.6 Type Traits ...................................................................................... 289 19.7 Epilogue ......................................................................................... 297 20 setjmp and longjmp 299 20.1 Basics ............................................................................................ 299 20.2 setjmp Restrictions ........................................................................ 300 20.3 volatile Variables ........................................................................ 301 20.4 longjmp Details .............................................................................. 301 20.5 Exceptions in C? ............................................................................. 302 20.6 Epilogue ......................................................................................... 302 21 restrict 305 21.1 The Problem .................................................................................... 305 21.2 The Solution .................................................................................... 306 21.3 Pitfalls ............................................................................................ 306 21.4 When (and When Not) to Use restrict ................... 307 21.5 Miscellaneous ................................................................................ 308 21.6 Epilogue ......................................................................................... 308 22 volatile 309 22.1 Optimization Suppression ............................................................... 309 22.2 Signal Handling .............................................................................. 310 22.3 setjmp ............................................. 311 22.4 volatile in Other Languages ...................................................... 311 22.5 Wrong Uses .................................................................................... 312 22.6 Epilogue ......................................................................................... 312
📄 Page 14
CONTENTS xv Part III Extended Examples 313 23 Strings 315 23. 1 string 2.0 ................................................................................... 315 23.1.1 More put Variants ........................................................... 315 23.1.2 Formatted Printing ........................................................... 316 23.1.3 Taking Ownership ........................................................... 317 23. 2 strbuf: A String Buffer Type ..................................................... 318 23.2.1 Reserving Space .............................................................. 319 23.2.2 Putting ............................................................................. 319 23.2.3 Formatted Printing ........................................................... 320 23.2.4 Taking Ownership ........................................................... 321 23.2.5 Resetting .......................................................................... 321 23. 3 Epilogue ......................................................................................... 323 24 Lists 325 24. 1 Initialization and Clean-Up ........................................................... 326 24. 2 Pushing ......................................................................................... 326 24. 3 Front, Back, and Empty ................................................................. 328 24. 4 Popping ......................................................................................... 328 24. 5 Removing from the Middle ........................................................... 329 24. 6 Iterating ......................................................................................... 331 24.7 Epilogue ......................................................................................... 332 25 Maps 333 25.1 Hash Tables ................................................................................... 334 25.2 Hash Table Types .......................................................................... 336 25.3 Initialization and Clean-Up ........................................................... 338 25.4 Insert ............................................................................................... 339 25.5 Growing ......................................................................................... 340 25.6 Finding ............................................................................................ 341 25.7 Deleting ......................................................................................... 342 25.8 Iteration ......................................................................................... 342 25.9 Epilogue ......................................................................................... 343 26 Dynamic Dispatch 345 26.1 Pointers to Function ....................................................................... 346 26.2 Function Tables ............................................................................. 347 26.3 Fat Pointers ................................................................................... 348 26.4 Epilogue ......................................................................................... 350 27 Exceptions in C 351 27.1 Requirements ................................................................................ 351 27.2 try ................................................ 352 27.3 throw ............................................. 353 27.4 catch ............................................. 356
📄 Page 15
xvi CONTENTS 27.5 finally ........................................... 357 27.6 Restrictions ................................................................................... 358 27.7 Epilogue ......................................................................................... 359 A Standard Headers 361 B Standard Functions 363 B.1 ctype.h ........................................... 363 B.2 string.h .......................................... 364 B.3 time.h ............................................. 366 C C23 Differences 371 C.1 Aggregate Initialization ................................................................. 371 C.2 alignas and alignof ................................. 371 C.3 Attributes ...................................................................................... 372 C.4 auto .............................................. 372 C.5 Binary Literals ................................................................................ 372 C.6 bool .............................................. 372 C.7 constexpr .......................................... 373 C.8 Declarations After Labels .............................................................. 373 C.9 Digit Separators ............................................................................. 374 C.10 #embed ............................................. 374 C.11 Fixed-Type Enumerations .............................................................. 374 C.12 Function Definition Unnamed Parameters ...................................... 374 C.13 K&R-Style Function Declarations and Definitions ....................... 374 C.14 noreturn .......................................... 376 C.15 nullptr ........................................... 376 C.16 static_assert ..................................... 377 C.17 Storage Classes for Compound Literals ......................................... 377 C.18 thread_local ....................................... 377 C.19 typeof and typeof_unqual ........................... 378 C.20 __VA_OPT__ ........................................ 378 C.21 Variadic Functions .......................................................................... 378 C.22 #warning .......................................... 379 Index 381
📄 Page 16
Preface “Should I still learn C?” That’s a question I see asked by many beginning (and some intermediate) program­ mers. Since you’re reading this preface, perhaps you have the same question. Con­ sidering that C was created in 1972 and that many more modern languages have been created since, it’s a fair question. Somewhat obviously (since this book exists), I believe the answer is “Yes.” Why? A few reasons: 1. Modern languages have many features for things like data structures (e.g., dy­ namic arrays, lists, maps), flow control (dynamic dispatch, exceptions), and al­ gorithms (e.g., counting, iteration, searching, selection, sorting) as part of the language (either directly built-in or readily available via their standard libraries). While convenient, the way in which those features are implemented “behind the curtain” has to be done in a general way to be applicable to a wide variety of programs. Most of the time, they work just fine. However, occasionally, they don’t. C is a fairly minimal language and has almost none of those things. If you want any of them, you’re likely going to have to implement them yourself. While onerous, you’ll be able to tailor your implementations to your circumstances. Knowledge of how to implement such features from scratch and understanding the trade-offs will serve you well even when programming in other languages because you’ll have insight as to how their features are implemented. 2. Many systems and some scripting languages (e.g., Python) provide C APIs for implementing extensions. If you ever want to write your own, you’ll need to know C. 3. Many open-source software packages upon which modern computers and the In­ ternet still depend are written in C including Apache, cURL, Exim, Git, the GNU compiler collection, Linux, OpenSSL, Postfix, PostgreSQL, Python, Sendmail, Wireshark, Zlib, and many others. If you ever want either to understand how those work or contribute to them, you’ll need to know C. xvii
📄 Page 17
xviii Preface 4. Embedded systems are largely developed in C (or C++, but with restrictions). If you ever want to work on embedded systems, you’ll likely need to know C. 5. C has influenced more languages than any other (except ALGOL). If, in addition to programming, you also have an interest in programming languages in general or from a historical perspective, you should know C. I’m not suggesting that you should learn C intending to switch to it as your pri­ mary programming language nor that you should implement your next big project in C. Programming languages are tools and the best tool should always be used for a given job. If you need to do any of the things listed in reasons 2-4 above, C will likely be the best tool for the job. “Wouldn’t learning C++ be good enough?” “I already know C++. Isn’t that good enough?” Since C++ has supplanted C in many cases, both of those are fair questions. The answer to both is “No.” Why? A couple of reasons: 1. Even though C++ is based on C, their similarities are superficial. Aside from sharing some keywords, basic syntax, and toolchain, they are very different lan­ guages. The ways in which you get things done in C is necessarily different from C++ due to C’s minimal features. 2. From the perspective of learning how features are implemented behind the cur­ tain, C++ is already too high-level since the language has modern features and its standard library contains several data structures and many algorithms. “Why this book?” If all that has convinced you that C is still worth learning, the last question is “Why this book?” Considering that The C Programming Language"* (by Brian Kernighan and Dennis Ritchie, C’s creator, known as “K&R”) is the classic book for learning C, that too is a fair question. The second (and last) edition of K&R was published in 1988 based on the then draft of the first ANSI standard of C (C89). C has evolved (slowly) since with the C95, C99, C11, C17, and C23 standards. This book covers them all. This book is split into three parts: ^The C Programming Language, Brian W. Kernighan and Dennis M. Ritchie, AT&T Bell Laboratories, Prentice-Hall, Englewood Cliffs, New Jersey, 1978 (1st ed.), 1988 (2nd ed.).
📄 Page 18
Preface xix 1. Learning C: teaches the C23 standard of C, includes many additional notes on C’s history and philosophy, and also includes best-practices I’ve learned over my thirty-five year career. 2. Selected Topics: explains several additional advanced or obscure parts of C that I’ve found not to be explained well elsewhere, if at all. 3. Extended Examples: gives detailed examples with full source code of how fea­ tures in other languages might be implemented including discussion of the trade­ offs involved so you can understand what’s really going on behind the curtain in whatever language you program in. Additionally, there’s an appendix that lists differences between C23 and C17, the previous version of C. Notes to the Reader This book is intended for professional programmers, computer science students, or serious computer hobbyists who either want to learn C or get up-to-date on C23. Consequently, this book assumes familiarity with programming language con­ cepts such as variables, statements, loops, functions, arrays, classes, objects, etc. Though no knowledge of any particular programming language is assumed, a few concepts from C++ are alluded to (not surprisingly). This book also assumes familiarity with algorithm characterization given in “big O” notation in terms of n, the size of the input, the most common of which are: O(1) Constant time: same amount of time regardless of n. O(1g n) Logarithmic time: base-2 logarithm (1g n) time, e.g., 1g 10000 « 13. O(n) Linear time: time proportional to n. This book’s content is presented as fo11ows: • Concepts that are essentia1 for 1earning C are presented norma11y 1ike this. • Commentary, exp1anations for why something is the way it is, historica1 con­ text, and persona1 opinion, i.e., things not essentia1 for 1earning C, but nonethe- 1ess interesting (hopefu11y), are presented as in1ine notes that are indented and bracketed by 1itt1e squares. ■ Like this. □ • Un1ess otherwise noted, cross references 1ike §X, §X.Y, or §X.Y.Z, refer to chap­ ter or appendix X, section X.Y, or subsection X.Y.Z, respective1y, of this book. • Footnotes^ are used for references to other sources. iLike this.
📄 Page 19
xx Preface • Italics are used for one of emphasis (e.g., “. . . is not the same . . .”), for the first occurrences of important concepts (e.g., pointer), an excerpt from or the title of another work (e.g., The C Programming Language), or for Unix manual pages when followed by a digit in parentheses that specifies its section (e.g., grep(1)). • Anything followed by a superscripted asterisk like this means zero or more of the preceding item; anything followed by a superscripted plus like this+ means one or more. * • C constructs are often presented like this: for ( init-expropt ; cond-expropt ; next-expropt ) statement Within such a presentation: - The Courier typeface like this is used for literal text that’s part of a C program. Courier Bold like this is used for C keywords. - Italics like this are also used as placeholders (formally, “non-terminals”) for concepts that are to be replaced by more literal text. - Anything followed by a subscripted opt means it’s optional. • Occasionally, brackets [like this] are used instead ofa subscripted opt to enclose something optional. The source code for many of the examples in this book is freely available online at https://github.com/Apress/Why-Learn-C. Some Preliminary Notes on C The standard for C23 is ISO/IEC 9899:2024^ that describes both the C23 program­ ming language and its standard library. There’s also the related standard of IEEE Std 1003.1-2024, aka, POSIX.1-2024^ (portable operating system interface), henceforth POSIX (“pahz-icks”), that describes a Unix-like operating system, command-line interpreter (aka, “shell”), and common utility programs. POSIX extends the C standard library with both additional functions and ad­ ditional semantics for existing functions. Various operating systems are POSIX- certified or at least “mostly” POSIX-compliant. While this book primarily teaches standard C, it would be a disservice to ignore POSIX due to its significance. The few places in this book that are POSIX-specific are tagged with “[POSIX].” ^Information technology — Programming languages — C, International Organization for Standardization (ISO), ISO/IEC 9899:2024, 2024, https://www.iso.org/standard/82075.html tPOSIX.1-2024, aka, IEEE Std 1003.1-2024, IEEE and The Open Group, 2001-2024, https://pubs.opengroup.org/onlinepubs/9799919799/
📄 Page 20
Preface xxi As described in K&R, C is a general-purpose programming language with a sim­ ple syntax. Part of C’s philosophy^ includes things like: • “Trust the programmer.” That means the compiler assumes you know what you’re doing (even when you don’t). Sometimes, this leads to a core dump. (If you don’t know what that is, you will.) • “Make it fast, even if it’s not guaranteed to be portable.” C prioritizes generating efficient code. By many benchmarks, a program writ­ ten in C runs faster than equivalent programs written in other languages. One of the ways C achieves speed is by leaving many facets of the language implemen­ tation defined meaning that each C compiler generates code for what works best (is fastest) for a particular CPU. Examples include the number of bits comprising an integer and whether characters are signed or unsigned. Consequently, it can be too easy to write non-portable code. That is, it may work perfectly on your machine, but if compiled and run on another machine, it may fail in surprising ways. Despite these things, there are best practices for avoiding bugs and writing portable C code. “C is quirky, flawed, and an enormous success.” — Dennis M. Ritchie Indeed, despite its quirks and flaws, the fact that you’re considering learning C over half a century after its creation should demonstrate its success. Acknowledgments I would like to thank Andrew Brown, Dana Florescu, Mark Musante, Vishal Patel, and especially Simon Tatham for their thoughtful comments, gentle criticisms, and helpful suggestions on drafts of this book. Now, let’s begin. April 2025 Paul J. Lucas t Rationale for International Standard—Programming Languages—C, Revision 5.10, April, 2003, https://www.open-std.org/jtc1/sc22/wg14/www/C99RationaleV5.10.pdf
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List