22,99 €
Get an A grade in C As with any major language, mastery of C can take you to some very interesting new places. Almost 50 years after it first appeared, it's still the world's most popular programming language and is used as the basis of global industry's core systems, including operating systems, high-performance graphics applications, and microcontrollers. This means that fluent C users are in big demand at the sharp end in cutting-edge industries--such as gaming, app development, telecommunications, engineering, and even animation--to translate innovative ideas into a smoothly functioning reality. To help you get to where you want to go with C, this 2nd edition of C Programming For Dummies covers everything you need to begin writing programs, guiding you logically through the development cycle: from initial design and testing to deployment and live iteration. By the end you'll be au fait with the do's and don'ts of good clean writing and easily able to produce the basic--and not-so-basic--building blocks of an elegant and efficient source code. * Write and compile source code * Link code to create the executable program * Debug and optimize your code * Avoid common mistakes Whatever your destination: tech industry, start-up, or just developing for pleasure at home, this easy-to-follow, informative, and entertaining guide to the C programming language is the fastest and friendliest way to get there!
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 512
C Programming For Dummies®, 2nd Edition
Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com
Copyright © 2021 by John Wiley & Sons, Inc., Hoboken, New Jersey
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions.
Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit https://hub.wiley.com/community/support/dummies.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport.wiley.com. For more information about Wiley products, visit www.wiley.com.
Library of Congress Control Number: 2020945155
ISBN: 978-1-119-74024-7; 978-1-119-74025-4 (ebk); 978-1-119-74026-1 (ebk)
Cover
Title Page
Copyright Page
Introduction
Why the C Language?
The C Programming For Dummies Approach
How This Book Works
Icons Used in This Book
Parting Thoughts
Part 1: The ABs of C
Chapter 1: A Quick Start for the Impatient
What You Need to Program
Command Prompt Programming
IDE Programming
Your First Program
Chapter 2: The Programming Thing
The History of Programming
The Programming Process
Chapter 3: Anatomy of C
Parts of the C Language
Behold the Typical C Program
Part 2: C Programming 101
Chapter 4: Trials and Errors
Display Stuff on the Screen
More Text Output Nonsense
Chapter 5: Values and Simple Math
A Venue for Various Values
The Computer Does the Math
Chapter 6: A Place to Put Stuff
Values That Vary
Variable Madness!
Constants Always the Same
Chapter 7: Input and Output
Character I/O
Text I/O, but Mostly I
Chapter 8: Decision Making
What If?
Multiple Decisions
Multiple Comparisons with Logic
The Old
Switch Case
Trick
The Weird ?: Decision Thing
Chapter 9: Loops, Loops, Loops
A Little Déjà Vu
The Thrill of
for
Loops
The Joy of the
while
Loop
Loopy Stuff
Chapter 10: Fun with Functions
Anatomy of a Function
Functions and Variables
Constants of the Global Kind
Part 3: Build Upon What You Know
Chapter 11: The Unavoidable Math Chapter
Math Operators from Beyond Infinity
Math Function Mania
It’s Totally Random
The Holy Order of Precedence
Chapter 12: Give Me Arrays
Behold the Array
Multidimensional Arrays
Arrays and Functions
Chapter 13: Fun with Text
Character Manipulation Functions
String Functions Galore
Fun with
printf()
Formatting
Gently Down the Stream
Chapter 14: Structures, the Multivariable
Hello, Structure
Weird Structure Concepts
Chapter 15: Life at the Command Prompt
Conjure a Terminal Window
Arguments for the
main()
Function
Time to Bail
Chapter 16: Variable Nonsense
Variable Control
Variables, Variables Everywhere
Chapter 17: Binary Mania
Binary Basics
Bit Manipulation
The Joy of Hex
Part 4: The Advanced Part
Chapter 18: Introduction to Pointers
The Biggest Problem with Pointers
Sizing Up Variable Storage
The Hideously Complex Topic of Pointers
Chapter 19: Deep into Pointer Land
Pointers and Arrays
Strings Are Pointer-Things
Pointers in Functions
Chapter 20: Memory Chunks and Linked Lists
Give Me Memory!
Lists That Link
Chapter 21: It’s About Time
What Time Is It?
Time to Program
Part 5: And the Rest of It
Chapter 22: Permanent Storage Functions
Sequential File Access
Random File Access
Chapter 23: File Management
Directory Madness
Fun with Files
Chapter 24: Beyond Mere Mortal Projects
The Multi-Module Monster
Other Libraries to Link
Chapter 25: Out, Bugs!
Simple Tricks to Resolve Problems
The Debugger
Improved Error Messages
Part 6: The Part of Tens
Chapter 26: Ten Common Boo-Boos
Conditional Foul-Ups
Dangerous Loop Semicolons
Commas in
for
Loops
Missing break in a switch Structure
Missing Parentheses and Curly Brackets
Don’t Ignore a Warning
Endless Loops
scanf()
Blunders
Streaming Input Restrictions
Chapter 27: Ten Reminders and Suggestions
Maintain Good Posture
Use Creative Names
Write a Function
Work on Your Code a Little Bit at a Time
Break Apart Larger Projects into Several Modules
Know What a Pointer Is
Add Whitespace before Condensing
Know When
if-else
Becomes
switch-case
Remember Assignment Operators
When You Get Stuck, Read Your Code Out Loud
Part 7: Appendices
Appendix A: ASCII Codes
Appendix B: Keywords
Appendix C: Operators
Appendix D: Data Types
Appendix E: Escape Sequences
Appendix F: Conversion Characters
Appendix G: Order of Precedence
Index
About the Author
Connect with Dummies
End User License Agreement
Chapter 3
TABLE 3-1 C Language Keywords
Chapter 4
TABLE 4-1: Escape Sequences
Chapter 5
TABLE 5-1: Basic Math Operators
Chapter 6
TABLE 6-1 Basic C Language Variable Types
TABLE 6-2 More C Language Data Types
Chapter 8
TABLE 8-1 C Language Comparison Operators
TABLE 8-2 Logical Comparison Operators
Chapter 11
TABLE 11-1 C Math Operators
TABLE 11-2 C Math Assignment Operators
TABLE 11-3 Common, Sane Math Functions
Chapter 13
TABLE 13-1 CTYPE Testing Functions
TABLE 13-2 CTYPE Manipulation Functions
TABLE 13-3 String Functions
Chapter 17
TABLE 17-1 Binary Groupings
TABLE 17-2 Powers of 2
TABLE 17-3 Binary Operators
TABLE 17-4 Hexadecimal Values
Chapter 19
TABLE 19-1 Pointers and Peekers In and Out of Parentheses
TABLE 19-2 Array Notation Replaced by Pointers
TABLE 19-3 Pointer Notation and Array Notation
Chapter 22
TABLE 22-1: Access Modes for the
fopen()
Function
Appendix G
TABLE G-1 Standard Operator Precedence
TABLE G-2 Pointers and Precedence
Chapter 1
FIGURE 1-1: The Code::Blocks workspace.
FIGURE 1-2: Program output.
Chapter 5
FIGURE 5-1: Matching
printf()
conversion characters and arguments.
Chapter 11
FIGURE 11-1: Degrees and radians.
Chapter 12
FIGURE 12-1: Storing strings in a two-dimensional array.
Chapter 15
FIGURE 15-1: Text mode in a terminal window.
FIGURE 15-2: Setting command-line arguments in Code::Blocks.
Chapter 17
FIGURE 17-1: Base 2 values in a byte.
Chapter 18
FIGURE 18-1: How a structure fits in memory.
FIGURE 18-2: Variable locations in memory.
FIGURE 18-3: Using a pointer to read values.
Chapter 19
FIGURE 19-1: Filling an array by using a pointer.
FIGURE 19-2: How the ** thing works.
Chapter 20
FIGURE 20-1: A linked list in memory.
FIGURE 20-2: Removing an item from a linked list.
FIGURE 20-3: Adding an item to a linked list.
Chapter 24
FIGURE 24-1: Two source code files in the Code::Blocks IDE.
Chapter 25
FIGURE 25-1: The Compiler toolbar.
FIGURE 25-2: A breakpoint in the code.
FIGURE 25-3: Monitoring variable values.
Cover
Title Page
Copyright Page
Table of Contents
Begin Reading
Index
About the Author
i
ii
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
221
222
223
224
225
226
227
228
229
230
231
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
449
450
451
Part 1
IN THIS PART …
Get started with C coding
Work through your very first program
Learn how programming works
Discover the parts of the C language
Craft a basic C skeleton
Chapter 1
IN THIS CHAPTER
Reviewing software requirements
Programming at the command prompt
Using an IDE
Creating a command prompt program
Working in Code::Blocks
Compiling a program
You’re most likely eager to get started programming in C. I shan’t waste your time.
If you already have a compiler or an IDE set up and are ready to go, skip to Chapter 2.
The two most important things you need to begin your programming adventure are
A computer
Access to the Internet
The computer is your primary tool for writing and compiling code. Yes, even if you’re writing a game for the Xbox, you need a computer to be able to code. The computer can be a PC or a Macintosh. The PC can run Windows or Linux.
Internet access is necessary to obtain the programming software. You need a text editor to write the code and a compiler to translate the code into a program. The compiler generally comes with other tools you need, such as a linker and a debugger. All these tools are found at no cost on the Internet.
The software tools offer two approaches to programming: command line and IDE.
If you want to learn C programming as I did back in the dark ages, you use a terminal window and traditional command-line tools: editor, compiler, and linker. The process is fast, but complicated because you’re using text mode commands. Still, it offers a spiritual connection with those who built the foundations upon which the computer industry roosts.
The most common way to craft code, however, is to obtain an integrated development environment — called an IDE by the cool kids. It combines all the tools you need for programming into one compact, terrifying, and intimidating unit.
Don’t freak! The terms compiler, linker, debugger, and terrifying are all defined in Chapter 2.
To re-create the environment where the C language was born, use a Unix or Linux terminal window running a shell program such as bash. This environment is available to all major computing platforms, and the programming tools used are reliable and well-documented. Programming at the command prompt earns you a nerd merit badge and the admiration of your peers.
For Windows 10, open the Microsoft Store app and install Ubuntu, a free Linux shell. Ensure that you follow the directions to install the Windows Subsystem for Linux, which is an extra step you’ll probably miss.
For Linux, you’re ready to go: Open a terminal window to access the shell.
For Mac OS X, use the Terminal app. I also recommend obtaining the Homebrew package manager. Visit https://brew.sh for directions. Homebrew allows you to install programming tools not available to OS X.
For an editor, you can use any text mode editor available at the command prompt, such as vi or emacs. You can also “mix it up” and use a window-based editor. I’m fond of using the Windows version of the VIM editor while I simultaneously work at the command prompt in an Ubuntu terminal window.
A C compiler comes native to a Unix/Linux command prompt. The standard version is cc or gcc, but I recommend that you use the shell’s package manager to acquire the LLVM clang compiler. In Ubuntu Linux for Windows 10, type this command to install clang:
sudo apt-get install clang
Type your account password to initiate the process. To verify the installation, type
clang --version
Various Linux distros offer similar package managers, which you can use to obtain an editor and the clang compiler.
The VIM editor can be obtained from
vim.org
.
Your choice to use the command prompt means you’re taking on an extra layer of complexity when it comes to programming. I find it fast and enjoyable, but if you believe it to be too much, especially when first learning the C language, rely instead upon an IDE, as covered in the next section.
Plenty of programming IDEs are available for your C coding pleasure. On the Mac, use Xcode, which you can install from the App Store. For Windows and Linux, I recommend obtaining the Code::Blocks IDE, which is found at codeblocks.org. You can choose any other IDE you prefer, but Code::Blocks for Windows is fairly stable and comes with everything you need — providing that you install the correct version.
The Code::Blocks website will doubtless be altered over time, so follow these general steps to install the IDE and confirm that the C compiler is accessible:
On the main Code::Blocks website page, click the Downloads link.
Click the binary release link.
The “binary release” means you’re installing a runnable program, not source code or something equally strange.
Choose the proper installation program for your computer’s operating system.
For Windows 10, I recommend that you choose the installation with the text mingw-setup appended. For example:
codeblocks-20.03mingw-setup.exe
The 20.03 part of the filename is the release number, which will change in the future. The mingw-setup choice means you're downloading both the IDE and the MinGW compiler.
For Linux, click the link to install the proper version for your distro, but keep in mind that Code::Blocks might be more easily acquired by using the Linux GUI package/software manager.
Open the downloaded archive to extract the Code::Blocks IDE installer.
In Windows, you see a User Account Control warning when you open the archive. Click Yes to proceed with installation.
Run the installation program.
Perform a default installation; you need not customize anything.
Choose to run Code:Blocks: Click the Yes button.
Code::Blocks appears, showing its splash screen. Don’t start coding now. Instead, confirm the compiler’s installation:
Choose Settings, Compiler.
The Compiler Settings dialog box appears.
With Global Compiler Settings chosen on the left, click the Toolchain Executables tab on the right side of the dialog box.
Ensure that the Compiler’s Installation Directory text box is filled.
In a default confirmation, the following pathname is listed:
C:\Program Files (x86)\CodeBlocks\MinGW
If the text box is blank, use the Browse button (three dots to the right of the text box) to locate the MinGW installation directory.
Confirm that gcc.exe is set in the Compiler text box.
If not, click the Browse button (three dots) to locate the gcc.exe program, installed in the MinGW\bin directory by default.
Close the Compiler Settings dialog box; click OK.
Installation is complete. I recommend you close the Code::Blocks window. Finish the installation program as well.
Figure 1-1 illustrates the Code::Blocks workspace, which is the official name of the massive mosaic of windows and toolbars you see arranged on the screen.
FIGURE 1-1: The Code::Blocks workspace.
On your computer, as well as in Figure 1-1, locate the following parts of the workspace:
Toolbars: These messy strips, adorned with various command buttons, cling to the top of the Code::Blocks window. The toolbars can be rearranged or hidden, so don't mess with them until you get comfy with the interface.
Management: The pane on the left side of the workspace features four tabs, though you may not see all four at one time. The window provides a handy oversight of your programming endeavors.
Status bar: At the bottom of the screen, you see information about the project, editor, and other activities that take place in Code::Blocks.
Editor: The big window in the center-right area of the screen is where you type code.
Logs: The bottom of the screen features a window with many, many tabs displaying various tidbits about the programming process. The tab used most often is named Build Log.
The View menu controls the visibility of every item displayed in the window. Choose the pane name, such as Manager, from the View menu to show or hide that item. Control toolbars by using the View, Toolbars submenu.
Maximize the Code::Blocks program window so that it fills the screen. You need all that real estate.
In addition to color-coding your text, the Code::Blocks editor offers an autocomplete feature. Items that must be typed in pairs, such as quotes, parentheses, and so on, are generated automatically for you. Certain C language keywords and functions are presented automatically, along with hints for their arguments and options.
The editor features a tabbed interface, which lets you work on multiple source code files at one time.
The traditional first program written for any programming language is called Hello World. It’s boring, like all traditions.
Listing 1-1 shows the Hello World source code as presented in Code::Blocks. This code is generated by default whenever you start a new Code::Blocks project.
LISTING 1-1 The Code::Blocks Skeleton
#include <stdio.h>#include <stdlib.h>int main(){ printf("Hello world!\n"); return 0;}
The programming process works the same whether you use the command prompt or an IDE:
Use an editor to write the source code.
Compile and link the source code into a program.
Run the program to see whether it works.
Chapter 2 goes over these steps in detail, but I assume you’re in a rush. The following sections cover the specifics for the command prompt and IDE environments.
Use your text editor to create a new file and type in the text presented in Listing 1-1. This code, like all source code in this book, is available on the companion website: https://c-for-dummies.com/cprog.
Save the source code file as ex0101.c. The filename must end in .c (“dot C”) to be recognized as a C source code file by the compiler.
Compile and link, or “build,” the source code into a program file in a Unix terminal window, such as the Ubuntu bash shell in Windows 10. Type the following command in the same folder/directory where the source code file is saved:
clang -Wall ex0101.c
The name of the compiler program is clang. The -Wall argument activates all warning messages. The final argument is the name of the source code file, ex0101.c, in this example.
Upon success, you see no output. If you see warnings or error messages, you probably mistyped the source code. Try again: re-edit and compile.
To run the program, type the default program filename a.out. In a terminal window, the program name must be prefixed by ./ (“dot slash”) to direct the command interpreter to look in the current directory:
./a.out
You see the message Hello, world! output in the terminal window. Now skim to Chapter 2 to discover what just happened.
Two approaches can be used in Code::Blocks to build the sample code shown in this book: You can build a project for each exercise or you can use an empty file to write the code.
For a project, follow these steps:
Choose File, New, Project.
Choose Console Application and then click the Go button.
Select C as the programming language and then click the Next button.
C is quite different from C++ — you can do things in one language that aren't allowed in the other.
Type a project title.
The code exercises in this book follow a naming pattern you can use for the project title: ex followed by a 2-digit chapter number and 2-digit sequential number. For the sample code presented in Listing 1-1, the project title is ex0101.
When you set the project title, the project’s filename is automatically filled in.
Click the … (Browse) button to the right of the text box titled Folder to Create Project In.
I recommend that you create and use a special folder for all projects in this book. Once the location is set, you can skip this step in the future.
Click the Next button.
The next screen (the final one) allows you to select a compiler and choose whether to create Debug or Release versions of your code, or both.
The compiler selection is fine; the GNU GCC Compiler (or whatever is shown in the window) is the one you want.
Remove the check mark by Create Debug Configuration.
You create this configuration only when you need to debug, or fix, a programming predicament that puzzles you. See Chapter 25.
Click the Finish button.
Code::Blocks builds a skeleton of your project, which is the same code shown in Listing 1-1. Skim to the later section “Building and running.”
A less complicated method for working with this book’s exercises is to type the source code into an empty project file. Obey these steps in the Code::Blocks IDE:
Choose File, New, Empty File.
Type the source code into the editor.
You can also copy-and-paste the source code from the companion website into the editor. Refer to the introduction for details on the companion website.
If you’d prefer to see the editor color-code your text, save the file! Press Ctrl+S and choose the folder where you plan to keep all this book’s programming projects. Name the file according to this book’s convention: ex followed by a 2-digit chapter number and 2-digit project number. End the filename in .c (“dot C”) to identify it as a C source code file.
Save the source code file.
If the file is already saved, press Ctrl+S. Otherwise, follow the naming convention listed under Step 2.
After the empty file is created, you can build and run the program just as you would had you run through the bothersome technique of starting a Code::Blocks project.
You can also open the source code file directly in Code::Blocks, if you’ve obtained it from the companion website: Use the Open command to open the file. At this point, you can build and run, modify the code, or do whatever your heart pleases.
In Code::Blocks, the process of compiling and linking C language source code is accomplished in one step called Build.
To build the project, click the Build button on the toolbar, as shown in the margin and illustrated in Figure 1-1. Any compiler warnings or errors appear on the Build Log tab at the bottom of the window. For Listing 1-1, no warnings or errors should be generated, providing the code is input exactly.
To test-run the program, click the Run button, shown in the margin and illustrated in Figure 1-1. Output appears in a terminal window, as shown in Figure 1-2.
FIGURE 1-2: Program output.
Press the Enter key to close the output window. In Linux, you must type the exit command to close the window.
Both build and run steps are combined when you click the Build and Run button, shown in the margin.
When you’re done with a project, or even after you’ve changed a minor thing, save it. Save the source code file, but also save the project if one was created: Choose File, Save Everything to save both the source code and project files.
Commands for building and running the code are also found on the Build menu.
The keyboard shortcuts for Build, Run, and Build and Run are Ctrl+F9, Ctrl+F10, and F9, respectively. No need to memorize those shortcuts; they’re listed on the menu.
You can view documentation for the various C library functions in two ways.
First, in a terminal window, use the man program to look up function definitions. For example, type man printf to read about the printf() function. This documentation is referred to as the “man pages,” where “man” is short for manual.
The man program also documents shell commands. Occasionally, a shell command shares the name of a C language function, such as stat. To ensure that you’re viewing the proper man page, use the page argument to specify either page 2 or page 3, where most of the C language functions are found. For example:
man stat — view the man page on the stat shell command.
man 2 stat — view the man page for the C language stat() function.
If you’re not using a Unix-like shell to program, man page documentation is found on the Internet. I recommend these pages:
http://man7.org/linux/man-pages/dir_section_2.htmlhttp://man7.org/linux/man-pages/dir_section_3.html
The program output appears in the top part of the command prompt window (refer to Figure 1-2). The last two lines are generated by the IDE when the program is run. The text shows a value returned from the program to the operating system, a zero, and how long the program took to run (0.005 seconds).
Chapter 2
IN THIS CHAPTER
Understanding programming history
Reviewing the programming processes
Creating source code
Building a program
Testing the final program
It’s called programming, though the cool kids know it as coding — the process whereby a human being writes information resembling cryptic English that is then somehow translated into directions for an electronic gizmo. In the end, this silent and solitary art grants individuals the power to control electronics. It’s a big deal. It’s the programming thing.
Few books written about programming get away with not describing the thrill-a-minute drama of programming history. As a programmer myself, it’s difficult not to write about it, let alone contain my enthusiasm at cocktail parties. So consider this section optional reading, though a review of where programming has been and where it is today may help you better understand the art form.
In a nutshell, programming is the process of telling a gizmo what to do. That gizmo is hardware; the program is software.
The first known machine to be programmed was Charles Babbage’s analytical engine, back in 1822. The programming took place by physically changing the values represented by a column of gears. The engine computed the result of some dull, complex mathematical equation.
In the 1940s, early electronic computers were programmed in a similar manner to Babbage’s analytical engine. A major difference was that, rather than rearrange physical gears, instructions were hard-wired directly into electric circuitry. “Programming” pretty much meant “rewiring.”
Over time, the rewiring job was replaced by rows of switches. Computer instructions were input by throwing switches in a certain way.
Professor John von Neumann pioneered the modern method of computer programming in the 1950s. He introduced decision making into the process, where computers could make if-then choices. Professor von Neumann also developed the concept of the repeating loop and the subroutine.
It was Admiral Grace Hopper who developed the compiler, or a program that creates other programs. Her compiler would take words and phrases in English and translate them into computer code. Thus, the programming language was born.
The first significant programming language was FORTRAN, born in the 1950s. Its name came from formula translator. Other programming languages of the period were COBOL, Algol, Pascal, and BASIC.
Regardless of the form, whether it’s rewiring circuits, flipping switches, or writing a programming language, the result is the same: telling hardware to do something.
The C language was developed in 1972 at AT&T Bell Labs by Dennis Ritchie. It combined features from the B and BCPL programming languages but also mixed in a bit of the Pascal language. Mr. Ritchie, along with Brian Kernighan, used C to create the Unix operating system. A C compiler has been part of that operating system ever since.
In the early 1980s, Bjarne Stoustroup used C as the basis of the object-oriented C++ programming language. The ++ (plus-plus) part of the name is kind of an in-joke, which you’ll understand better after reading Chapter 11. Mr. Stoustroup intended C++ to be the successor to C. In many ways it is, yet C remains one of the most popular programming languages.
The B programming language, upon which C is based, was named after the B in Bell Labs.
BCPL stands for Basic Combined Programming Language.
The C++ programming language is quite similar to C, but it’s not merely an extension or an add-on. It’s easier to learn C++ when you know C, but it’s not easy to switch between the languages.
A D programming language exists. Developed in the early 2000s, it’s not as popular today as other current languages, such as Python and Java.
Unfortunately, I have no idea how to pronounce “Bjarne Stoustroup.”
No matter which language you use, certain procedures are common to the programming process. In this manner, learning to program is like learning to cook: You must take things in a certain order, whether the result is crème brûlée or a smoldering pile of egg glop.
The goal of programming is to create a program. The language is C, and the tools are the editor, compiler, and linker — or an IDE, which combines everything. The result is a program that directs the hardware to do something. That hardware can be a computer, tablet, phone, microcontroller, or whatever.
Step-by-step, the programming process works like this:
Write the source code.
Compile and link, or build, the source code into a program.
Run and test the program.
A human (you) writes source code. The source code is built into a program in two steps: compiling it into object code and then linking the object code with C libraries to build the program. Finally, that program is run.
The reality goes more like this:
Write the source code.
Compile the source code into object code.
Fix warnings and repeat Steps 1 and 2.
Link the object code with libraries to build the program.
Fix errors and repeat Steps 1 through 4.
Run and test the program.
Fix bugs by repeating the entire process.
Or, more frequently, the program runs fine but you want to add a feature or refine an element. Then you repeat everything.
Hopefully, Steps 3, 5, and 7 don’t happen often. Still, you do a lot of fixing in the programming cycle.
The good news is that the compiler dutifully reports the errors and even shows you where they are. That’s better than tracking down a bug in miles of wires back in the old ENIAC days.
Despite having “build” as a single step, the compiler still creates object code, and a linker links the object code into a program. If you goof up royally, linking doesn’t even happen and you must fix the compiler warnings before taking the next step.
One of my professional programmer friends said that the art form should be called debugging, not programming.
Legend has it that the first computer bug was a moth that Grace Hopper found in the wiring of an early computer. There’s some doubt about this legend, considering that the word bug has been used since Shakespeare’s time to describe something quirky or odd.
Source code represents the part of the process that contains the programming language itself. You use a text editor to write a source code file.
In this book, source code is shown in program listings, such as the example in Listing 2-1.
LISTING 2-1 Standard “Hello World” Program
#include <stdio.h>int main(){ puts("Greetings, human."); return 0;}
Line numbers are not shown in this book’s listings. They aren’t part of the code, and showing them here can be confusing. The text editor may display line numbers for reference purposes.
In this book, you’re directed to type the source code from a listing as part of an exercise. For example:
Exercise 2-1: Start a new project in Code::Blocks named ex0201. Or use your text editor to create the source code file ex0201.c for compiling and linking at the command prompt.
Do it: Obey Exercise 2-1, either in Code::Blocks, at the command prompt in a terminal window, or in another C language IDE, such as Xcode on the Mac.
Write the source code in the editor, copying it from Listing2-1.
Alternatively, you can copy-and-paste the code from the companion website or use the listing's source code file, downloaded from the website. Refer to this book’s introduction for details.
If you’re creating a Code::Blocks project, erase the skeleton that’s provided and replace it with the code shown in Listing 2-1.
Save the source code file.
There. You’ve just completed the first step in the programming process — writing source code. The next section continues your journey with the compiler.
All C source code files end with the .c (“dot-see”) filename extension.
In Windows, I recommend that you set the folder display options so that filename extensions appear.
C++ source code files have the extension .cpp (“dot-see-pee-pee”). I shall refrain from writing a puerile joke here.
Source code files follow the same naming conventions as any file on a computer. Traditionally, a small program has the same name (but not extension) as the final program. If your program is named puzzle, the source code is most likely named puzzle.c.
Traditionally, the compiler reads text from a source code file and translates that text — a programming language — into something called object code. The linker then creates the final program. It links the object code file with C language libraries to create a program. All this happens exactly as written — unless a warning or an error crops up along the way.
You can compile and link separately in an IDE or at the command prompt. Fortunately, modern compilers combine both steps in a process called build.
To build the project from Listing 2-1 in Code::Blocks, click the Build toolbar button (shown in the margin) or choose Build ⇒ Build from the menu. Any errors present themselves on the Build Log tab as well as on the Build Messages tab.
To build the program at the command prompt, type this line in the same directory (folder) as the source code file (ex0201.c):
clang -c -Wall ex0201.c
First comes the compiler name, clang, followed by the -Wall switch to report all warnings. The final argument is the source code filename. Upon success, you see no feedback; otherwise, warnings and error messages spill on the screen like fruit from an upturned apple cart.
(Running the program file is covered in the next section.)
The
object code
file has the same name as the source code file, but ends in
.o
(“dot-o,” “little o”). If the source code file is named
ex0201.c
the object code file is named
ex0201.o
. The modern build process deletes this file unless you specifically direct the compiler to generate and retain the object code file.
As the compiler translates your C code into object code, it checks for common mistakes, missing items, and other issues. If anything is awry, the compiler displays a list of warnings. To fix them, you re-edit the source code and attempt to compile once again.
The linker brings in the C language library, which is how the final program is built. The libraries contain the actual instructions that tell the computer (or whatever device) what to do. Those instructions are executed based on the shorthand directions found in the object code.
Any mistakes found by the linker are called
errors.
When errors occur, a program isn't created; errors are fatal.
Some C programs link in several libraries, depending on what the program does. In addition to the standard C library, you can link libraries for working with graphics, networking, sound, and so on. As you learn more about programming, you’ll discover how to choose and link in various libraries.
Chapter 24
offers the details.
The next thing to do after building is to run the result. Running is necessary, primarily to demonstrate that the program does what you intend and in the manner you desire.
When the program doesn’t work, you must go back and fix the source code and try again. Yes, it’s entirely possible to build a program and see no warnings or errors and then find that the thing doesn’t work. It happens all the time.
Continue with Exercise 2-1: Run the program.
In Code::Blocks, choose Build ⇒ Run or click the Run toolbar button, shown in the margin.
At the command prompt, type the program name prefixed by the current directory:
./a.out
Beyond source code, a C compiler also deals with special instructions called preprocessor directives. For example, Listing 2-1 shows the following preprocessor directive:
#include <stdio.h>
The include directive instructs the compiler to locate the header file stdio.h. The contents of this file are inserted into the source code at compile time. Together, both files are converted into object code.
The name a.out is the default C program filename. You can reset this name by specifying the -o (“little o”) switch followed by the desired output filename when building. For example:
clang -Wall ex0201.c -o ex0201
The preceding command uses the source code in ex0201.c to build a program named ex0201. It must be run at the command prompt in the same manner as a.out:
./ex0201
The program runs, outputting text, which appears on the next line after you type the program name:
Greetings, human.
In Code::Blocks, output appears in a terminal window. Press the Enter key to close the window. For Code::Blocks in Linux, type the exit command to close the output terminal window.
A program like ex0201 doesn't require much testing to ensure that it works. As your programming skills mature, testing, rewriting, compiling, and debugging become a standard part of the process. Don’t be discouraged; this is how all programmers learn the craft.
The mechanics of running a program are carried out by the device’s operating system: The operating system loads the program into memory, where the processor or CPU executes the code. This is a loose description of how a program works.
In Windows, the program name ends with the exe (for executable) extension, as in ex0201.exe. In Mac OS X, Linux, and Unix, the program name has no extension: ex0201. Further, in those operating systems, the file’s permissions are set for the file to run as an executable.