官术网_书友最值得收藏!

Preface

Learning to program is the process of learning to solve problems with a computer. Your journey in gaining this knowledge will be long and arduous with unexpected twists and turns, yet the rewards of this journey, both small and large, are manyfold. Initial satisfaction comes when you get your program to work and to give the correct results. Satisfaction grows as you are able to solve larger and more complex problems than you ever thought possible.

The beginning of your journey is learning a programming language. This book primarily addresses that beginning: learning a programming language, in this case, C. The first step in learning a programming language is to learn its syntax. This means understanding and memorizing important keywords, punctuation, and the basic building blocks of program structure.

The approach taken in Learn C Programming is intended to give you the tools, methods, and practices you need to help you minimize the frustrations you will encounter. Every program provided is a complete, working program using modern C syntax. The expected output for each program is also provided.

Learning to program is especially frustrating because there are so many moving parts. By this, I mean that every aspect of the programming process has changed over time and will continue to change in the future. Computer hardware and operating systems will evolve to meet new uses and challenges. Computer languages will also evolve and change to remove old language deficiencies as well as to adapt to solving new problems. The programming practices and methods used today will change as languages evolve. The kinds of problems that need to be solved will also change as people use computers for different uses.And lastly, you will change. As you use a programming language, it will change the way you think about problems. As problems and solutions change, so does our thinking about what will become possible. This leads to changes in computer language. It's a never-ending cycle.

C has evolved considerably from the language first developed by Denis Ritchie in the early 1970s. It was extremely simple yet powerful enough to develop early versions of the Unix operating system at Bell Labs. Those early versions of C were not for novice programmers. Those versions required advanced knowledge and programming skills in order to make programs robust and stable. Over the years, as C compilers became much more widely available, there have been several efforts to rein in unrestricted and sometimes dangerous language features. The first was ANSI C, codified in 1989. The next major refinement came with C99, codified in 1999; it included significant language additions and clarified many C behaviors. Since then, two additional revisions have been made, C11 and C18, both of which have focused on minor language additions and internal corrections to the language.

C today is much more constrained and complex than the early versions of C. Yet it retains its power, performance, and suitability to a wide range of computing problems. This book strives to present the most current syntax and concepts as specified in C99, C11, and C18. Each program has been compiled and run using the C11 standard. As time goes on, C18 compliance will be much more widespread than today. I would expect, however, that all of these programs will compile and run as intended using the C18 standard.

There will always be more to learn, even without the parts moving. After reading Learn C Programming, you will find a particular way to make C work for you. As you gain experience solving problems with C, you will discover new things—features, uses, and limitations—about C that you didn't see before. So, we can say that learning to program is as much about learning how to learn as it is about solving problems with programs.

Along the way, you will learn about other programming concepts not directly tied to the C. The general development cycle will not only be discussed but will also be illustrated in the development of a card dealing program. While you may not be interested in cards, pay particular attention to the process of how this program is developed. Throughout, the basic practices of experimentation and validation will be illustrated.

Who this book is for

When this book was conceived, it was intended for two very diverse audiences, the absolute beginning programmer and the experienced programmer who wants to learn C. Each of these audiences has very different needs.

For the beginning programmer, I have written this book as if I were sitting beside you explaining the most important concepts and practices you need to know to become a successful C programmer. I have tried to explain every concept thoroughly and have reinforced each concept with a working program. The beginner should be familiar with the general operation of their computer; no other knowledge is assumed.

For the experienced programmer, I have presented the full range of C syntax as well as common C idioms. You may skim the explanations and focus primarily upon the source code provided.

For both, there are over 80 working programs that demonstrate both the syntax of C as well as the flavor of C programming idioms—things that are common in C but not found in other languages. I have sprinkled in programming practices and techniques that have served me well in my nearly 35 years of experience.

What this book covers

Section 1, C Fundamentals, introduces the very basic concepts of C syntax and program structure.

Chapter 1, Running Hello, World!,introduces the program development cycle and the tools you'll need for the rest of the book. Those tools are used to create, build, and run your first C program, a "Hello, world!" program. The concepts of commenting code and experimenting with code are also introduced.

Chapter 2, Understanding Program Structure,introduces statements and blocks. It also describes function definitions and function declarations, also known as function prototypes. How functions are called and their order of execution is illustrated. Statements, blocks, and functions define the structure of C programs.

Chapter 3, Working with Basic Data Types,explores how C represents values in various ways through the use of data types. Each data type has a size and possible range of values that C uses to interpret a value.

Chapter 4, Using Variables and Assignment, introduces variables and constants, which are used to contain values. For a variable to receive a value, that value must be assigned to it; several types of assignment are explained.

Chapter 5, Exploring Operators and Expressions, introduces and demonstrates operations—ways to manipulate values—on each of the various data types.

Chapter 6, Exploring Conditional Program Flow, introduces flow of control statements, which execute one group of statements or another depending upon the result of an expression.

