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. 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.
2 Ultimately, theseinstruc-tionsmustbe translatedfromtheprogramminglanguageinto thenative languageof thecomputer(assemblyinstructions).Thetra nslationis 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.
3 Itscommandsaretranslatedinto assemblylanguage\lineby line"andthetranslationtakes uptimeduringtheexecutionof responsibleforcheckingthatwhatyouhave writtenis legal; 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.
4 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++. ++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.
5 Caseis important, notthesameasSIN. Totallyfreeform,linesandnamescanbe as longas youlike! Comments take theform/* C stylecomment*/or// C++ : The32 additionalC++keywords Groupsof instructionsaresurroundedby braces{}.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; to writea smallC++programis to usea texteditor,say Notepad,to lethatcontainstherequiredinstructionsand thento compiletheprogramin a ++compileriscl , the lethatcontainsyourC++ illustratedin Figure1.
6 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) rsttimethatyourunVisualStudioyoumay be askedtoselecta defaultenvironment, in which caseyoushouldselect\VisualC++Development Settings".
7 InVisualStudio2003(andearlier),theStartP ageof 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. In orderto writeourownprogram,we comment outthepre-createdinstructionin thefunctioninttmain() thenbe compiledby goingto theBuildmenu , we canchoosetorunourprogramby selectingStartfromtheDebugmenu.
8 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)doublea double-precision, oating-point datum(a realnumber withtendigitsof precision)Table3.
9 The(non-void)C++ is ratherspecialandis usedto declarea functionthatdoes notreturna value(a subroutine), a namedlocationin memory, usedto storesomethingthatmay be modi edby , providedthatthenameyouchoosedoes notstartwithanumber,is nota C++keywordandis notthesameas any othervariablewithinthesamescope, is usuallya good ideato usedescriptive :int i,j,k;doublea,b;charinitial;2 GETTINGSTARTEDWITHC++13 Notethatcommasmay be usedto separatevariablesof thesametype andthateach lineendswitha a variablemay be assignedwhenthevariableis a sourceof mysteriouserrors,so it'sa goodideato initialiseyourvariablesif practical:int i=0,j=1,k=2;doublea= ;charch='a';Notethatcharactersmustbe enclosedin singlequotes'. of variablesC++permitsthedeclarationof variablesanywherewithinyourprogram,buta variablecanonlybe usedbetweenthebraces{}withinwhich it is whichthevariablecanbe usedis knownas itsscope. Anadvantageof localscopes is thatyoucanusethesamenameforvariableswith indi erent regionsof main()int main(){{//Declarea in new scope//Declarea in currentscope{inta = 10;}int a=10;//Declarea in new scope(ok)//Re-declarea in scope(illegal){inta = 15;}int a = 15;//a usedoutsidescope(illegal)//a usedin scope(ok)a = 20;a = 20;}}Neitherofthetwo 'a' : undeclaredidentifierbecauseahasnotbeende -claredin failsonthefourthlineofmainwiththeerror'a ' : redefinition;multipleinitializationbecau sethevariableacannotbe de-claredtwicein a justlike an array in maths:a collectionof variablesof thesametype, calledby thesamename,buteach witha di erent to de neanarrayis to enclosethedimensionin squarebrackets[] ++14int x[100];// 100 integerarraydoubley[300];// Arrayof 300 doublesArrays areinitialisedby usingbracesto de nethearray andcommasto separatetheindividualarray entries:doublex[3]= { , , }.
10 Theindividualentriesof anarray areaccessedby addinga singlenumber in [3]hastheentriesx[0](=1:0),x[1](=2:5) andx[2](=3:7).Important note:In C++,array aredeclaredandinitialisedin anobviousway:doublematrix[10][10];int 3dtensor[3][3][3]= {{1,2,3},{4,5,6},{7,8,9}};Themaximumnumb er of dimensions,if any, is determinedby de nedin thisway areallocatedin thestack, anareaof memorydesignedto thestack is setby memorythatis designedto storelonger-lived variablesis knownas theheap,butcanonlybe many cases,thesizeof thearray willnotbe ,if we arereadingin datafroma lethenthetotalnumber of datawilldependonthesizeof the thesesituationstherearetwo options: StaticAllocation:Allocatea xed,butlarge,amount of storage,doubleA[1000];(possiblylimitedby stack size). DynamicAllocation:Determinetheexactamoun t of storagerequiredas C++dynamicmemoryallocationis handledby pointers,which aredeclaredusingthe* *A_dynamic;2 GETTINGSTARTEDWITHC++15We have declaredthevariableA_dynamicas apointerto a double,or anaddressinmemory.