+ All Categories
Home > Documents > CS 110 Computer Architecture Lecture 2: Introduction to C ...CS 110 Computer Architecture Lecture 2:...

CS 110 Computer Architecture Lecture 2: Introduction to C ...CS 110 Computer Architecture Lecture 2:...

Date post: 17-Feb-2021
Category:
Upload: others
View: 3 times
Download: 0 times
Share this document with a friend
44
CS 110 Computer Architecture Lecture 2: Introduction to C, Part I Instructor: Sören Schwertfeger http://shtech.org/courses/ca/ School of Information Science and Technology SIST ShanghaiTech University 1 Slides based on UC Berkley's CS61C
Transcript
  • CS110ComputerArchitecture

    Lecture2:IntroductiontoC,PartI

    Instructor:SörenSchwertfeger

    http://shtech.org/courses/ca/

    School of Information Science and Technology SIST

    ShanghaiTech University

    1Slides based on UC Berkley's CS61C

  • Agenda

    • EverythingisaNumber• Compilevs.Interpret• Administrivia• QuickStartIntroductiontoC• Pointers• AndinConclusion,…

    2

  • Agenda

    • EverythingisaNumber• Compilevs.Interpret• Administrivia• QuickStartIntroductiontoC• Pointers• AndinConclusion,…

    3

  • BIG IDEA: Bits can represent anything!!• Characters?

    – 26 letters Þ 5 bits (25 = 32)– upper/lower case + punctuation

    Þ 7 bits (in 8) (“ASCII”)

    – standard code to cover all the world’s languages Þ 8,16,32 bits (“Unicode”)www.unicode.com

    • Logical values?– 0 ® False, 1 ® True

    • colors ? Ex:

    • locations / addresses? commands?

    • MEMORIZE: N bits Û at most 2N things

    Red (00) Green (01) Blue (11)

  • KeyConcepts• Insidecomputers,everythingisanumber• Butnumbersusuallystoredwithafixedsize– 8-bitbytes,16-bithalfwords,32-bitwords,64-bitdoublewords,…

    • Integerandfloating-pointoperationscanleadtoresultstoobig/smalltostorewithintheirrepresentations:overflow/underflow

    5

  • NumberRepresentation

    • Valueofi-th digitisd × Baseiwherei startsat0andincreasesfromrighttoleft:

    • 12310=110 x 10102 +210 x 10101 +310 x 10100=1x10010 +2x1010 +3x110=10010 +2010 +310=12310

    • Binary(Base2),Hexadecimal(Base16),Decimal(Base10)differentwaystorepresentaninteger– Weuse1two,5ten,10hex tobeclearer

    (vs.12,48,510,1016)

    6

  • NumberRepresentation

    • Hexadecimaldigits:0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F

    • FFFhex =15tenx16ten2 +15tenx16ten1 +15tenx16ten0=3840ten +240ten +15ten=4095ten

    • 111111111111two =FFFhex =4095ten• Mayputblankseverygroupofbinary,octal,orhexadecimaldigitstomakeiteasiertoparse,likecommasindecimal

    7

  • SignedandUnsignedIntegers

    • C,C++,andJavahavesignedintegers,e.g.,7,-255:int x, y, z;

    • C,C++alsohaveunsignedintegers,e.g.foraddresses

    • 32-bitwordcanrepresent232 binarynumbers• Unsignedintegersin32bitwordrepresent0to232-1(4,294,967,295)(4Gig)

    8

  • UnsignedIntegers00000000000000000000000000000000two =0ten00000000000000000000000000000001two =1ten00000000000000000000000000000010two =2ten

    ... ...01111111111111111111111111111101two =2,147,483,645ten01111111111111111111111111111110two =2,147,483,646ten01111111111111111111111111111111two =2,147,483,647ten10000000000000000000000000000000two =2,147,483,648ten10000000000000000000000000000001two =2,147,483,649ten10000000000000000000000000000010two =2,147,483,650ten

    ... ...11111111111111111111111111111101two =4,294,967,293ten11111111111111111111111111111110two =4,294,967,294ten11111111111111111111111111111111two =4,294,967,295ten

    9

  • SignedIntegersandTwo’s-ComplementRepresentation

    • SignedintegersinC;want½numbers0,andwantone0

    • Two’scomplementtreats0aspositive,so32-bitwordrepresents232integersfrom-231(–2,147,483,648)to231-1(2,147,483,647)– Note:onenegativenumberwithnopositiveversion– Booklistssomeotheroptions,allofwhichareworse– Everycomputerusestwo’scomplementtoday

    • Most-significantbit(leftmost)isthesignbit,since0meanspositive(including0),1meansnegative– Bit31ismostsignificant,bit0isleastsignificant

    10

  • Two’s-ComplementIntegers00000000000000000000000000000000two =0ten00000000000000000000000000000001two =1ten00000000000000000000000000000010two =2ten

    ... ...01111111111111111111111111111101two =2,147,483,645ten01111111111111111111111111111110two =2,147,483,646ten01111111111111111111111111111111two =2,147,483,647ten10000000000000000000000000000000two =–2,147,483,648ten10000000000000000000000000000001two =–2,147,483,647ten10000000000000000000000000000010two =–2,147,483,646ten

    ... ...11111111111111111111111111111101two =–3ten11111111111111111111111111111110two =–2ten11111111111111111111111111111111two =–1ten

    11

    SignBit

  • WaystoMakeTwo’sComplement• ForN-bitword,complementto2tenN

    – For4bitnumber3ten=0011two,two’scomplement

    (i.e.-3ten)wouldbe

    16ten-3ten=13ten or10000two – 0011two =1101two

    12

    • Hereisaneasierway:– Invertallbitsandadd1

    – Computersactuallydoitlikethis,too

    0011two

    1100two+1two

    3ten

    1101two

    Bitwisecomplement

    -3ten

  • Two’s-ComplementExamples

    • Assumeforsimplicity4bitwidth,-8to+7represented

    13

    00110010

    3+25 0101

    00111110

    3+(-2)

    1 10001

    01110001

    7+1-8 1000Overflow!

    11011110

    -3+(-2)

    -5 11011

    10001111

    -8+(-1)+7 10111

    CarryintoMSB=CarryOutMSB

    CarryintoMSB=CarryOutMSB

    Overflow!

    Overflowwhenmagnitudeofresulttoobigtofitintoresultrepresentation

    Carryin=carryfromlesssignificantbitsCarryout=carrytomoresignificantbits

  • 0to+31

    -16to+15

    -32to+31

    B

    C

    D

    14

    Supposewehada5-bitword.Whatintegerscanberepresentedintwo’scomplement?

    A

  • 0to+31

    -16to+15

    15

    Supposewehada5-bitword.Whatintegerscanberepresentedintwo’scomplement?

    B

    C

    D

    A -32to+31

  • Agenda

    • EverythingisaNumber• Compilevs.Interpret• Administrivia• QuickStartIntroductiontoC• Pointers• AndinConclusion,…

    16

  • Processor

    Control

    Datapath

    ComponentsofaComputer

    17

    PC

    Registers

    Arithmetic&LogicUnit(ALU)

    MemoryInput

    Output

    Bytes

    Enable?Read/Write

    Address

    WriteData

    ReadData

    Processor-MemoryInterface I/O-MemoryInterfaces

    Program

    Data

  • GreatIdea:LevelsofRepresentation/Interpretation

    lw t0,0(s2)lw t1,4(s2)sw t1,0(s2)sw t0,4(s2)

    HighLevelLanguageProgram(e.g.,C)

    AssemblyLanguageProgram(e.g.,RISC-V)

    MachineLanguageProgram(RISC-V)

    HardwareArchitectureDescription(e.g.,blockdiagrams)

    Compiler

    Assembler

    MachineInterpretation

    temp=v[k];v[k]=v[k+1];v[k+1]=temp;

    0000 1001 1100 0110 1010 1111 0101 10001010 1111 0101 1000 0000 1001 1100 0110 1100 0110 1010 1111 0101 1000 0000 1001 0101 1000 0000 1001 1100 0110 1010 1111

    LogicCircuitDescription(CircuitSchematicDiagrams)

    ArchitectureImplementation

    Anythingcanberepresentedasanumber,

    i.e.,dataorinstructions

    18

    Wearehere!

  • IntroductiontoC“TheUniversalAssemblyLanguage”

    19

  • IntrotoC• Cisnota“veryhigh-level”language,nora“big”one,andisnotspecializedtoanyparticularareaofapplication.Butitsabsenceofrestrictionsanditsgeneralitymakeitmoreconvenientandeffectiveformanytasksthansupposedlymorepowerfullanguages.

    – KernighanandRitchie• Enabledfirstoperatingsystemnotwritteninassemblylanguage:UNIX- AportableOS!

    20

  • IntrotoC

    • WhyC?:wecanwriteprogramsthatallowustoexploitunderlyingfeaturesofthearchitecture– memorymanagement,specialinstructions,parallelism

    • Candderivatives(C++/Obj-C/C#)stilloneofthemostpopularapplicationprogramminglanguagesafter>40years!

    21

  • Disclaimer

    • YouwillnotlearnhowtofullycodeinCintheselectures!You’llstillneedyourCreferenceforthiscourse– K&Risamust-have• Checkonlineformoresources

    • KeyCconcepts:Pointers,Arrays,ImplicationsforMemorymanagement

    • WewilluseANSIC89– original”oldschool”C– BecauseitisclosesttoAssembly

    22

  • Compilation:Overview

    • CcompilersmapCprogramsintoarchitecture-specificmachinecode(stringof1sand0s)– UnlikeJava,whichconvertstoarchitecture-independentbytecode

    – UnlikePythonenvironments,whichinterpretthecode– Thesediffermainlyinexactlywhenyourprogramisconvertedtolow-levelmachineinstructions(“levelsofinterpretation”)

    – ForC,generallyatwopartprocessofcompiling.c filesto.o files,thenlinkingthe.o filesintoexecutables;

    – Assemblingisalsodone(butishidden,i.e.,doneautomatically,bydefault);we’lltalkaboutthatlater

    23

  • CCompilationSimplifiedOverview(morelaterincourse)

    24

    foo.c bar.c

    Compiler Compiler

    foo.o bar.o

    Linker lib.o

    a.out

    Csourcefiles(text)

    Machinecodeobjectfiles

    Pre-builtobjectfilelibraries

    Machinecodeexecutablefile

    Compiler/assemblercombinedhere

  • Compilation:Advantages

    • Excellentrun-timeperformance:generallymuchfasterthanSchemeorJavaforcomparablecode(becauseitoptimizesforagivenarchitecture)

    • Reasonablecompilationtime:enhancementsincompilationprocedure(Makefiles)allowonlymodifiedfilestoberecompiled

    25

  • Compilation:Disadvantages

    • Compiledfiles,includingtheexecutable,arearchitecture-specific,dependingonprocessortype(e.g.,MIPSvs.RISC-V)andtheoperatingsystem(e.g.,Windowsvs.Linux)

    • Executablemustberebuiltoneachnewsystem– I.e.,“portingyourcode”toanewarchitecture

    • “Change® Compile® Run[repeat]”iterationcyclecanbeslowduringdevelopment– butMaketoolonlyrebuildschangedpieces,andcandocompilesinparallel(linkerissequentialthough->Amdahl’sLaw)

    26

  • CPre-Processor(CPP)

    • Csourcefilesfirstpassthroughmacroprocessor,CPP,beforecompilerseescode

    • CPPreplacescommentswithasinglespace• CPPcommandsbeginwith“#”• #include“file.h”/*Insertsfile.h intooutput*/• #include/*Looksforfileinstandardlocation*/• #defineM_PI(3.14159)/*Defineconstant*/• #if/#endif /*Conditionalinclusionoftext*/• Use-save-tempsoptiontogcc toseeresultofpreprocessing• Fulldocumentationat:http://gcc.gnu.org/onlinedocs/cpp/

    27

    foo.c CPP foo.i Compiler

  • TypedVariablesinCint variable1 = 2;float variable2 = 1.618;

    char variable3 = 'A';

    • Mustdeclarethetypeofdataavariablewillhold– Typescan'tchange

    28

    Type Description Examplesint integernumbers,includingnegatives 0,78,-1400unsignedint integernumbers(nonegatives) 0,46,900long largersignedinteger -6,000,000,000char singletextcharacterorsymbol 'a','D','?’float floatingpointdecimalnumbers 0.0,1.618,-1.4double greaterprecision/bigFPnumber 10E100

  • Integers:Pythonvs.Javavs.C

    • C:int shouldbeintegertypethattargetprocessorworkswithmostefficiently

    • Onlyguarantee:sizeof(long long)≥sizeof(long)≥sizeof(int)≥sizeof(short)– Also,short >=16bits,long >=32bits– Allcouldbe64bits 29

    Language sizeof(int)Python >=32bits(plainints),infinite (longints)Java 32bitsC Dependsoncomputer;16 or32or64

  • Consts andEnums inC

    • Constantisassignedatypedvalueonceinthedeclaration;valuecan'tchangeduringentireexecutionofprogramconst float golden_ratio = 1.618;const int days_in_week = 7;

    • YoucanhaveaconstantversionofanyofthestandardCvariabletypes

    • Enums:agroupofrelatedintegerconstants.Ex:enum cardsuit {CLUBS,DIAMONDS,HEARTS,SPADES};enum color {RED, GREEN, BLUE};

    30

  • B:Canassignto“PI”butnot“pi”

    C:Coderunsatsamespeedusing“PI”or“pi”

    A:Constants“PI”and“pi”havesametype

    31

    Compare“#define PI 3.14”and“const float pi=3.14”– whichistrue?

  • Agenda

    • EverythingisaNumber• Compilevs.Interpret• Administrivia• QuickStartIntroductiontoC• Pointers• AndinConclusion,…

    32

  • Administrivia• Findapartnerforthelab.InformyourlabTAaboutyourpartnerselectionduringlab1.Partnerteamsshouldbe2persons– therecanbeexactlyone3personlabteamperlab.

    • Labsstartnextweek!Checkyourschedule!Youcannotgetcheckedwithoutapartner!

    • ThetasksforLab1arepostedonthewebsite.Prepareforitovertheweekend.

    33

  • Administrivia• WehaveregisteredyouforAutolab yesterdaynight.

    • HW1isavailableonAutolab.DuenextThursday.• Websiteisdown.Hopefullywillbeupsoon.Slideswillbepostedonpiazzafornow.MaybeLab1,too.

    • Registerinpiazza!Willbepartofyourgrade!– Therearealsoappsforyourphone…

    34

  • Agenda

    • EverythingisaNumber• Compilevs.Interpret• Administrivia• QuickStartIntroductiontoC• Pointers• AndinConclusion,…

    35

  • TypedFunctionsinC

    int number_of_people (){return 3;

    }

    float dollars_and_cents (){return 10.33;

    }

    int sum ( int x, int y){

    return x + y;}

    • Youhavetodeclarethetypeofdatayouplantoreturnfromafunction

    • ReturntypecanbeanyCvariabletype,andisplacedtotheleftofthefunctionname

    • Youcanalsospecifythereturntypeasvoid– Justthinkofthisassayingthatnovalue

    willbereturned• Alsonecessarytodeclaretypes

    forvaluespassedintoafunction• VariablesandfunctionsMUSTbe

    declaredbeforetheyareused

    36

  • Structs inC• Structs arestructuredgroupsof

    variables,e.g.,

    typedef struct {int length_in_seconds;int year_recorded;

    } Song;

    Song song1;

    song1.length_in_seconds = 213;song1.year_recorded = 1994;

    Song song2;

    song2.length_in_seconds = 248;song2.year_recorded = 1988;

    37

    Dotnotation:x.y = value

  • AFirstCProgram:HelloWorldOriginal C:

    main(){printf("\nHello World\n");

    }

    ANSI Standard C:

    #include

    int main(void){printf("\nHello World\n");return 0;

    }

    38

  • CSyntax:main

    • WhenCprogramstarts– Cexecutablea.out isloadedintomemorybyoperatingsystem(OS)

    – OSsetsupstack,thencallsintoCruntimelibrary,– Runtime1st initializesmemoryandotherlibraries,– thencallsyourprocedurenamedmain()

    • We’llseehowtoretrievecommand-lineargumentsinmain()later…

    39

  • ASecondCProgram:ComputeTableofSines

    #include #include

    int main(void){

    int angle_degree;double angle_radian, pi, value;/* Print a header */printf("\nCompute a table of the sine function\n\n");

    /* obtain pi once for all *//* or just use pi = M_PI, where *//* M_PI is defined in math.h */pi = 4.0*atan(1.0);printf("Value of PI = %f \n\n", pi);

    printf("angle Sine \n");

    angle_degree = 0;/* initial angle value *//* scan over angle */while (angle_degree 360 */

    {angle_radian = pi*angle_degree/180.0;value = sin(angle_radian);printf (" %3d %f \n ",

    angle_degree, value);angle_degree = angle_degree + 10; /* increment the loop index */

    }return 0;}

    40

  • SecondCProgramSampleOutput

    Compute a table of the sine function

    Value of PI = 3.141593

    angle Sine 0 0.000000

    10 0.173648 20 0.342020 30 0.500000 40 0.642788 50 0.766044 60 0.866025 70 0.939693 80 0.984808 90 1.000000

    100 0.984808 110 0.939693 120 0.866025 130 0.766044 140 0.642788 150 0.500000 160 0.342020 170 0.173648 180 0.000000

    190 -0.173648 200 -0.342020 210 -0.500000 220 -0.642788 230 -0.766044 240 -0.866025 250 -0.939693 260 -0.984808 270 -1.000000 280 -0.984808 290 -0.939693 300 -0.866025 310 -0.766044 320 -0.642788 330 -0.500000 340 -0.342020 350 -0.173648 360 -0.000000

    41

  • CSyntax:VariableDeclarations

    • Allvariabledeclarationsmustappearbeforetheyareused(e.g.,atthebeginningoftheblock)

    • Avariablemaybeinitializedinitsdeclaration;ifnot,itholdsgarbage!

    • Examplesofdeclarations:– Correct: {

    int a = 0, b = 10;...

    −Incorrect: for (int i = 0; i < 10; i++)}

    42NewerCstandardsaremoreflexibleaboutthis,morelater

  • CSyntax:ControlFlow(1/2)

    • Withinafunction,remarkablyclosetoJavaconstructsintermsofcontrolflow– if-else

    • if (expression) statement• if (expression) statement1else statement2

    – while• while (expression)

    statement• do

    statementwhile (expression);

    43

  • CSyntax:ControlFlow(2/2)

    – for• for (initialize; check; update) statement

    – switch• switch (expression){

    case const1: statementscase const2: statementsdefault: statements

    }• break

    44


Recommended