Beginning C Programming - Programmer Books

Transcription

Beginning C ProgrammingThis is the start of your journey into the most powerfullanguage available to the programming publicRichard GrimesBIRMINGHAM - MUMBAI

Beginning C ProgrammingCopyright 2017 Packt PublishingAll rights reserved. No part of this book may be reproduced, stored in a retrieval system, ortransmitted in any form or by any means, without the prior written permission of thepublisher, except in the case of brief quotations embedded in critical articles or reviews.Every effort has been made in the preparation of this book to ensure the accuracy of theinformation presented. However, the information contained in this book is sold withoutwarranty, either express or implied. Neither the author, nor Packt Publishing, and itsdealers and distributors will be held liable for any damages caused or alleged to be causeddirectly or indirectly by this book.Packt Publishing has endeavoured to provide trademark information about all of thecompanies and products mentioned in this book by the appropriate use of capitals.However, Packt Publishing cannot guarantee the accuracy of this information.First published: April 2017Production reference: 1180417Published by Packt Publishing Ltd.Livery Place35 Livery StreetBirminghamB3 2PB, UK.ISBN 978-1-78712-494-3www.packtpub.com

CreditsAuthorCopy EditorRichard GrimesSafis EditingReviewerProject CoordinatorAngel HernandezVaidehi SawantCommissioning EditorProofreaderAaron LazarSafis EditingAcquisition EditorIndexerNitin DasanTejal Daruwale SoniContent Development EditorGraphicsZeeyan PinheiroAbhinash SahuTechnical EditorProduction CoordinatorPavan RamchandaniShraddha Falebhai