Chapter 7, Exploring Loops and Iteration, introduces each of the looping statements. It also describes the proper and improper use ofgoto. Additional means of controller loop iterations are explained.

Chapter 8, Creating and Using Enumerations, explains named constants, enumerations, and how to use them.

Section 2, Complex Data Types, extends your understanding of the concepts of basic, or intrinsic, data types to more complex types.

Chapter 9, Creating and Using Structures, explores how to represent complex objects with groups of variables, called structures. Operations on structures are explored. How structures are related to object-oriented programming is described.

Chapter 10, Creating Custom Data Types with typedef, describes how to rename enum and struct declarations. Compiler options and header files are explored.

Chapter 11, Working with Arrays, illustrates how to define, initialize, and access simple arrays. Using loops to traverse arrays is explored. Operating on arrays via functions is demonstrated.

Chapter 12, Working with Multi-Dimensional Arrays, extends your understanding of the concept of 1-dimensional arrays to 2, 3, and n-dimensional ones. Declaring, initializing, and accessing these multi-dimensional arrays in loops and in functions are demonstrated.

Chapter 13, Using Pointers, explores direct and indirect addressing with pointers. Operations with pointers are demonstrated. How to think and talk about pointers is described. Using pointers in functions and using pointers to structures is demonstrated.

Chapter 14, Understand Arrays and Pointers, explores the similarities and differences between pointers and arrays.

Chapter 15, Working with Strings, introduces the ASCII character set and C strings, which are arrays with two special properties. A program to print the ASCII character set in a table is developed. The C Standard Library string operations are introduced.

Chapter 16, Creating and Using More Complex Structures, builds upon the concepts of structures and arrays to explore how to create various combinations of complex structures. Throughout the chapter, each complex structure is demonstrated through the development of a complete card dealing program. This chapter provides the most comprehensive example of the method of stepwise, iterative program development.

Section 3, Memory Manipulation, explores how memory is allocated and deallocated in a variety of ways.

Chapter 17, Understanding Memory Allocation and Lifetime, introduces the concepts of automatic versus dynamic memory storage classes as well as internal versus external storage classes. The static storage class is demonstrated.

Chapter 18, Using Dynamic Memory Allocation, introduces the use of dynamic memory and describes various operations on dynamic memory. A dynamic linked-list program is demonstrated. An overview of other dynamic structures is provided.

Section 4, Input and Output, explores a wide variety of topics related to the reading (input) and writing (output) of values.

Chapter 19, Exploring Formatted Output, goes into thorough detail about the various format specifiers of printf() for each of the intrinsic data types: signed and unsigned integers, floats and doubles, and strings and characters.

Chapter 20, Getting Input from the Command Line, demonstrates how to use the argc and argv parameters of main() to get values from the command line.

Chapter 21, Exploring Formatted Input, demonstrates how to read values from an input stream usingscanf(). It clarifies how the format specifiers forprintf()andscanf(), while similar, are really very different. Internal data conversion and unformatted input and output are also demonstrated.

Chapter 22, Working with Files, is a largely conceptual chapter that introduces basic file concepts. It demonstrates how to open and close files from within the program and from the command line.

Chapter 23, Using File Input and File Output, demonstrates how to use command-line switches with getopt() to read and write files. The basic program is then expanded to read names from input, sort them via a linked list, and then write them out in sorted order.

Section 5, Building Blocks for Larger Programs, details how to create and manage programs that consist of multiple files.

Chapter 24, Working with Multi-File Programs, demonstrates how to take the single source file program that was developed in Chapter 16, Creating and Using More Complex Structures, and separate it into multiple source files. Each of the source files has functions that are logically grouped by the structures they manipulate. Effective and safe uses for the preprocessor are described.

Chapter 25, Understanding Scope, defines various components of scope and how they related to single- and multi-file programs. Details of variable scope and function scope are described. The epilogue outlines some useful next steps to take in learning both C and programming.

Appendix, provides a number of useful reference guides. These include C keywords, operator precedence, a summary of some useful GCC and CLang options, ASCII characters, using Bstrlib, an overview of Unicode, and an itemization of the C Standard Library.

To get the most out of this book

To use this book, you will need a basic text editor, a terminal or console application, and a compiler. Descriptions of each of these and how to download and use them are provided in Chapter 1, Running Hello, World!. Here are the technical requirements for this book:

To install GCC on certain Linux OSes, follow these steps:

  • If you are running an RPM-based Linux, such as RedHat, Fedora, or CentOS, on the command line in Terminal, enter the following:
$ sudo yum group install development-tools
  • If you are running Debian Linux, on the command line in Terminal, enter the following:
$ sudo apt-get install build-essential

To verify your installation of GCC or Clang for any platform, on the command line in the Terminal, enter the following:

$ cc --version

