Ngôn ngữ lập trình C là một ngôn ngữ mệnh lệnh được phát triển từ đầu thập niên 1970 bởi Dennis Ritchie để dùng trong hệ điều hành UNIX. Từ đó, ngôn ngữ này đã lan rộng ra nhiều hệ điều hành khác và trở thành một những ngôn ngữ phổ dụng nhất. C là ngôn ngữ rất có hiệu quả và được ưa chuộng nhất để viết các phần mềm hệ thống, mặc dù nó cũng được dùng cho việc viết các ứng dụng. Ngoài ra, C cũng thường được dùng làm phương tiện giảng dạy trong khoa học máy tính mặc dù ngôn ngữ này không được thiết kế dành cho người nhập môn
About This eBook ePUB is an open, industry-standard format for eBooks However, support of ePUB and its many features varies across reading devices and applications Use your device or app settings to customize the presentation to your liking Settings that you can customize often include font, font size, single or double column, landscape or portrait mode, and figures that you can click or tap to enlarge For additional information about the settings and features on your reading device or app, visit the device manufacturer ’s Web site Many titles include programming code or configuration examples To optimize the presentation of these elements, view the eBook in single-column, landscape mode and adjust the font size to the smallest setting In addition to presenting code and configurations in the reflowable text format, we have included images of the code that mimic the presentation found in the print book; therefore, where the reflowable format may compromise the presentation of the code listing, you will see a “Click here to view code image” link Click the link to view the print-fidelity code image To return to the previous page viewed, click the Back button on your device or app Learn C The Hard Way Practical Exercises on the Computational Subjects You Keep Avoiding (Like C) Zed A Shaw New York • Boston • Indianapolis • San Francisco Toronto • Montreal • London • Munich • Paris • Madrid Capetown • Sydney • Tokyo • Singapore • Mexico City Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and the publisher was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals The author and publisher have taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein For information about buying this title in bulk quantities, or for special sales opportunities (which may include electronic versions; custom cover designs; and content particular to your business, training goals, marketing focus, or branding interests), please contact our corporate sales department at corpsales@pearsoned.com or (800) 382-3419 For government sales inquiries, please contact governmentsales@pearsoned.com For questions about sales outside the U.S., please contact international@pearsoned.com Visit us on the Web: informit.com/aw Library of Congress Cataloging-in-Publication Data Shaw, Zed, author Learn C the hard way : practical exercises on the computational subjects you keep avoiding (like C) / Zed A Shaw pages cm Includes index ISBN 978-0-321-88492-3 (pbk : alk paper)—ISBN 0-321-88492-2 (pbk : alk paper) C (Computer program language)—Problems, exercises, etc I Title QA76.73.C15S473 2016 005.13’3—dc23 2015020858 Copyright © 2016 Zed A Shaw All rights reserved Printed in the United States of America This publication is protected by copyright, and permission must be obtained from the publisher prior to any prohibited reproduction, storage in a retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise To obtain permission to use material from this work, please submit a written request to Pearson Education, Inc., Permissions Department, 200 Old Tappan Road, Old Tappan, New Jersey 07657, or you may fax your request to (201) 236-3290 ISBN-13: 978-0-321-88492-3 ISBN-10: 0-321-88492-2 Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana First printing, August 2015 Contents Acknowledgments This Book Is Not Really about C The Undefined Behaviorists C Is a Pretty and Ugly Language What You Will Learn How to Read This Book The Videos The Core Competencies Reading and Writing Attention to Detail Spotting Differences Planning and Debugging Exercise 0 The Setup Linux Mac OS X Windows Text Editor Do Not Use an IDE Exercise 1 Dust Off That Compiler Breaking It Down What You Should See How to Break It Extra Credit Exercise 2 Using Makefiles to Build Using Make What You Should See How to Break It Extra Credit Exercise 3 Formatted Printing What You Should See External Research How to Break It Extra Credit Exercise 4 Using a Debugger GDB Tricks GDB Quick Reference LLDB Quick Reference Exercise 5 Memorizing C Operators How to Memorize The List of Operators Exercise 6 Memorizing C Syntax The Keywords Syntax Structures A Word of Encouragement A Word of Warning Exercise 7 Variables and Types What You Should See How to Break It Extra Credit Exercise 8 If, Else-If, Else What You Should See How to Break It Extra Credit Exercise 9 While-Loop and Boolean Expressions What You Should See How to Break It Extra Credit Exercise 10 Switch Statements What You Should See How to Break It Extra Credit Exercise 11 Arrays and Strings What You Should See How to Break It Extra Credit Exercise 12 Sizes and Arrays What You Should See How to Break It Extra Credit Exercise 13 For-Loops and Arrays of Strings What You Should See Understanding Arrays of Strings How to Break It Extra Credit Exercise 14 Writing and Using Functions What You Should See How to Break It Extra Credit Exercise 15 Pointers, Dreaded Pointers What You Should See Explaining Pointers Practical Pointer Usage The Pointer Lexicon Pointers Aren’t Arrays How to Break It Extra Credit Exercise 16 Structs and Pointers to Them What You Should See Explaining Structures How to Break It Extra Credit Exercise 17 Heap and Stack Memory Allocation What You Should See Heap versus Stack Allocation How to Break It Extra Credit Exercise 18 Pointers to Functions What You Should See How to Break It Extra Credit Exercise 19 Zed’s Awesome Debug Macros The C Error-Handling Problem The Debug Macros Using dbg.h What You Should See How the CPP Expands Macros Extra Credit Exercise 20 Advanced Debugging Techniques Debug Printing versus GDB A Debugging Strategy Extra Credit Exercise 21 Advanced Data Types and Flow Control Available Data Types Type Modifiers Type Qualifiers Type Conversion Type Sizes Available Operators Math Operators Data Operators Logic Operators Bit Operators Boolean Operators Assignment Operators Available Control Structures Extra Credit Exercise 22 The Stack, Scope, and Globals ex22.h and ex22.c ex22_main.c What You Should See Scope, Stack, and Bugs How to Break It Extra Credit Exercise 23 Meet Duff’s Device What You Should See Solving the Puzzle Why Bother? Extra Credit Exercise 24 Input, Output, Files What You Should See How to Break It The I/O Functions Extra Credit Exercise 25 Variable Argument Functions What You Should See How to Break It Extra Credit Exercise 26 Project logfind The logfind Specification Exercise 27 Creative and Defensive Programming The Creative Programmer Mind-Set The Defensive Programmer Mind-Set The Eight Defensive Programmer Strategies Applying the Eight Strategies Never Trust Input Prevent Errors Fail Early and Openly Document Assumptions Prevention over Documentation Automate Everything Simplify and Clarify Question Authority Order Is Not Important Extra Credit Exercise 28 Intermediate Makefiles The Basic Project Structure Makefile The Header The Target Build The Unit Tests The Cleaner The Install The Checker What You Should See ... Exercise 48 A Simple Network Server The Specification Exercise 49 A Statistics Server Specification Exercise 50 Routing the Statistics Exercise 51 Storing the Statistics The Specification Exercise 52 Hacking and Improving Your Server... If that worked, then you should see this: Exercise 2 Session Click here to view code imag e $ make clean rm -f ex1 $ make ex1 cc -Wall -g ex1 .c -o ex1 ex1 .c: In function 'main': ex1 .c: 3: warning: implicit declaration of function 'puts'... Yes, it’s called ex1 .c Do I know how to build c files? Yes, I run this command cc ex1 .c -o ex1 to build them I shall make you one ex1 by using cc to build it from ex1 .c The second command in the listing above is a way to pass modifiers to the make command