Reader small image

You're reading from  Learn C Programming. - Second Edition

Product typeBook
Published inAug 2022
PublisherPackt
ISBN-139781801078450
Edition2nd Edition
Right arrow
Author (1)
Jeff Szuhay
Jeff Szuhay
author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay

Right arrow

Preface to the Second Edition

In the Preface to the First Edition, I stated that "you will find a particular way to make C work for you." I must admit that I myself was a victim of this trap. It turns out that because I had learned C before 1990, I was not as familiar with important C99 features as I should have been. I was guilty of thinking with my older C version habits. This outdated thinking was reflected largely in the chapter on enumerations and especially in the chapter introducing arrays, where Variable-Length Arrays (VLAs) – a major feature of C99 – were poorly covered. Both of these chapters have been completely rewritten to accurately represent the C standard.

I especially want to thank readers who pointed out the various text and source code typos. I understand how frustrating it can be when the code you use from the book just won't work. For this reason, extra attention has been given to the source code in the book and the example programs in the repository.

This edition corrects those typographical errors both in the text and in the sample code. It also corrects some conceptual errors that were either poorly described or just plain wrong. I offer my sincerest apologies to the readers of that edition. Any errors that remain are purely my responsibility.

This edition, as much as possible, provides some hints as to what is to come in the next version of the C standard – C23. These are added refinements that do not change the core of C but extend the clarity and usefulness of C.

Another addition to this version is the questions at the end of each chapter to reinforce the key concepts of that chapter. These should prove to be especially useful to programming beginners.

Finally, Chapter 27 has been added, which implements two complete yet simple card games. These demonstrate how to use pre-built structures and functions as well as how to employ a library, in this case. our own linked list library, for added functionality.

Preface to the First Edition

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 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 and also adapt to solve 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 Dennis 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 C17, 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 for a wide range of computing problems. This book strives to present the most current syntax and concepts as specified in C99, C11, and C17. Each program has been compiled and run using the C11 standard. As time goes on, C17 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 C17 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 in 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 C. The general development cycle will not only be discussed but also 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 programming beginner and the experienced programmer who wants to learn C. Each of these audiences has very different needs.

For the programming beginner, 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 on the source code provided. The programs are intended to provide a reference to C syntax.

For both, there are over 100 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

Part 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 Assignments, 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 the flow of control statements, which execute one group of statements or another, depending on the result of an expression.

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

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

Part 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 one-dimensional arrays to two-, three-, and n-dimensional ones. Declaring, initializing, and accessing these multi-dimensional arrays in loops and 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, Understanding 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.

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

Part 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 usethe 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 using scanf(). It clarifies how the format specifiers for printf() and scanf(), 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 a 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.

Part 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 relate to single- and multi-file programs. Details of variable scope and function scope are described.

Chapter 26, Building Multi-File Programs with make, introduces basic features of the make utility. make is then used to build a multi-file program. A general-purpose makefile is developed.

Chapter 27, Creating Two Card Programs, starts with the dealer program developed in Chapter 16, Creating and Using More Complex Structures, to create two different yet complete and playable card games: Blackjack, or 21, and One-Handed Solitaire. The user interface is limited to the command-line entry of characters.

The Epilogue outlines some useful next steps to take in learning both C and programming.

The 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, a brief overview of Unicode, an annotated history of C versions, 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:

All of the software given in the table are either built into the operating system or are free to download.

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

  • If you are running an RPM-based Linux, such as Red Hat, 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 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 to the 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 – you must do 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 on memorizing keywords and syntax. This will greatly speed up your learning time.
  4. Be aware that you will need to sharpen the precision of your thinking. The syntax of computer language 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.
  5. 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 most appropriately. 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's The C Programming Language and Effective C: An Introduction to Professional C Programming, by Seacord, are two such books.
  • Textbooks, which 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 as C 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, and Algorithms 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, and 21st 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. This is not intended to be a textbook. 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 a first-approximation reference. Throughout, my intent has been to show good programming practice with C.

I expect that Learn C Programming will 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, C17, or C23. Most C code before C99 is definitely old-school; more effective programming practices and methods have been developed since C99 and before.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Learn-C-Programming-Second-Edition. If there's an update to the code, it will be updated in the GitHub repository.

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

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/uDSeu

Conventions used

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

Code in text: 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: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

html, body, #map {
 height: 100%; 
 margin: 0;
 padding: 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:

[default]
exten => s,1,Dial(Zap/1|30)
exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)

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

$ mkdir css
$ cd css

Tips or Important Notes

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, email us at customercare@packtpub.com and mention the book title in the subject of your message.

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 visit www.packtpub.com/support/errata and fill in the form.

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 at copyright@packt.com with 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 visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read Learn C Programming, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn C Programming. - Second Edition
Published in: Aug 2022Publisher: PacktISBN-13: 9781801078450
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Jeff Szuhay

Jeff Szuhay is the principal developer at QuarterTil2 which specializes in graphics-rich software chronographs for desktop environments. In his software career of over 35 years, he has engaged in a full range of development activities from systems analysis and systems performance tuning to application design, from initial development through full testing and final delivery. Throughout that time, he has taught computer applications and programming languages at various educational levels from elementary school students to university students, as well as developed and presented professional, on-site training.
Read more about Jeff Szuhay