Whichever version of this book you are using, digital or hard copy, we advise you to type the code yourself. After you do that, you can access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related tothe copying and pasting of code.

If you are an absolute beginner, once you have the necessary development tools, you will need to learn how to read a programming book. If you have taken an algebra course or a calculus course in school, then you will need to approach learning from a programming book in a similar fashion:

  1. Read through the chapter to get an overview of the concepts being presented.
  2. Begin the chapter again, this time typing in each program as you encounter it. Make sure you get the expected output before moving on. If you don't get the expected output, try to figure out what is different in your program from the one given. Learning to program is a lot like learning math—youmustdo the exercises and get the programs to work. You cannot learn to program just by looking at programs; to learn to program, you must program. There is no way around that.
  3. Focus upon memorizing keywords and syntax. This will greatly speed up your learning time.
  1. Be aware that you will need to sharpen the precision of your thinking. Computer language syntax is extremely precise and you will need to pay extra attention to it. You will also have to think much more precisely and in sometimes excruciating detail about the steps needed to solve a particular problem.
  2. Review both the concepts and example programs. Make a note of anything you don't understand.

If you are an experienced programmer who is new to C, I still strongly advise you to first skim the text and examples. Then, enter the programs and get them to work on your system. This will help you to learn C syntax and its idioms more quickly.

I have found that it is important to understand what kind of book you are reading so that you can use it in the most appropriate way. There are several kinds of computer programming books:

  • Conceptual books, which deal with the underlying ideas and motivation for the topics they present. Kernighan and Ritchie'sThe C Programming Languageis one such book.
  • Textbooksthat go through every major area of the language, sometimes in gory detail and usually with a lot of code snippets. Deitel and Deitel's books, as well asC Programming: A Modern Approach, by K. N. King, are examples of these. They are often best used in a formal programming course.
  • Reference books,which describe the specifics of each syntax element.C: A Reference Manual, by Harbison and Steele, is one such book.
  • Cookbooks, which present specific solutions to specific problems in a given language.Advanced C Programming by Example, by Perry, Expert C Programming: Deep Secrets, by Van Der Linden, andAlgorithms in C, by Sedgewick, are examples of these.
  • Topical books, which delve deeply into one or more aspects of a programing language.Pointers in C, by Reek, is one example.
  • Practice books, which deal with how to address programming with C generally.C Interfaces and Implementations, by Hanson, and21st Century C: C Tips from the New School, by Klemens, are two examples of these.

There are different ways to use these books. For instance, read a conceptual book once, but keep a reference book around and use it often. Try to find cookbooks that offer the kinds of programs you are likely to need and use them as needed.

I think of this book as a combination of a C cookbook, a C reference book, and a C practice book. All of the programs are working examples that can be used to verify how your compiler behaves on your system. Enough of the C language has been included that it may also be used as afirst approximationreference. Throughout, my intent has been to show good programming practice with C.

I would expect that Learn C Programmingwill not be your last book on C. When you consider other C books, be sure that they pertain to C99 at a minimum; ideally, they should include C11 or C18. Most C code before C99 is definitely old school; more effective programming practices and methods have been developed since before C99.

Download the example code files

You can download the example code files for this book from your account atwww.packt.com. If you purchased this book elsewhere, you can visitwww.packtpub.com/supportand register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register atwww.packt.com.
  2. Select theSupporttab.
  3. Click onCode Downloads.
  4. Enter the name of the book in theSearchbox and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR/7-Zip for Windows
  • Zipeg/iZip/UnRarX for Mac
  • 7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Learn-C-Programming. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here:https://static.packt-cdn.com/downloads/9781789349917_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText:Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles.Here is an example:"As a hint, this pairing involves the lines int main() and return 0;"

A block of code is set as follows:

#include <stdio.h>

int main()
{
printf( "Hello, world!\n" );
return 0;
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

#include <stdio.h>

int main()
{
printf( "Hello, world!\n" );
return 0;
}

Any command-line input or output is written as follows:

          $ cc hello6.c
        

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "This program is useful because it prints something out to the Terminal, also known as the console."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book,mention the book title in the subject of your message and email us atcustomercare@packtpub.com.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visitwww.packtpub.com/support/errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us atcopyright@packt.comwith a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visitauthors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

主站蜘蛛池模板: 汉中市| 砀山县| 呼图壁县| 鹤山市| 醴陵市| 嘉祥县| 瑞昌市| 灵石县| 毕节市| 莱阳市| 霍城县| 个旧市| 威海市| 汽车| 关岭| 江安县| 泗洪县| 清河县| 新丰县| 娄底市| 津市市| 右玉县| 汉源县| 通海县| 巴彦淖尔市| 都兰县| 安福县| 安丘市| 政和县| 奉新县| 平原县| 孟津县| 怀化市| 嘉黎县| 上高县| 萍乡市| 长汀县| 扎鲁特旗| 岳阳市| 北碚区| 武宣县|