About the AuthorRichard Grimes has been programming in C for 25 years, working on projects as diverseas scientific control and analysis and finance analysis to remote objects for the automotivemanufacturing industry. He has spoken at 70 international conferences on Microsofttechnologies (including C and C#) and has written 8 books, 150 articles for programmingjournals, and 5 training courses for Microsoft. Richard was awarded Microsoft MVP for 10years (1998-2007). He has a reputation for his deep understanding of the .NET frameworkand C and the frank way in which he assesses new technology.For my wife Ellinor: it is only with your love and support that I am able to do anything atall

About the ReviewerAngel Hernandez is a highly regarded senior solutions, architect and developer with over15 years of experience, mainly in the consulting space. He is an 11-time Microsoft(2006-2016) MVP award recipient in Visual Studio and Development Technologies category(formerly, Visual C ), and he is currently a member of the Microsoft MVP ReconnectProgram. Angel is also a TOGAF practitioner. He has deep knowledge of Microsoft andopen source technologies (*nix Systems), and he's an expert in managed and nativelanguages, C# and C being his favorites. He can be reached at http://www.angelhernandezm.com.I’d like to thank, first and foremost, God and his son Jesus; Packt and the author for givingme the opportunity to review this book; and my family, Mery, Miranda, and Mikaela (the3Ms) for being understanding and patient with me.

www.PacktPub.comFor support files and downloads related to your book, please visit www.PacktPub.com.Did you know that Packt offers eBook versions of every book published, with PDF andePub files available? You can upgrade to the eBook version at www.PacktPub.com and as aprint book customer, you are entitled to a discount on the eBook copy. Get in touch with usat service@packtpub.com for more details.At www.PacktPub.com, you can also read a collection of free technical articles, sign up for arange of free newsletters and receive exclusive discounts and offers on Packt books andeBooks.https://www.packtpub.com/maptGet the most in-demand software skills with Mapt. Mapt gives you full access to all Packtbooks and video courses, as well as industry-leading tools to help you plan your personaldevelopment and advance your career.Why subscribe?Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Customer FeedbackThanks for purchasing this Packt book. At Packt, quality is at the heart of our editorialprocess. To help us improve, please leave us an honest review on this book's Amazon pageat https://www.amazon.com/dp/1787124940.If you'd like to join our team of regular reviewers, you can e-mail us atcustomerreviews@packtpub.com. We award our regular reviewers with free eBooks andvideos in exchange for their valuable feedback. Help us be relentless in improving ourproducts!

Table of ContentsCustomer FeedbackPrefaceChapter 1: Starting with C What will you find in this chapter?What is C ?Installing Visual C Setting upDownloading the installation filesInstalling Visual StudioRegistering with MicrosoftExamining C projectsCompilersLinking the codeSource filesA simple exampleCreating source filesCompiling the codePassing parameters between the command-line and an executableThe preprocessor and symbolsDefining constantsUsing macrosUsing symbolsUsing pragmasDependenciesLibrariesPre-compiled headersProject structureManaging dependenciesMakefilesWriting a simple projectThe project structureCreating the precompiled headerCreating the main fileUsing input and output streamsUsing time functionsBuilding the 4343536373839394042434445

Testing the codeChanging the projectSummary464747Chapter 2: Understanding Language FeaturesWriting C Using white spaceFormatting codeWriting statementsWorking with expressionsUsing the comma operatorUsing types and variablesUsing constants and literalsDefining constantsUsing constant expressionsUsing enumerationsDeclaring pointersUsing namespacesC scoping of variablesUsing operatorsExploring the built-in operatorsArithmetic operatorsIncrement and decrement operatorsBitwise operatorsBoolean operatorsBitwise shift operatorsAssignment operatorsControlling execution flowUsing conditional statementsSelectingLoopingLooping with iterationConditional loopsJumpingUsing C language featuresSummaryChapter 3: Exploring C 676767982828788889596Exploring built-in typesIntegersSpecifying integer literalsUsing bitset to show bit patternsDetermining integer byte order[ ii ]9697100101102

Floating point typesSpecifying floating point literalsCharacters and stringsCharacter typesUsing character macrosSpecifying character literalsSpecifying string literalsUnicode literalsRaw stringsString byte orderBooleanvoidInitializersDefault valuesDeclarations without a typeStorage classesUsing type aliasesAggregating data in record typesStructuresInitializingStructure fieldsUsing structure namesDetermining alignmentStoring data in the same memory with unionsAccessing runtime type informationDetermining type limitsConverting between typesType conversionsPromoting conversionsNarrowing conversionsNarrowing to boolConverting signed typesCastingCasting away const-nessCasting without runtime checksCasting pointers without runtime checksCasting with runtime checksCasting with list initializerUsing C castsUsing C typesSummaryChapter 4: Working with Memory, Arrays, and PointersUsing memory in C 36137138138139140140148149149[ iii ]

Using C pointer syntaxUsing null pointersTypes of memoryPointer arithmeticUsing arraysFunction parametersMultidimensional arraysPassing multidimensional arrays to functionsUsing arrays of charactersComparing stringsPreventing buffer overrunsUsing pointers in C Accessing out of boundsPointers to deallocated memoryConverting pointersConstant pointersChanging the type pointed toAllocating memory in codeAllocating individual objectsAllocating arrays of objectsHandling failed allocationsUsing other versions of the new operatorMemory lifetimeThe Windows SDK and pointersMemory and the C Standard LibraryStandard Library arraysUsing the stack-based array classUsing the dynamically allocated vector classReferencesConstant referencesReturning referencesTemporaries and referencesThe rvalue referencesRanged for and referencesUsing pointers in practiceCreating the projectAdding a task object to the listDeleting the task listIterating the task listInserting items[ iv 185187189190192193194

Summary197Chapter 5: Using Functions198Defining C functionsDeclaring and defining functionsSpecifying linkageInliningDetermining the return typeNaming the functionFunction parametersSpecifying exceptionsFunction bodyUsing function parametersPassing Initializer listsUsing default parametersVariable number of parametersInitializer listsArgument listsFunction featuresCall stackSpecifying calling conventionsUsing C linkageSpecifying how the stack Is maintainedUsing recursionOverloading functionsFunctions and scopeDeleted functionsPassing by value and passing by referenceDesigning functionsPre- and post-conditionsUsing invariantsFunction pointersRemember the parentheses!Declaring function pointersUsing function pointersTemplated functionsDefining templatesUsing template parameter valuesSpecialized templatesVariadic 18218220222223225227229

Overloaded operatorsFunction objectsIntroducing lambda expressionsUsing functions in C SummaryChapter 6: Classes231234237239244246Writing classesReviewing structuresDefining classesDefining class behaviorUsing the this pointerUsing the scope resolution operatorDefining class stateCreating objectsConstruction of objectsDefining constructorsDelegating constructorsCopy constructorConverting between typesMaking friendsMarking constructors as explicitDestructing objectsAssigning objectsMove semanticsDeclaring static membersDefining static membersUsing static and global objectsNamed constructorsNested classesAccessing const objectsUsing objects with pointersGetting pointers to object membersOperator overloadingDefining function classesDefining conversion operatorsManaging resourcesWriting wrapper classesUsing smart pointersManaging exclusive ownershipSharing ownershipHandling dangling pointersTemplates[ vi 283285287

Using classesSummary289294Chapter 7: Introduction to Object-Orientated ProgrammingInheritance and compositionInheriting from a classOverriding methods and hiding namesUsing pointers and referencesAccess levelsChanging access level through inheritanceInheritance access levelsMultiple inheritanceObject slicingIntroducing polymorphismVirtual methodsVirtual method tablesMultiple inheritance and virtual method tablesVirtual methods, construction, and destructionContainers and virtual methodsFriends and inheritanceOverride and finalVirtual inheritanceAbstract classesObtaining type informationSmart pointers and virtual methodsInterfacesClass relationshipsUsing mixin classesUsing polymorphismSummaryChapter 8: Using the Standard Library ContainersWorking with pairs and tuplesContainersSequence 358358361362364364365368ListForward listVectorDequeAssociative containersMaps and multimapsSets and multisets[ vii ]

Unordered containersSpecial purpose containersUsing iteratorsInput and output iteratorsStream iteratorsUsing iterators with the C Standard LibraryAlgorithmsIteration of itemsGetting informationComparing containersChanging ItemsFinding ItemsSorting itemsUsing the numeric librariesCompile time arithmeticComplex numbersUsing the Standard LibrarySummaryChapter 9: Using 89391393400401Using the string class as a containerGetting information about a stringAltering stringsSearching stringsInternationalizationUsing facetsStrings and numbersConverting strings to numbersConverting numbers to stringsUsing stream classesOutputting floating point numbersOutputting integersOutputting time and moneyConverting numbers to strings using streamsReading numbers from strings using streamsUsing regular expressionsDefining regular expressionsStandard Library classesMatching expressionsUsing iteratorsReplacing strings[ viii 24426428430433

Using stringsCreating the projectProcessing header subitemsSummary433434439443Chapter 10: Diagnostics and Debugging444Preparing your codeInvariants and conditionsConditional compilationUsing pragmasAdding informational messagesCompiler switches for debuggingPre-processor symbolsProducing diagnostic messagesTrace messages with the C runtimeTracing messages with WindowsUsing assertsApplication terminationError valuesObtaining message descriptionsUsing the Message CompilerC exceptionsException specificationsC exception syntaxStandard exception classesCatching exceptions by typeFunction try blocksSystem errorsNested exceptionsStructured Exception HandlingCompiler exception switchesMixing C and SEH exception handlingWriting exception-safe 491492[ ix ]

PrefaceC has been used for 30 years, and during that time, many new languages have come andgone, but C has endured. The big question behind this book is: Why? Why use C ? Theanswer lies in the ten chapters you see in front of you but, as a spoiler, it is the flexibilityand power of the language and the rich, broad Standard Library.C has always been a powerful language, giving you direct access to memory whileproviding high-level features such as the ability to create new types—classes

Richard Grimes has been programming in C for 25 years, working on projects as diverse as scientific control and analysis and finance analysis to remote objects for the automotive manufacturing industry. He has spoken at 70 international conferences on Microsoft technologies (including C and C#) and has written 8 books, 150 articles for programming journals, and 5 training courses for .