logo资料库

ModernC.pdf

第1页 / 共320页
第2页 / 共320页
第3页 / 共320页
第4页 / 共320页
第5页 / 共320页
第6页 / 共320页
第7页 / 共320页
第8页 / 共320页
资料共320页,剩余部分请下载后查看
Level 0. Encounter
1. Getting started
1.1. Imperative programming
1.2. Compiling and running
2. The principal structure of a program
2.1. Grammar
2.2. Declarations
2.3. Definitions
2.4. Statements
Level 1. Acquaintance
Warning to experienced C programmers
3. Everything is about control
3.1. Conditional execution
3.2. Iterations
3.3. Multiple selection
4. Expressing computations
4.1. Arithmetic
4.2. Operators that modify objects
4.3. Boolean context
4.4. The ternary or conditional operator
4.5. Evaluation order
5. Basic values and data
5.1. Basic types
5.2. Specifying values
5.3. Initializers
5.4. Named constants
5.5. Binary representions
6. Aggregate data types
6.1. Arrays
6.2. Pointers as opaque types
6.3. Structures
6.4. New names for types: typedef
7. Functions
7.1. Simple functions
7.2. main is special
7.3. Recursion
8. C Library functions
8.1. Mathematics
8.2. Input, output and file manipulation
8.3. String processing and conversion
8.4. Time
8.5. Runtime environment settings
8.6. Program termination and assertions
Level 2. Cognition
9. Style
9.1. Formatting
9.2. Naming
10. Organization and documentation
10.1. Interface documentation
10.2. Implementation
10.3. Macros
10.4. Pure functions
11. Pointers
11.1. Address-of and object-of operators
11.2. Pointer arithmetic
11.3. Pointers and structs
11.4. Opaque structures
11.5. Array and pointer access are the same
11.6. Array and pointer parameters are the same
11.7. Null pointers
11.8. Function pointers
12. The C memory model
12.1. A uniform memory model
12.2. Unions
12.3. Memory and state
12.4. Pointers to unspecific objects
12.5. Implicit and explicit conversions
12.6. Effective Type
12.7. Alignment
13. Allocation, initialization and destruction
13.1. malloc and friends
13.2. Storage duration, lifetime and visibility
13.3. Initialization
13.4. Digression: a machine model
14. More involved use of the C library
14.1. Text processing
14.2. Formatted input
14.3. Extended character sets
14.4. Binary files
15. Error checking and cleanup
Level 3. Experience
16. Performance
Safety first
Optimizers are good enough
Help the compiler
16.1. Inline functions
16.2. Avoid aliasing: restrict qualifiers
16.3. Measurement and inspection
17. Functionlike macros
17.1. how does it work
17.2. Argument checking
17.3. Accessing the calling context
17.4. Variable length argument lists
17.5. Type generic programming
18. Variations in Control Flow
18.1. Sequencing
18.2. Short jumps
18.3. Functions
18.4. Long jumps
18.5. Signal handlers
19. Threads
19.1. Simple inter-thread control
19.2. Thread local data
19.3. Critical data and critical sections
19.4. Communicating through condition variables
19.5. More sophisticated thread management
20. Atomic access and memory consistency
20.1. The ``happend before'' relation
20.2. Synchronizing C library calls
20.3. Sequential consistency
20.4. Other consistency models
Level 4. Ambition
21. The register overhaul
Overview
21.1. Introduce register storage class in file scope
21.2. Typed constants with register storage class and const qualification
21.3. Extend ICE to register constants
21.4. Functions
21.5. Unify designators
22. Improve type generic expression programming
22.1. Storage class for compound literals
22.2. Inferred types for variables and functions
22.3. Anonymous functions
23. Improve the C library
23.1. Make the presence of all C library headers mandatory
23.2. Add requirements for sequence points
23.3. Provide type generic interfaces for string functions
24. Modules
24.1. C needs a specific approach
24.2. All is about naming
24.3. Modular C features
25. Simplify the object and value models
25.1. Remove objects of temporary lifetime
25.2. Introduce comparison operator for object types
25.3. Make memcpy and memcmp consistent
25.4. Enforce representation consistency for _Atomic objects
25.5. Make string literals char const[]
25.6. Default initialize padding to 0
25.7. Make restrict qualification part of the function interface
25.8. References
26. Contexts
26.1. Introduce evaluation contexts in the standard
26.2. Convert object pointers to void* in unspecific context
26.3. Introduce nullptr as a generic null pointer constant and deprecate NULL
List of Rules
Listings
Bibliography
Index
Modern C Jens Gustedt INRIA, FRANCE ICUBE, STRASBOURG, FRANCE Email address: jens gustedt inria fr URL: http://icube-icps.unistra.fr/index.php/Jens_Gustedt This is the version of this book on Feb 13, 2018. It should already contain all material of a final version. You might find a more up to date version at http://icube-icps.unistra.fr/index.php/File:ModernC.pdf (inline) http://icube-icps.unistra.fr/img_auth.php/d/db/ModernC.pdf (download) Special thanks go to the people that encouraged the writing of this book by providing me with constructive feedback, in particular Cédric Bastoul, Lucas Nussbaum, Vincent Loechner, Kliment Yanev, Szabolcs Nagy, Marcin Kowalczuk, Ali Asad Lotia, Richard Palme ... and probably some that I missed to mention. ©2016-2018 Jens Gustedt, Strasbourg, France. This work is licensed under a Creative Commons “Attribution-NonCommercial- NoDerivatives 4.0 International” license.
iii PRELIMINARIES. The C programming language has been around for a long time — the canonical reference for it is the book written by its creators, Kernighan and Ritchie [1978]. Since then, C has been used in an incredible number of applications. Programs and systems written in C are all around us: in personal computers, phones, cameras, set-top boxes, refrigerators, cars, mainframes, satellites, basically in any modern device that has a programmable interface. In contrast to the ubiquitous presence of C programs and systems, good knowledge of and about C is much more scarce. Even experienced C programmers often appear to be stuck in some degree of self-inflicted ignorance about the modern evolution of the C language. A likely reason for this is that C is seen as an "easy to learn" language, allowing a programmer with little experience to quickly write or copy snippets of code that at least appear to do what it’s supposed to. In a way, C fails to motivate its users to climb to higher levels of knowledge. This book is intended to change that general attitude. It is organized in chapters called “Levels” that sum- marize levels of familiarity with the C language and programming in general. Some features of the language are presented in parts on earlier levels, and elaborated in later ones. Most notably, pointers are introduced at Level 1 but only explained in detail at Level 2. This leads to many forward references for impatient readers to follow. As the title of this book suggests, today’s C is not the same language as the one originally designed by its creators Kernighan and Ritchie (usually referred to as K&R C). In particular, it has undergone an important standardization and extension process now driven by ISO, the International Standards Organization. This led to three major publications of C standards in the years 1989, 1999 and 2011, commonly referred to as C89, C99 and C11. The C standards committee puts a lot of effort into guaranteeing backwards compatibility such that code written for earlier versions of the language, say C89, should compile to a semantically equivalent executable with a compiler that implements a newer version. Unfortunately, this backwards compatibility has had the unwanted side effect of not motivating projects that could benefit greatly from the new features to update their code base. In this book we will mainly refer to C11, as defined in JTC1/SC22/WG14 [2011], but at the time of this writing many compilers don’t implement this standard completely. If you want to compile the examples of this book, you will need at least a compiler that implements most of C99. For the changes that C11 adds to C99, using an emulation layer such as my macro package P99 might suffice. The package is available at http: //p99.gforge.inria.fr/. Programming has become a very important cultural and economic activity and C remains an important element in the programming world. As in all human activities, progress in C is driven by many factors, corporate or individual interest, politics, beauty, logic, luck, ignorance, selfishness, ego, sectarianism, ... (add your primary motive here). Thus the development of C has not been and cannot be ideal. It has flaws and artifacts that can only be understood with their historic and societal context. An important part of the context in which C developed was the early appearance of its sister language C++. One common misconception is that C++ evolved from C by adding its particular features. Whereas this is historically correct (C++ evolved from a very early C) it is not particularly relevant today. In fact, C and C++ separated from a common ancestor more than 30 years ago, and have evolved separately ever since. But this evolution of the two languages has not taken place in isolation, they have exchanged and adopted each other’s concepts over the years. Some new features, such as the recent addition of atomics and threads have been designed in a close collaboration between the C and C++ standard committees. Nevertheless, many differences remain and generally all that is said in this book is about C and not C++. Many code examples that are given will not even compile with a C++ compiler. Rule A C and C++ are different, don’t mix them and don’t mix them up. ORGANIZATION. This book is organized in levels. The starting level, encounter, will introduce you to the very basics of programming with C. By the end of it, even if you don’t have much experience in programming, you should be able to understand the structure of simple programs and start writing your own. The acquaintance level details most principal concepts and features such as control structures, data types, operators and functions. It should give you a deeper understanding of the things that are going on when you run your programs. This knowledge should be sufficient for an introductory course in algorithms and other work at that level, with the notable caveat that pointers aren’t fully introduced yet at this level. The cognition level goes to the heart of the C language. It fully explains pointers, familiarizes you with C’s memory model, and allows you to understand most of C’s library interface. Completing this level should enable you to write C code professionally, it therefore begins with an essential discussion about the writing and organization of C programs. I personally would expect anybody who graduated from an engineering school with a major related to computer science or programming in C to master this level. Don’t be satisfied with less. The experience level then goes into detail in specific topics, such as performance, reentrancy, atomicity, threads and type generic programming. These are probably best discovered as you go, that is when you encounter them in the real world. Nevertheless, as a whole they are necessary to round off the picture and to provide you with full expertise in C. Anybody with some years of professional programming in C or who heads a software project that uses C as its main programming language should master this level. Last but not least comes ambition. It discusses my personal ideas for a future development of C. C as it is today has some rough edges and particularities that only have historical justification. I propose possible paths to improve on the lack of general constants, to simplify the memory model, and more generally to improve the modularity of the language. This level is clearly much more specialized than the others, most C programmers can probably live without it, but the curious ones among you could perhaps take up some of the ideas.
Contents Imperative programming Level 0. Encounter 1. Getting started 1.1. 1.2. Compiling and running 2. The principal structure of a program 2.1. Grammar 2.2. Declarations 2.3. Definitions 2.4. Statements Level 1. Acquaintance Iterations Initializers Warning to experienced C programmers 3. Everything is about control 3.1. Conditional execution 3.2. 3.3. Multiple selection 4. Expressing computations 4.1. Arithmetic 4.2. Operators that modify objects 4.3. Boolean context 4.4. The ternary or conditional operator 4.5. Evaluation order 5. Basic values and data 5.1. Basic types 5.2. Specifying values 5.3. 5.4. Named constants 5.5. Binary representions 6. Aggregate data types 6.1. Arrays 6.2. Pointers as opaque types 6.3. Structures 6.4. New names for types: typedef 7. Functions 7.1. Simple functions 7.2. 7.3. Recursion 8. C Library functions 8.1. Mathematics 8.2. 8.3. String processing and conversion 8.4. Time 8.5. Runtime environment settings Input, output and file manipulation main is special v 1 1 1 3 6 6 7 9 10 13 13 15 15 17 20 23 23 26 27 28 29 30 32 34 37 38 42 50 50 55 56 60 62 62 63 65 70 74 74 84 87 91
vi CONTENTS 8.6. Program termination and assertions Level 2. Cognition Interface documentation Implementation 9. Style 9.1. Formatting 9.2. Naming 10. Organization and documentation 10.1. 10.2. 10.3. Macros 10.4. Pure functions 11. Pointers 11.1. Address-of and object-of operators 11.2. Pointer arithmetic 11.3. Pointers and structs 11.4. Opaque structures 11.5. Array and pointer access are the same 11.6. Array and pointer parameters are the same 11.7. Null pointers 11.8. Function pointers 12. The C memory model 12.1. A uniform memory model 12.2. Unions 12.3. Memory and state 12.4. Pointers to unspecific objects 12.5. 12.6. Effective Type 12.7. Alignment 13. Allocation, initialization and destruction 13.1. 13.2. Storage duration, lifetime and visibility 13.3. 13.4. Digression: a machine model 14. More involved use of the C library 14.1. Text processing 14.2. Formatted input 14.3. Extended character sets 14.4. Binary files 15. Error checking and cleanup Implicit and explicit conversions malloc and friends Initialization Inline functions Level 3. Experience 16. Performance Safety first Optimizers are good enough Help the compiler 16.1. 16.2. Avoid aliasing: restrict qualifiers 16.3. Measurement and inspection 17. Functionlike macros 17.1. how does it work 17.2. Argument checking 17.3. Accessing the calling context 17.4. Variable length argument lists 92 95 95 95 96 99 100 103 103 105 106 108 109 112 115 115 116 117 118 121 122 122 124 125 126 127 128 130 131 139 144 146 149 149 155 157 164 165 171 171 171 172 172 173 176 177 183 184 186 189 192
CONTENTS 17.5. Type generic programming 18. Variations in Control Flow 18.1. Sequencing 18.2. Short jumps 18.3. Functions 18.4. Long jumps 18.5. Signal handlers 19. Threads 19.1. Simple inter-thread control 19.2. Thread local data 19.3. Critical data and critical sections 19.4. Communicating through condition variables 19.5. More sophisticated thread management 20. Atomic access and memory consistency 20.1. The “happend before” relation 20.2. Synchronizing C library calls 20.3. Sequential consistency 20.4. Other consistency models Level 4. Ambition Introduce nullptr as a generic null pointer constant and deprecate NULL Improve type generic expression programming Inferred types for variables and functions Improve the C library Introduce register storage class in file scope 21. The register overhaul Overview 21.1. 21.2. Typed constants with register storage class and const qualification 21.3. Extend ICE to register constants 21.4. Functions 21.5. Unify designators 22. 22.1. Storage class for compound literals 22.2. 22.3. Anonymous functions 23. 23.1. Make the presence of all C library headers mandatory 23.2. Add requirements for sequence points 23.3. Provide type generic interfaces for string functions 24. Modules 24.1. C needs a specific approach 24.2. All is about naming 24.3. Modular C features 25. Simplify the object and value models 25.1. Remove objects of temporary lifetime 25.2. 25.3. Make memcpy and memcmp consistent 25.4. Enforce representation consistency for _Atomic objects 25.5. Make string literals char const[] 25.6. Default initialize padding to 0 25.7. Make restrict qualification part of the function interface 25.8. References 26. Contexts 26.1. 26.2. Convert object pointers to void* in unspecific context 26.3. Introduce comparison operator for object types Introduce evaluation contexts in the standard vii 199 206 207 209 212 213 217 225 227 228 229 231 234 236 237 238 239 240 243 244 245 245 246 249 251 253 256 257 258 261 263 263 269 271 274 275 275 276 277 277 277 277 278 278 278 278 279 279 279 279 279
CONTENTS viii List of Rules Listings Bibliography Index 281 292 295 299
分享到:
收藏