Professional Documents
Culture Documents
Beginning C
From Beginner to Pro
7th ed.
German Gonzalez-Morris
Santiago, Chile
Ivor Horton
STRATFORD UPON AVON, UK
This work is subject to copyright. All rights are solely and exclusively
licensed 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.
The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
This Apress imprint is published by the registered company APress
Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
To my family, Patricia, Raimundo, and Gregorio
—German Gonzalez-Morris
In memory of my beautiful wife, Eve
—Ivor Horton
Introduction
Welcome to Beginning C: From Beginner to Pro, Seventh Edition. With
this book, you can become a competent C programmer using the latest
version of the C language. In many ways, C is an ideal language with
which to learn programming. It’s very compact, so there isn’t a lot of
syntax to learn before you can write real applications. In spite of its
conciseness, it’s extremely powerful and is used by professionals in
many different areas. The power of C is such that it can be applied at all
levels, from developing device drivers and operating system
components to creating large-scale applications. A relatively new area
for C is in application development for mobile phones.
C compilers are available for virtually every kind of computer, so
when you’ve learned C, you’ll be equipped to program in just about any
context. Once you know C, you have an excellent base from which you
can build an understanding of the object-oriented C++.
My objective in this book is to minimize what I think are the three
main hurdles the aspiring programmer must face: coming to grips with
the jargon that pervades every programming language, understanding
how to use the language elements (as opposed to merely knowing what
they are), and appreciating how the language is applied in a practical
context.
Jargon is an invaluable and virtually indispensable means of
communication for the expert professional as well as the competent
amateur, so it can’t be avoided. My approach is to ensure that you
understand the jargon and get comfortable using it in context. In this
way, you’ll be able to more effectively use the documentation that
comes along with the typical programming product and also feel
comfortable reading and learning from the literature that surrounds
most programming languages.
Comprehending the syntax and effects of the language elements is
obviously an essential part of learning C, but appreciating how the
language features work and how they are used is equally important.
Rather than just using code fragments, I provide you with practical
working examples in each chapter that show how the language features
can be applied to specific problems. These examples provide a basis for
you to experiment and see the effects of changing the code.
Your understanding of programming in context needs to go beyond
the mechanics of applying individual language elements. To help you
gain this understanding, I conclude most chapters with a more complex
program that applies what you’ve learned in the chapter. These
programs will help you gain the competence and confidence to develop
your own applications and provide you with insight into how you can
apply language elements in combination and on a larger scale. Most
importantly, they’ll give you an idea of what’s involved in designing real
programs and managing real code.
The book’s spirit is to start from a beginner and finish as a pro.
Nevertheless, as usual, technology is broad and complex for each part
of the knowledge. Therefore, there is always a space to learn more
profoundly about each topic. I encourage you to keep learning and
researching each aspect you find more interesting (new knowledge is
always good).
It’s important to realize a few things that are true for learning any
programming language. First, there is quite a lot to learn, but this
means you’ll gain a greater sense of satisfaction when you’ve mastered
it. Second, it’s great fun, so you really will enjoy it. Third, you can only
learn programming by doing it, and this book helps you along the way.
Finally, it’s certain you will make a lot of mistakes and get frustrated
from time to time during the learning process. When you think you are
completely stuck, you just need to be persistent. You will eventually
experience that eureka moment and realize it wasn’t as difficult as you
thought.
Conventions Used
I use a number of different styles of text and layout in the book to help
differentiate between the different kinds of information. For the most
part, their meanings will be obvious. Program code will appear like
this:
int main(void)
{
printf("Beginning C\n");
return 0;
}
When a code fragment is a modified version of a previous instance, I
occasionally show the lines that have changed in bold type like this:
int main(void)
{
printf("Beginning C by Ivor Horton & German
Gonzalez-Morris\n");
return 0;
}
When code appears in the text, it has a different typestyle that looks
like this: double.
I’ll use different types of “brackets” in the program code. They aren’t
interchangeable, and their differences are very important. I’ll refer to
the symbols ( ) as parentheses, the symbols { } as braces, and the
symbols [ ] as square brackets.
Important new words in the text are shown in italic like this.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub via the book’s
product page, located at www.apress.com/9781484259757. For
more detailed information, please visit www.apress.com/source-
code.
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.
Acknowledgments
I am profoundly grateful to Patricia Cruces, my life partner, whose
infinite patience, unwavering support, and boundless love have been
my constant companions through every challenge and triumph. Her
presence has been a source of inspiration, making this journey more
meaningful and fulfilling.
To my sons, Raimundo and Gregorio, I owe immeasurable thanks for
being the bright sparks of joy and inspiration in my life. Your happiness
reminds me of what truly matters, and your enthusiasm fills me with
determination.
To my parents, Germá n and Felicia Morris, who have been my pillars
of strength, providing both love and guidance and invaluable
educational opportunities.
To my friend Daniel Lagos, a great engineer, whose constructive
criticism, suggestions, exchange of ideas, and feedback have not only
helped my understanding with his input but have inspired me to
explore alternative approaches and support continuous improvement.
I appreciate the collaborative spirit demonstrated by my university
classmates Alejandro Cuevas and Fernando Castillo, as their diverse
perspectives have contributed to more comprehensive, real-world
examples and practical applications, particularly to my lessons on C
language pointers.
I am grateful for the support and opportunities provided to me by
the entire Apress team, especially Melissa Duffy and Sowmya Thodur.
Their guidance and advice have been invaluable. I also want to thank
Megan Hirni, the technical reviewer, for her clever feedback,
suggestions, and corrections.
—German Gonzalez-Morris
Table of Contents
Chapter 1:Programming in C
The C Language
The Standard Library
Learning C
Creating C Programs
Editing
Compiling
Linking
Executing
Creating Your First Program
Editing Your First Program
Dealing with Errors
Dissecting a Simple Program
Comments
Preprocessing Directives
Defining the main() Function
Keywords
The Body of a Function
Outputting Information
Function Arguments
Control Characters
Trigraph Sequences
The Preprocessor
Developing Programs in C
Understanding the Problem
Detailed Design
Implementation
Testing
Functions and Modular Programming
Common Mistakes
Points to Remember
Summary
Chapter 2:First Steps in Programming
Memory in Your Computer
What Is a Variable?
Naming Variables
Variables That Store Integers
Using Variables
Initializing Variables
More on Division with Integers
Unary Operators
Unary Minus Operator
Variables and Memory
Signed Integer Types
Unsigned Integer Types
Specifying Integer Constants
Binary Integer Constants
Working with Floating-Point Numbers
Floating-Point Number Representation
Floating-Point Variables
Division Using Floating-Point Values
Controlling the Number of Decimal Places in the Output
Controlling the Output Field Width
More Complicated Expressions
Checked Integer Arithmetic
constexpr
Defining Named Constants
Knowing Your Limitations
Introducing the sizeof Operator
Choosing the Correct Type for the Job
Explicit Type Conversion
Automatic Conversions
Rules for Implicit Conversions
Implicit Conversions in Assignment Statements
Type Inference
typeof
More Numeric Data Types
Character Type
Character Input and Character Output
Enumerations
Choosing Enumerator Values
Unnamed Enumeration Types
Variables That Store Boolean Values
The op=Form of Assignment
Mathematical Functions
Designing a Program
The Problem
The Analysis
The Solution
Summary
Chapter 3:Making Decisions
The Decision-Making Process
Arithmetic Comparisons
The Basic if Statement
Extending the if Statement:if-else
Using Blocks of Code in if Statements
Nested if Statements
Testing Characters
Logical Operators
The Conditional Operator
Operator Precedence:Who Goes First?
Multiple-Choice Questions
Using else-if Statements for Multiple Choices
The switch Statement
The goto Statement
Bitwise Operators
The op=Use of Bitwise Operators
Using Bitwise Operators
Bit-Precise Integers
Modern Bit Utilities
Designing a Program
The Problem
The Analysis
The Solution
Summary
Chapter 4:Loops
How Loops Work
Introducing the Increment and Decrement Operators
The for Loop
General Form of the for Loop
More on the Increment and Decrement Operators
The Increment Operator
The Prefix and Postfix Forms of the Increment Operator
The Decrement Operator
The for Loop Revisited
Modifying the for Loop Control Variable
A for Loop with No Parameters
The break Statement in a Loop
Limiting Input Using a for Loop
Generating Pseudo-random Integers
More for Loop Control Options
Floating-Point Loop Control Variables
Chars loop Control Variables
The while Loop
Nested Loops
Nested Loops and the goto Statement
The do-while Loop
The continue Statement
Designing a Program
The Problem
The Analysis
The Solution
Summary
Chapter 5:Arrays
An Introduction to Arrays
Programming Without Arrays
What Is an Array?
Using an Array
The Address of Operator
Arrays and Addresses
Initializing an Array
Compound Literal
Finding the Size of an Array
MultidimensionalArrays
Initializing MultidimensionalArrays
Constant Arrays
Variable-Length Arrays
Designing a Program
The Problem
The Analysis
The Solution
Summary
Chapter 6:Applications with Strings and Text
What Is a String?
Variables That Store Strings
Arrays of Strings
Operations with Strings
Checking for C11/C23 Support
Finding the Length of a String
Copying Strings
Concatenating Strings
Comparing Strings
Searching a String
Tokenizing a String
Reading Newline Characters into a String
Analyzing and Transforming Strings
Converting Character Case
Converting Strings to Numerical Values
Designing a Program
The Problem
The Analysis
The Solution
Summary
Chapter 7:Pointers
A First Look at Pointers
Declaring Pointers
Accessing a Value Through a Pointer
Using Pointers
Testing for a NULL Pointer
Pointers to Constants
Constant Pointers
Naming Pointers
Arrays and Pointers
MultidimensionalArrays
MultidimensionalArrays and Pointers
Accessing Array Elements
Using Memory As You Go
Dynamic Memory Allocation:The malloc() Function
Releasing Dynamically Allocated Memory
Memory Allocation with the calloc() Function
Extending Dynamically Allocated Memory
Handling Strings Using Pointers
Using Arrays of Pointers
Pointers and Array Notation
Designing a Program
The Problem
The Analysis
The Solution
The Complete Program
Summary
Chapter 8:Structuring Your Programs
Program Structure
Variable Scope and Lifetime
Variable Scope and Functions
Storage classes
Functions
Defining a Function
The return Statement
The Pass-by-Value Mechanism
Function Prototypes
Pointers As Parameters and Return Types
const Parameters
Perils of Returning Pointers
Summary
Chapter 9:More on Functions
Pointers to Functions
Declaring a Pointer to a Function
Calling a Function Through a Function Pointer
Arrays of Pointers to Functions
Pointers to Functions As Arguments
Variables in Functions
Static Variables:Keeping Track Within a Function
Sharing Variables Between Functions
Functions That Call Themselves:Recursion
Functions with a Variable Number of Arguments
Copying a va_list
Basic Rules for Variable-Length Argument Lists
The main( ) Function
Terminating a Program
The abort() Function
The exit() and atexit() Functions
The _Exit() Function
The quick_exit() and at_quick_exit() Functions
Enhancing Performance
Declaring Functions Inline
Using the restrict Keyword
The _Noreturn Function Specifier
Attributes
Designing a Program
The Problem
The Analysis
The Solution
Summary
Chapter 10:Essential Input and Output
Input and Output Streams
Standard Streams
Input from the Keyboard
Formatted Keyboard Input
Input Format Control Strings
Characters in the Input Format String
Variations on Floating-Point Input
Reading Hexadecimal and Octal Values
Reading Characters Using scanf_s()
String Input from the Keyboard
Single-Character Keyboard Input
Output to the Screen
Formatted Output Using printf_s()
Escape Sequences
Integer Output
Outputting Floating-Point Values
Character Output
Other Output Functions
Unformatted Output to the Screen
Formatted Output to an Array
Formatted Input from an Array
Summary
Chapter 11:Structuring Data
Data Structures:Using struct
Defining Structure Types and Structure Variables
Accessing Structure Members
Unnamed Structures
Arrays of Structures
Structure Members in Expressions
Pointers to Structures
Dynamic Memory Allocation for Structures
More on Structure Members
Structures As Members of a Structure
Declaring a Structure Within a Structure
Pointers to Structures As Structure Members
Doubly Linked Lists
Bit Fields in a Structure
Structures and Functions
Structures As Arguments to Functions
Pointers to Structures As Function Arguments
Structure As a Function Return Value
Binary Trees
Sharing Memory
Designing a Program
The Problem
The Analysis
The Solution
Summary
Chapter 12:Working with Files
The Concept of a File
Positions in a File
File Streams
Accessing Files
Opening a File
Buffering File Operations
Renaming a File
Closing a File
Deleting a File
Writing a Text File
Reading a Text File
Reading and Writing Strings to a Text File
Formatted File Input and Output
Formatted Output to a File
Formatted Input from a File
Dealing with Errors
More Open Modes for Text Files
The freopen_s( ) Function
Binary File Input and Output
Opening a File in Binary Mode
Writing a Binary File
Reading a Binary File
Moving Around in a File
File Positioning Operations
Finding Out Where You Are
Setting a Position in a File
Using Temporary Work Files
Creating a Temporary Work File
Creating a Unique File Name
Updating Binary Files
Changing the Contents of a File
Creating a Record from Keyboard Input
Writing a Record to a File
Reading a Record from a File
Writing a File
Listing the File Contents
Updating the Existing File Contents
File Open Mode Summary
Designing a Program
The Problem
The Analysis
The Solution
Summary
Chapter 13:The Preprocessor and Debugging
Preprocessing
Including Header Files
Defining Your Own Header Files
Managing Multiple Source Files
External Variables
Static Functions
Substitutions in Your Program Source Code
Macros
Macros That Look Like Functions
Strings As Macro Arguments
Joining Two Arguments in a Macro Expansion
Preprocessor Directives on Multiple Lines
Logical Preprocessor Directives
Conditional Compilation
Testing for Multiple Conditions
Undefining Identifiers
Testing for Specific Values for Identifiers
Multiple-Choice Selections
Standard Preprocessing Macros
_Generic Macro
The Unreachable Macro
Debugging Methods
Integrated Debuggers
The Preprocessor in Debugging
Assertions
Date and Time Functions
Getting Time Values
Getting the Date
Getting the Day for a Date
Summary
Chapter 14:Advanced and Specialized Topics
Working with International Character Sets
Understanding Unicode
Setting the Locale
The Wide Character Type wchar_t
Operations on Wide Character Strings
File Stream Operations with Wide Characters
Fixed Size Types That Store Unicode Characters
Specialized Integer Types for Portability
Fixed-Width Integer Types
Minimum-Width Integer Types
Maximum-Width Integer Types
The Complex Number Types
Complex Number Basics
Complex Types and Operations
Programming with Threads
Creating a Thread
Exiting a Thread
Joining One Thread to Another
Suspending a Thread
Managing Thread Access to Data
Summary
Appendix A:Computer Arithmetic
Appendix B:ASCII Character Code Definitions
Appendix C:Reserved Words in C
Appendix D:Input and Output Format Specifications
Appendix E:Standard Library Header Files
Index
About the Authors
German Gonzalez-Morris
is a polyglot software architect/engineer
with 20+ years in the field, with
knowledge in Java, SpringBoot, C/C++,
Julia, Python, Haskell, and JavaScript,
among others. He works for cloud
(architecture), web-distributed
applications, and microservices. German
loves math puzzles (including reading
Knuth, proud of solving some of Don’s
puzzles), swimming, and table tennis.
Also, he has reviewed several books,
including those on application
containers (WebLogic) and languages (C,
Java, Spring, Python, Haskell, TypeScript,
WebAssembly, Math for coders, regexp,
Julia, data structures, and algorithms).
You can see details on his blog
(https://devwebcl.blogspot.com/) or X/Twitter account
(@devwebcl)
Ivor Horton
is self-employed in consultancy and writes programming tutorials. He
worked for IBM for many years and holds a bachelor’s degree, with
honors, in mathematics. Ivor’s experience at IBM includes
programming in most languages (such as assembler and high-level
languages on a variety of machines), real-time programming, and
designing and implementing real-time closed-loop industrial control
systems. He has extensive experience teaching programming to
engineers and scientists (Fortran, PL/1, APL, etc.). Ivor is an expert in
mechanical, process, and electronic CAD systems; mechanical CAM
systems; and DNC/CNC systems.
Another random document with
no related content on Scribd:
"It is probably unknown to the inhabitants of the Transvaal
and Orange River Colony that nearly 15,000 of their
fellow-subjects are now prisoners of war, not one of whom will
be released until those now in arms against us surrender
unconditionally. The burghers must by this time be cognisant
of the fact that no intervention on their behalf can come from
any of the Great Powers, and, further, that the British Empire
is determined to complete the work which has already cost her
so many valuable lives, and to carry to its conclusion the war
declared against her by the late Governments of the South
African Republic and Orange Free State, a war to which there
can be but one ending. If any further doubts remain in the
minds of the burghers as to Her Britannic Majesty's
intentions, they should be dispelled by the permanent manner
in which the country is gradually being occupied by Her
Majesty's Forces, and by the issue of the Proclamations signed
by me on the 24th May and 1st September 1900, annexing the
Orange Free State and the South African Republic respectively,
in the name of Her Majesty.
{508}
{509}
|NON-COMMISSIONED
OFFICERS AND MEN.
OFFICERS|CAVALRY|ARTILLERY|INFANTRY|OTHERS|TOTAL|
TOTAL
AND
OFFICERS
INFANTRY
-------------------------------------------------
----------------------------
I. Garrison on
Aug. 1, 1899 318 1,127 1,035
6,428 1,032 9,622 9,940
-------------------------------------------------
----------------------------
II.
Reinforcements,
Aug. 1, 1899,
to Oct. 11, 1899
(outbreak of war)
-------------------------------------------------
-----------------------------
539 1,564 1,396
9,047 … 12,007 12,546
-------------------------------------------------
-----------------------------
III. Further
reinforcements
from Oct. 11,
1899, to end
of July, 1900
Regulars
(1.) From Home
and Colonies. 5,748 11,003 14,145
110,292 14,347 149,787 155,535
(2.) From India. 132 713 376
670 … 1,759 1,891
-------------------------------------------------
-----------------------------
5,880 11,716 14,521
110,962 14,347 151,546 157,426
-------------------------------------------------
-----------------------------
Colonials
(1.) From Colonies
other than
South African. 550 287 692
9,788 267 11,034 11,584
(2.) Raised in
South Africa. 1,387 … …
… … 28,932 30,319
-------------------------------------------------
------------------------------
1,937 … …
… … 39,966 41,903
-------------------------------------------------
------------------------------
-------------------------------------------------
-------------------------------
-------------------------------------------------
-------------------------------
IV. Further
reinforcements
from Aug. 1, 1900,
to Jan. 31, 1901
(1.) Regulars 820 3,213 652
10,439 975 15,279 16,099
(2.) Militia 7 … …
1,141 … 1,141 1,148
-------------------------------------------------
-------------------------------
11,210 … …
… … 271,169 282,379
-------------------------------------------------
-------------------------------
{510}
Officers Cavalry.
Artillery. Infantry Others. Total. Total
and Officers
Infantry
V. Numbers
(1.) Killed to
Jan. 31, 1901 334.
3,346 3,680
(2.) Wounded to
Jan 31, 1901. 1,242.
14,914 16,156
(3.) Died of disease
or wounds or accidentally
killed in South Africa
to Jan. 31, 1001. 301.
9,008 9,309
(4.) Disbanded and
discharged in South Africa. 299.
5,231 5,530
(5.) In hospital in South
Africa on Dec. 28, 1900
(latest returns). 415.
13,716 14,131
VI. Numbers left
South Africa
(1.) For England
not invalids. 1,214
11,109 12,323
(2.) For England
sick, wounded, and
died on passage 1,703
39,095 40,198
(3.) Returned to India
direct from South Africa. 20
70 90
(4.) Returned to Colonies
direct from South Africa
(a) Regulars, including two
battalions to Ceylon. 98
2,041 2,139
(b) Colonials. 177
3,384 3,561
TOTAL 7,064
197,885 204,949*
* Exclusive of recently raised Colonials whose numbers have not yet been
reported.
"From the moment when the invasion took place, and the first
shot was fired by the Boers, from that moment we declared our
policy, that not one shred of the independence which the Boers
had abused should ever again be conceded to them. That was the
policy stated by the Prime Minister in his answer to the
representations which were made to him by the Presidents of
the two Republics. That was the policy, is the policy, and
will be the policy of His Majesty's Government to the end. Let
there be no mistake about that. It is no use arguing with us
on the subject of independence. That, as far as we are
concerned, is a closed question. Raise it, if you like to
raise it, not in speeches, but by amendments. We are quite
ready. We challenged you at the last election. You have never
ceased to complain of the challenge. We challenge you in the
House of Commons. If you believe the annexation we have
announced ought to be repudiated; if you think, with the
honorable and learned gentleman who has just spoken, that we
ought to restore the independence of these two Republics, in
any form, it is for you to say so in a definite amendment. It
is for you to put the issue before the House of Commons and
the country and we are perfectly prepared to meet you.
Assuming that we are all agreed that annexation cannot be
undone, then the policy of the Government is to establish
equality and protection and justice for the native population
and to grant the fuller liberties involved in our definition
of self-government as soon as that can safely be conceded. …
The Boers know perfectly well, they have been told again and
again, directly and indirectly, and it has been repeatedly
stated in this House that at the earliest possible moment they
will be granted self-government."
{511}
"I arranged with him that I should write and let him know the
view of the Government on these points. All I said during the
interview was qualified by being subject to confirmation from
home. He was anxious to get an answer soon."