Transcription of A brief introduction to C++ and Interfacing with Excel
1 A briefintroductionto C++andInterfacingwithExcelANDREWL. HAZELS chool of Mathematics,TheUniversity of ManchesterOxfordRoad,Manchester,M139PL,U KCONTENTS1 Contents1 .. ++program.. ++keywords.. thesourcecode.. :compilingandrunningC++..82 GettingstartedwithC++ .. of variables.. |Operators.. theworld|InputandOutput.. noteonnamespaces.. code.. command.. executionof commands|Loops..293 de nefunctions.. functionarguments..364 .. ++class.. functions.. objects..525 InterfacingC++ simpleExcelAdd-Inin C++.. VisualStudio.. ++..611 INTRODUCTION31 IntroductionComputersareanessentialtool in ,analysisandsimulationof orderto usea computerto solve aparticularproblem,however,we mustgeneratea listof instructionsforthecomputertofollow, a taskknownasprogramming.
2 For commontasks,thelistsof instructionswillalmostcertainlyhave beencreatedby somebodyelseandwe canusetheirworkto example,MicrosoftExcelcontainstheinstruc tionsto performa hugenumber of ,Excelcannotdoeverything;andforunusual,o rnew,tasksa newsetof instructionsmustbe thiscourseis to provideyouwiththenecessaryskillsto generateyourownlistsof instructionsso thatyoucanusecomputersto perform(almost)any programminglanguageis a setof keywordsandsyntaxrulesthatareusedto \tell"thecomputerwhatyouwant it to listof instructionswrittenin a programminglanguageis calledaprogramandis mostoftencreatedusingtexteditorsor thetexteditorcomponent of anintegrateddevelopment environment. Ultimately, theseinstruc-tionsmustbe translatedfromtheprogramminglanguageinto thenative languageof thecomputer(assemblyinstructions).
3 Thetranslationis performedby specialisedprogramsknownascompilers. In orderto usea programminglanguageyoumusthave a thetimeof writing,therearehundreds,if notthousands,of di erent programminglanguages,each withdi erent programminglanguageis driven in partby thenatureof (VBA)is thenative languageof Excelandis idealforwritingsmallextensions,or macros, essence, notsuitableforeverytask, thatthelanguageis notveryportable;everyExcelVBAprogrammust runfromwithinExcel,which meansthatyouneedtohave addition,forintensive numericalcalculations,VBAcanbe ++is perhapsbestdescribed as middle-level, highlyportable(therearecompilersforalmos tallcomputers),e cient thesenotes,we shalldiscusshow to useC++onitsownandin conjunctionwithExcel,allowingthedevelopm ent of powerfulande cient solutionsto aninterpretedlanguage;itscommandsaretran slatedinto assemblylanguage\lineby line"andthetranslationtakes uptimeduringtheexecutionof responsibleforcheckingthatwhatyouhave writtenis legal.
4 Obeyedallthesyntaxrulesandnotviolatedany restrictionsin ,a largeamount of timeis spent correctingyourprogramin responseto ,or built,theprogrammustthenbe run,or executed,at which pointthecomputerwillcarryoutthetasksspec i edin programcompiles,however,does notmeanthatit is perfectlypossibleto writeasyntacticallycorrectprogramthattri esto performanillegalaction,forexampledividin gby ,as opposedto compile-timeerrors,areanothersource,or rathersink,of development illustratedbelow:WriteCompileRunCompile- TimeDebuggingRun-TimeDebugging-- @@I XXXXXXXXXXXXXXXyFor complexprojects,theworkcyclecanbe simpli edby usinganintegrateddevel-opment environment (IDE),such as MicrosoftVisualStudio,or environment containsa texteditor,forwritingprograms;a compiler,forbuildingtheprograms.
5 Anda wholerangeof debuggingtoolsfortrackingdownproblemsdur ingthecompilationand/orexecutionof theunini-tiated,however,IDEscanseemoverw helmingwitha hugerangeof ++programEveryvalidC++programmust\tell"t hecompilerwhereitssetof instructionsstartsand ,everyC++programmustcontainafunction, seex3, thatcontainseveryinstructiontobe performedby calledmain()andthesimplestC++programis shownbelow:int main(){}Theprogramis veryboringbecausethefunctioncontainsnoin structions,butit willcompileandit ()willreturn1 INTRODUCTION5aninteger(a wholenumber)whenit C++,setsof instructionsaregroupedtogetherby braces,sometimescalledcurlybrackets,{};e verythingbetweenthebracesfollowingmain() willbe specifyarguments to functions, ispossibleto writeprogramsusingonlythemainfunction,bu tto doso wouldfailto takeadvantageof themorepowerfulstructuralfeaturesof C++.
6 ++keywordsThereare32keywordsde nedby theANSIC standard, youarepro-grammingin C, thesearetheonlykeywordsthatyouhave to remember and,in practice,theworkingvocabularyis ++standardde nesanadditional32keywords,shownin ++is a rapidlyevolvinglanguageandthenumber ofkeywordsmay stillchangein important in C++andkeywordsmustbe speci edin lower a keyword,butElse, oatshortunsignedcontinueforsignedvoiddef aultgotosizeofvolatiledoifstaticwhileTab le1: The32C thesourcecodeThekey elements of C++syntaxareshownbelow: A semicolonis usedto markendof aninstruction. Caseis important, notthesameasSIN. Totallyfreeform,linesandnamescanbe as longas youlike! Comments take theform/* C stylecomment*/or// C++ : The32 additionalC++keywords Groupsof instructionsaresurroundedby braces{}.
7 Themostimportant point to remember is thatallstatements mustendwitha semi-colon;. Often,forgettinga semicoloncancausea hugenumber of compilationerrors,particularlyif theomissionis nearthestartof a :compilingandrunningC++Beforeit canbe compiled,a C++programmustbe savedasa leand,by conven-tion,C++programsarelabelledby the ,. Largeprojectsmay, andprobablyshould,be splitinto separate les,which canbe compiledseparately. Thedivisionof largeprojectsinto separate\compilationunits"speedsupthere- compilationof thewholeprojectif onlyonesmallpartof of separate lesandtheirinterdependenceis anareain is to usecommand-linecompilationandkeeptrack of allthedi erent commandlineis,as thenamesuggests,a placewhereyoucanissue(type) starta program,youmusttype thenameof ,allcomputationwasperformedusingthecomma ndlineandit is stilleasier,andquicker,to considerboth\simple"command-linecompilat ionandcompilationwithinan IDE(VisualStudio)fora simpleprogramthatmerelyprints ++instructionthatperformsthistaskisstd:: cout<< "Hello"<< std::endl.
8 To writea smallC++programis to usea texteditor,say Notepad,to lethatcontainstherequiredinstructionsand thento compiletheprogramin a ++compileriscl , the lethatcontainsyourC++ illustratedin Figure1. Theresultof thecompilationprocessis Figure1:Anillustrationof Notepadwindowcontaininga simpleC++program, , thatwillprint thewordHelloonthescreen;anda VisualStudioCommandPromptshowingthecompi lationof In orderto ,or (andthenreturn)into thecommandprompt, of compilationwillworkforallsimpleprojects, thatis canbe madeto workformorecomplexprojects,butit becomesmoreandmoredi cultto betterway of managinglargeprojectsis , thiswillseemmorecomplicatedthanthesimple method outlinedabove, butit does notbecomesigni cantlymorecomplexas ,it is usedto write, VisualStudiois thatit automaticallyincludesa number libraryis a collectionoffunctionsthathave librariesshouldbe includeddependson thetype of programthatyou theprogramwillusegraphicsor interactwiththemouseit requiresmorelibrariesthana librariesareincludedby choosingyourprojecttype whencreatinga ,we shallconsideronly(Win32)
9 RsttimethatyourunVisualStudioyoumay be askedtoselecta defaultenvironment, in which caseyoushouldselect\VisualC++Development Settings".InVisualStudio2003(andearlier) ,theStartPageof VisualStudiocontainsa NewProjectbutton,which whenpressedbringsuptheNewProjectdialogbo x, ,thesamedialogbox is accessedby clickingtheProject:Createlinkin theRecent Projectswindow simpleC++programs,theprojectshouldbe a VisualC++ConsoleApplication,alsocalleda Win32 ConsoleApplication,locatedin theWin32submenu of theVisualC++ a name,e. , fortheprojectin thedialogbox anddouble-clickingontheConsoleApplicatio niconfromtheTemplateswindow (orclickingOpen in thedialogbox afterselectingtheConsoleApplicationicon) thedefaultsettings,simplypressFinishandV isualStudiowillthencreatea number of les,which shouldappearin theSolutionExplorerwindowonthesideof informationyoucandouble-click (theactualC++program)bringsupa shortsectionof1 INTRODUCTION9 Figure2 ConsoleApplicationcalledHellois aboutto be ++code,seeFigure3.
10 In orderto writeourownprogram,we comment outthepre-createdinstructionin thefunctioninttmain() thenbe compiledby goingto theBuildmenu , we canchoosetorunourprogramby selectingStartfromtheDebugmenu. If theprogramhasbeenmodi edwithoutcompilingit a dialogbox popsup,seeFigure4, pressingyes causestheprogramto be ,theentirewrite,compileandrunprocesstake s completedescriptionof thefeaturesof VisualStudiois wellbeyondthescope vastamount of informationis providedin Figure3:AVisualC++ConsoleApplication,Hel lo, TheRuncommandis aboutto be Figure4: VisualStudiodialogbox thatappearswhentryingto runa programwithoutre-compilation,clickingonY eswillcausetheprogramto be ++122 GettingstartedwithC++ data, ndingthemaxi-mumof a setof numbers,printingane-mail,modellingthegro wthof thestock market, C++,theparticulartype of each datummustbe declaredbeforeit canbe is possibleto createyourown\custom"datatypes,butforsim pletasksthesevenbuilt-indatatypes (char,wchart,bool,int, oat,doubleandvoid) aresu showsthetype of datarepresentedby the singlecharacter(letter)wcharta widecharacter(letter)(usedforcharactersf romnon-englishalphabets)boola booleandatum(trueor false)intanintegerdatum(wholenumber)floa ta oating-point datum(a realnumber withsixdigitsof precision)