50
1 Introduction to “C” Introduction to “C” HLL’s and the Basic HLL’s and the Basic Syntax Syntax Patt and Patel Ch. 11 & Patt and Patel Ch. 11 & 12 12

1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

  • View
    215

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

1

Introduction to “C”Introduction to “C”HLL’s and the Basic HLL’s and the Basic

Syntax Syntax Patt and Patel Ch. 11 & 12Patt and Patel Ch. 11 & 12

Page 2: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

2

C: A High-Level LanguageC: A High-Level LanguageGives symbolic names to valuesGives symbolic names to values

– don’t need to know which register or memory location

Provides abstraction of underlying hardwareProvides abstraction of underlying hardware

– operations do not depend on instruction set– example: can write “a = b * c”, even though

LC-3 doesn’t have a multiply instruction

Provides expressivenessProvides expressiveness

– use meaningful symbols that convey meaning– simple expressions for common control patterns (if-then-

else)

Enhances code readabilityEnhances code readability

Safeguards against bugsSafeguards against bugs

– can enforce rules or conditions at compile-time or run-time

Page 3: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

3

Compilation vs. InterpretationCompilation vs. InterpretationDifferent ways of translating high-level languageDifferent ways of translating high-level language

InterpretationInterpretation

– interpreter = program that executes program statements– generally one line/command at a time– limited processing– easy to debug, make changes, view intermediate results– languages: BASIC, LISP, Perl, Java, Matlab, C-shell

CompilationCompilation

– translates statements into machine language• does not execute, but creates executable program

– performs optimization over multiple statements– change requires recompilation

• can be harder to debug, since executed code may be different

– languages: C, C++, Fortran, Pascal

Page 4: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

4

Consider the following algorithm:Consider the following algorithm:

Get W from the keyboard.

X = W + W

Y = X + X

Z = Y + Y

Print Z to screen.

•If If interpretinginterpreting, how many arithmetic operations occur?, how many arithmetic operations occur?

•If If compilingcompiling, we can analyze the entire program and , we can analyze the entire program and possibly reduce the number of operations. Can we simplify possibly reduce the number of operations. Can we simplify the above algorithm to use a single arithmetic operation?the above algorithm to use a single arithmetic operation?

Compilation vs. Interpretation

Page 5: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

5

Compiling a C Compiling a C ProgramProgramEntire mechanism is usually called Entire mechanism is usually called the “compiler”the “compiler”

PreprocessorPreprocessor

– macro substitution– conditional compilation– “source-level” transformations

• output is still C

CompilerCompiler

– generates object file• machine instructions

LinkerLinker

– combine object files(including libraries)into executable image

CSource andHeader Files

C Preprocessor

Compiler

Source CodeAnalysis

Target CodeSynthesis

Symbol Table

Linker

ExecutableImage

LibraryObject Files

Page 6: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

6

CompilerCompilerSource Code AnalysisSource Code Analysis

– “front end”– parses programs to identify its pieces

• variables, expressions, statements, functions, etc.– depends on language (not on target machine)

Code GenerationCode Generation

– “back end”– generates machine code from analyzed source– may optimize machine code to make it run more

efficiently– very dependent on target machine

Symbol TableSymbol Table

– map between symbolic names and items– like assembler, but more kinds of information

Page 7: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

7

A Simple C ProgramA Simple C Program#include <stdio.h>#include <stdio.h>

#define STOP 0#define STOP 0

/* Function: main *//* Function: main */

/* Description: counts down from user input to STOP *//* Description: counts down from user input to STOP */

main()main()

{{

/* variable declarations *//* variable declarations */

int counter; int counter; /* an integer to hold count values *//* an integer to hold count values */

int startPoint; int startPoint; /* starting point for countdown *//* starting point for countdown */

/* prompt user for input *//* prompt user for input */

printf("Enter a positive number: ");printf("Enter a positive number: ");

scanf("%d", &startPoint); scanf("%d", &startPoint); /* read into startPoint *//* read into startPoint */

/* count down and print count *//* count down and print count */

for (counter=startPoint; counter >= STOP; counter--)for (counter=startPoint; counter >= STOP; counter--)

printf("%d\n", counter);printf("%d\n", counter);

}}

Page 8: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

8

Preprocessor DirectivesPreprocessor Directives#include <stdio.h>#include <stdio.h>

– Before compiling, copy contents of header file (stdio.h)into source code.

– Header files typically contain descriptions of functions and variables needed by the program.

• no restrictions -- could be any C source code

#define STOP 0#define STOP 0

– Before compiling, replace all instances of the string"STOP" with the string "0"

– Called a macro– Used for values that won't change during execution,

but might change if the program is reused. (Must recompile.)

Page 9: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

9

CommentsComments

•Begins with Begins with /*/* and ends with and ends with */*/

•Can span multiple linesCan span multiple lines

•Cannot have a comment within a commentCannot have a comment within a comment

•Comments are not recognized within a stringComments are not recognized within a string

– example: "my/*don't print this*/string"would be printed as: my/*don't print this*/string

As before, use comments to help reader, not to As before, use comments to help reader, not to confuse or to restate the obviousconfuse or to restate the obvious

Page 10: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

10

mainmain Function Function

•Every C program must have a function called Every C program must have a function called main()main()..

•This is the code that is executed when the program is run.This is the code that is executed when the program is run.

•The code for the function lives within brackets:The code for the function lives within brackets:

main()main()

{{

/* code goes here *//* code goes here */

}}

Page 11: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

11

Variable DeclarationsVariable Declarations

•Variables are used as names for data items.Variables are used as names for data items.

•Each variable has a Each variable has a typetype, which tells the compiler how , which tells the compiler how the data is to be interpreted (and how much space it the data is to be interpreted (and how much space it needs, etc.).needs, etc.).

intint counter;counter;

intint startPoint;startPoint;

intint is a predefined integer type in C.is a predefined integer type in C.

Page 12: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

12

Input and OutputInput and Output•Variety of I/O functions in Variety of I/O functions in C Standard LibraryC Standard Library..

•Must include Must include <stdio.h><stdio.h> to use them. to use them.

printf("%d\n", counter);printf("%d\n", counter);

– String contains characters to print and formatting directions for variables.

– This call says to print the variable counter as a decimal integer, followed by a linefeed (\n).

scanf("%d", &startPoint);scanf("%d", &startPoint);

– String contains formatting directions for looking at input.– This call says to read a decimal integer and assign it to

thevariable startPoint. (Don't worry about the & yet.)

Page 13: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

13

More About OutputMore About Output

•Can print arbitrary expressions, not just variablesCan print arbitrary expressions, not just variables

printf("%d\n", startPoint - counter);printf("%d\n", startPoint - counter);

•Print multiple expressions with a single statementPrint multiple expressions with a single statement

printf("%d %d\n", counter, printf("%d %d\n", counter, startPoint - counter); startPoint - counter);

•Different formatting options:Different formatting options:

%d%d decimal integer decimal integer

%x%x hexadecimal integer hexadecimal integer

%c%c ASCII character ASCII character

%f%f floating-point number floating-point number

Page 14: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

14

ExamplesExamples

•This code:This code:

printf("%d is a prime number.\n", 43);printf("%d is a prime number.\n", 43);

printf("43 plus 59 in decimal is %d.\n", 43+59);printf("43 plus 59 in decimal is %d.\n", 43+59);

printf("43 plus 59 in hex is %x.\n", 43+59);printf("43 plus 59 in hex is %x.\n", 43+59);

printf("43 plus 59 as a character is %c.\n", 43+59);printf("43 plus 59 as a character is %c.\n", 43+59);

•produces this output:produces this output:

43 is a prime number.43 is a prime number.

43 + 59 in decimal is 102.43 + 59 in decimal is 102.

43 + 59 in hex is 66.43 + 59 in hex is 66.

43 + 59 as a character is f.43 + 59 as a character is f.

Page 15: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

15

Examples of InputExamples of Input•Many of the same formatting characters are available for user input.Many of the same formatting characters are available for user input.

scanf("%c", &nextChar);scanf("%c", &nextChar);

– reads a single character and stores it in nextChar

scanf("%f", &radius);scanf("%f", &radius);

– reads a floating point number and stores it in radius

scanf("%d %d", &length, &width);scanf("%d %d", &length, &width);

– reads two decimal integers (separated by whitespace), stores the first one in length and the second in width

•Must use ampersand Must use ampersand ((&&)) for variables being modified. for variables being modified.(Explained in Chapter 16.)(Explained in Chapter 16.)

Page 16: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

16

Compiling and LinkingCompiling and Linking

•Various compilers availableVarious compilers available

– cc, gcc, MS Visual Studio– includes preprocessor, compiler, and linker

•Lots and lots of options!Lots and lots of options!

– level of optimization, debugging– preprocessor, linker options– intermediate files --

object (.o), assembler (.s), preprocessor (.i), etc.

Page 17: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

17

Basic C ElementsBasic C ElementsVariablesVariables

– named, typed data items

OperatorsOperators

– predefined actions performed on data items– combined with variables to form

expressions, statements

•Rules and usageRules and usage

•Implementation using LC-3Implementation using LC-3

Page 18: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

18

Data TypesData TypesC has three basic data typesC has three basic data types

intint integer (at least 16 bits)integer (at least 16 bits)

doubledouble floating point (at least 32 bits)floating point (at least 32 bits)

charchar character (at least 8 bits)character (at least 8 bits)

Exact size can vary, depending on processorExact size can vary, depending on processor

– int is supposed to be "natural" integer size; for LC-3, that's 16 bits -- 32 bits for most modern processors

Page 19: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

19

Variable NamesVariable NamesAny combination of letters, numbers, and underscore (_)Any combination of letters, numbers, and underscore (_)

Case mattersCase matters

– "sum" is different than "Sum"

Cannot begin with a numberCannot begin with a number

– usually, variables beginning with underscoreare used only in special library routines

Only first 31 characters are usedOnly first 31 characters are used

Page 20: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

20

ExamplesExamples

LegalLegal

iiwordsPerSecondwordsPerSecondwords_per_secondwords_per_second_green_greenaReally_longName_moreThan31charsaReally_longName_moreThan31charsaReally_longName_moreThan31charactersaReally_longName_moreThan31characters

IllegalIllegal

10sdigit10sdigitten'sdigitten'sdigitdone?done?doubledouble

reserved keyword

same identifier

Page 21: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

21

LiteralsLiteralsIntegerInteger

123 /* decimal */123 /* decimal */

-123-123

0x123 /* hexadecimal */0x123 /* hexadecimal */

Floating pointFloating point

6.0236.023

6.023e23 /* 6.023 x 106.023e23 /* 6.023 x 102323 */ */

5E12 /* 5.0 x 105E12 /* 5.0 x 101212 */ */

CharacterCharacter

'c''c'

'\n' /* newline */'\n' /* newline */

'\xA' /* ASCII 10 (0xA) */'\xA' /* ASCII 10 (0xA) */

Page 22: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

22

Scope: Global and LocalScope: Global and LocalWhere is the variable accessible?Where is the variable accessible?

– Global: accessed anywhere in program– Local: only accessible in a particular region

Compiler infers scope from where variable is declaredCompiler infers scope from where variable is declared

– programmer doesn't have to explicitly state

Variable is local to the block in which it is declaredVariable is local to the block in which it is declared

– block defined by open and closed braces { }– can access variable declared in any "containing" block

•Global variable is declared outside all blocksGlobal variable is declared outside all blocks

Page 23: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

23

ExampleExample#include <stdio.h>#include <stdio.h>

int itsGlobal = 0;int itsGlobal = 0;

main()main()

{{

int itsLocal = 1; /* local to main */int itsLocal = 1; /* local to main */

printf("Global %d Local %d\n", itsGlobal, itsLocal);printf("Global %d Local %d\n", itsGlobal, itsLocal);

{{

int itsLocal = 2; /* local to this block */int itsLocal = 2; /* local to this block */

itsGlobal = 4; /* change global variable */itsGlobal = 4; /* change global variable */

printf("Global %d Local %d\n", itsGlobal, itsLocal);printf("Global %d Local %d\n", itsGlobal, itsLocal);

}}

printf("Global %d Local %d\n", itsGlobal, itsLocal);printf("Global %d Local %d\n", itsGlobal, itsLocal);

}}

OutputOutput

Global 0 Local 1Global 0 Local 1Global 4 Local 2Global 4 Local 2Global 4 Local 1Global 4 Local 1

Page 24: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

24

OperatorsOperators•Programmers manipulate variables using the Programmers manipulate variables using the operatorsoperators provided by the high-level language. provided by the high-level language.

•Variables and operators combine to form Variables and operators combine to form expressionsexpressions and and statementsstatements which denote the work which denote the work to be done by the program.to be done by the program.

•Each operator may correspond to many machine Each operator may correspond to many machine instructions.instructions.

– Example: The multiply operator (*) typically requires multiple LC-3 ADD instructions.

Page 25: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

25

ExpressionExpression

Any combination of variables, constants, operators, Any combination of variables, constants, operators, and function callsand function calls

– every expression has a type, derived from the types of its components (according to C typing rules)

Examples:Examples:

counter >= STOPcounter >= STOP

x + sqrt(y)x + sqrt(y)

x & z + 3 || 9 - w-- % 6x & z + 3 || 9 - w-- % 6

Page 26: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

26

StatementStatement•Expresses a complete unit of workExpresses a complete unit of work

– executed in sequential order

•Simple statement ends with semicolonSimple statement ends with semicolon

z = x * y;z = x * y;/* assign product to z *//* assign product to z */

y = y + 1;y = y + 1;/* after multiplication *//* after multiplication */

; ; /* null statement *//* null statement */

•Compound statement groups simple statements using Compound statement groups simple statements using braces. braces.

– syntactically equivalent to a simple statement

{ z = x * y; y = y + 1; }{ z = x * y; y = y + 1; }

Page 27: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

27

OperatorsOperatorsThree things to know about each operatorThree things to know about each operator

(1) Function(1) Function

– what does it do?

(2) Precedence(2) Precedence

– in which order are operators combined?– Example:

"a * b + c * d" is the same as "(a * b) + (c * d)"because multiply (*) has a higher precedence than addition (+)

(3) Associativity(3) Associativity

– in which order are operators of the same precedence combined?– Example:

"a - b - c" is the same as "(a - b) - c"because add/sub associate left-to-right

Page 28: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

28

Assignment OperatorAssignment Operator

Changes the value of a variable.Changes the value of a variable.

x = x + 4;x = x + 4;

1. Evaluate right-hand side.

2. Set value of left-hand side variable to result.

Page 29: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

29

Assignment OperatorAssignment OperatorAll expressions evaluate to a value, even ones with All expressions evaluate to a value, even ones with the assignment operator.the assignment operator.

For assignment, the result is the value assigned.For assignment, the result is the value assigned.

– usually (but not always) the value of the right-hand side• type conversion might make assigned value different

than computed value

Assignment associates right to left.Assignment associates right to left.

y = x = 3;y = x = 3;

y gets the value 3, because (x = 3) evaluates to the value 3.y gets the value 3, because (x = 3) evaluates to the value 3.

Page 30: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

30

Arithmetic OperatorsArithmetic Operators

SymbolSymbol OperationOperation UsageUsage PrecedencePrecedence AssocAssoc

** multiplymultiply x * yx * y 66 l-to-rl-to-r

// dividedivide x / yx / y 66 l-to-rl-to-r

%% modulomodulo x % yx % y 66 l-to-rl-to-r

++ additionaddition x + yx + y 77 l-to-rl-to-r

-- subtractionsubtraction x - yx - y 77 l-to-rl-to-r

All associate left to right.All associate left to right.

* / %* / % have higher precedence than have higher precedence than + -+ -..

Page 31: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

31

Arithmetic ExpressionsArithmetic Expressions

If mixed types, smaller type is "promoted" to larger.If mixed types, smaller type is "promoted" to larger.

x + 4.3x + 4.3if x is int, converted to double and result is doubleif x is int, converted to double and result is double

Integer division -- fraction is dropped.Integer division -- fraction is dropped.

x / 3x / 3if x is int and x=5, result is 1 (not 1.666666...)if x is int and x=5, result is 1 (not 1.666666...)

Modulo -- result is remainder.Modulo -- result is remainder.

x % 3x % 3

if x is int and x=5, result is 2.if x is int and x=5, result is 2.

Page 32: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

32

Bitwise OperatorsBitwise Operators

SymbolSymbol OperationOperation UsageUsage PrecedencePrecedence AssocAssoc

~~ bitwise NOTbitwise NOT ~x~x 44 r-to-lr-to-l

<<<< left shiftleft shift x << yx << y 88 l-to-rl-to-r

>>>> right shiftright shift x >> yx >> y 88 l-to-rl-to-r

&& bitwise ANDbitwise AND x & yx & y 1111 l-to-rl-to-r

^̂ bitwise XORbitwise XOR x ^ yx ^ y 1212 l-to-rl-to-r

|| bitwise ORbitwise OR x | yx | y 1313 l-to-rl-to-r

• Operate on variables bit-by-bit.Operate on variables bit-by-bit.

– Like LC-3 AND and NOT instructions.• Shift operations are logical (not arithmetic).Shift operations are logical (not arithmetic).

• Operate on Operate on valuesvalues -- neither operand is changed. -- neither operand is changed.

Page 33: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

33

Logical OperatorsLogical Operators

SymbolSymbol OperationOperation UsageUsage PrecedencePrecedence AssocAssoc

!! logical NOTlogical NOT !x!x 44 r-to-lr-to-l

&&&& logical ANDlogical AND x && yx && y 1414 l-to-rl-to-r

|||| logical ORlogical OR x || yx || y 1515 l-to-rl-to-r

•Treats entire variable (or value) as TRUE (non-zero) or FALSE (zero).Treats entire variable (or value) as TRUE (non-zero) or FALSE (zero).

•Result is 1 (TRUE) or 0 (FALSE).Result is 1 (TRUE) or 0 (FALSE).

Page 34: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

34

Relational OperatorsRelational OperatorsSymbolSymbol OperationOperation UsageUsage PrecedencePrecedence AssocAssoc

>> greater thangreater than x > yx > y 99 l-to-rl-to-r

>=>= greater than or equalgreater than or equal x >= yx >= y 99 l-to-rl-to-r

<< less thanless than x < yx < y 99 l-to-rl-to-r

<=<= less than or equalless than or equal x <= yx <= y 99 l-to-rl-to-r

==== equalequal x == yx == y 1010 l-to-rl-to-r

!=!= not equalnot equal x != yx != y 1010 l-to-rl-to-r

• Result is 1 (TRUE) or 0 (FALSE).Result is 1 (TRUE) or 0 (FALSE).

• Note: Don't confuse equality (==) with assignment (=).Note: Don't confuse equality (==) with assignment (=).

Page 35: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

35

Special Operators: ++ and Special Operators: ++ and ----

Changes value of variable before (or after) its value is used in Changes value of variable before (or after) its value is used in an expression.an expression.

SymbolSymbol OperationOperation UsageUsage PrecedencePrecedence AssocAssoc

++++ postincrementpostincrement x++x++ 22 r-to-lr-to-l

---- postdecrementpostdecrement x--x-- 22 r-to-lr-to-l

++++ preincrementpreincrement ++x++x 33 r-to-lr-to-l

<=<= predecrementpredecrement --x--x 33 r-to-lr-to-l

•PrePre: Increment/decrement variable : Increment/decrement variable beforebefore using its value. using its value.

•PostPost: Increment/decrement variable : Increment/decrement variable afterafter using its value. using its value.

Page 36: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

36

Using ++ and --Using ++ and --x = 4;x = 4;

y = x++;y = x++;

Results: Results: x = 5, y = 4x = 5, y = 4 (because x is incremented after assignment)(because x is incremented after assignment)

x = 4;x = 4;

y = ++x;y = ++x;

Results: Results: x = 5, y = 5x = 5, y = 5(because x is incremented before assignment)(because x is incremented before assignment)

Page 37: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

37

Practice with PrecedencePractice with PrecedenceAssume a=1, b=2, c=3, d=4.Assume a=1, b=2, c=3, d=4.

x = a * b + c * d / 2; /* x = 8 */x = a * b + c * d / 2; /* x = 8 */

same as:same as:

x = (a * b) + ((c * d) / 2);x = (a * b) + ((c * d) / 2);

•For long or confusing expressions, For long or confusing expressions, use parenthesesuse parentheses, because , because reader might not have memorized precedence table.reader might not have memorized precedence table.

•Note: Assignment operator has lowest precedence, so all the Note: Assignment operator has lowest precedence, so all the arithmetic operations on the right-hand side are evaluated first.arithmetic operations on the right-hand side are evaluated first.

Page 38: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

38

Symbol TableSymbol Table

Like assembler, compiler needs to know Like assembler, compiler needs to know information associated with identifiersinformation associated with identifiers

– in assembler, all identifiers were labels and information is address

Compiler keeps more informationCompiler keeps more information

Name (identifier)Name (identifier)

TypeType

Location in memoryLocation in memory

ScopeScope

Name Type Offset Scope

amounthoursminutesratesecondstime

intintintintintint

0-3-4-1-5-2

mainmainmainmainmainmain

Page 39: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

39

Local Variable StorageLocal Variable Storage

Local variables are stored in an Local variables are stored in an activation activation recordrecord, also known as a , also known as a stack framestack frame..

Symbol table “offset” gives the distance from Symbol table “offset” gives the distance from the base of the frame.the base of the frame.

– R5 is the frame pointer – holds address of the base of the current frame.

– A new frame is pushed on the run-time stack each time a block is entered.

– Because stack grows downward, base is the highest address of the frame, and variable offsets are <= 0.

seconds

minutes

hourstimerate

amount

R5

Page 40: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

40

Allocating Space for Allocating Space for VariablesVariables

Global data sectionGlobal data section

– All global variables stored here(actually all static variables)

– R4 points to beginning

Run-time stackRun-time stack

– Used for local variables– R6 points to top of stack– R5 points to top frame on stack– New frame for each block

(goes away when block exited)

Offset = distance from beginningOffset = distance from beginningof storage areaof storage area

– Global: LDR R1, R4, #4– Local: LDR R2, R5, #-3

instructions

global data

run-timestack

0x0000

0xFFFF

PC

R4

R6R5

Page 41: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

41

Variables and Memory Variables and Memory LocationsLocations

In our examples, a variable is always stored in In our examples, a variable is always stored in memory.memory.

When assigning to a variable, must When assigning to a variable, must storestore to memory to memory location.location.

A real compiler would perform code optimizationsA real compiler would perform code optimizationsthat try to keep variables allocated in registers.that try to keep variables allocated in registers.

Why?Why?

Page 42: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

42

Example: Compiling to LC-Example: Compiling to LC-33

#include <stdio.h>#include <stdio.h>

int inGlobal;int inGlobal;

main()main()

{{

int inLocal; /* local to main */int inLocal; /* local to main */

int outLocalA;int outLocalA;

int outLocalB;int outLocalB;

/* initialize *//* initialize */

inLocal = 5;inLocal = 5;

inGlobal = 3;inGlobal = 3;

/* perform calculations *//* perform calculations */

outLocalA = inLocal++ & ~inGlobal;outLocalA = inLocal++ & ~inGlobal;

outLocalB = (inLocal + inGlobal) - (inLocal - inGlobal);outLocalB = (inLocal + inGlobal) - (inLocal - inGlobal);

/* print results *//* print results */

printf("The results are: outLocalA = %d, outLocalB = %d\n",printf("The results are: outLocalA = %d, outLocalB = %d\n",

outLocalA, outLocalB);outLocalA, outLocalB);

}}

Page 43: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

43

Example: Symbol TableExample: Symbol Table

NameName TypeType OffsetOffset ScopeScopeinGlobalinGlobal intint 00 globalglobal

inLocalinLocal intint 00 mainmain

outLocalAoutLocalA intint -1-1 mainmain

outLocalBoutLocalB intint -2-2 mainmain

Page 44: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

44

Example: Code GenerationExample: Code Generation

; main; main

; initialize variables; initialize variables

AND R0, R0, #0AND R0, R0, #0 ADD R0, R0, #5 ADD R0, R0, #5 ; inLocal = 5; inLocal = 5 STR R0, R5, #0 STR R0, R5, #0 ; (offset = 0); (offset = 0)

AND R0, R0, #0 AND R0, R0, #0 ADD R0, R0, #3 ADD R0, R0, #3 ; inGlobal = 3; inGlobal = 3 STR R0, R4, #0 STR R0, R4, #0 ; (offset = 0); (offset = 0)

Page 45: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

45

Example (continued)Example (continued)

; first statement:; first statement:

; outLocalA = inLocal++ & ~inGlobal;; outLocalA = inLocal++ & ~inGlobal;

LDR R0, R5, #0 LDR R0, R5, #0 ; get inLocal; get inLocal ADD R1, R0, #1 ADD R1, R0, #1 ; increment; increment STR R1, R5, #0 STR R1, R5, #0 ; store; store

LDR R1, R4, #0 LDR R1, R4, #0 ; get inGlobal; get inGlobal NOT R1, R1 NOT R1, R1 ; ~inGlobal; ~inGlobal AND R2, R0, R1 AND R2, R0, R1 ; inLocal & ~inGlobal; inLocal & ~inGlobal STR R2, R5, #-1 STR R2, R5, #-1 ; store in outLocalA; store in outLocalA ; (offset = -1); (offset = -1)

Page 46: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

46

Example (continued)Example (continued); next statement:; next statement:

; outLocalB = (inLocal + inGlobal); outLocalB = (inLocal + inGlobal); - (inLocal - inGlobal);; - (inLocal - inGlobal);

LDR R0, R5, #0 LDR R0, R5, #0 ; inLocal; inLocal LDR R1, R4, #0 LDR R1, R4, #0 ; inGlobal; inGlobal ADD R0, R0, R1 ADD R0, R0, R1 ; R0 is sum; R0 is sum LDR R2, R5, #0 LDR R2, R5, #0 ; inLocal; inLocal LDR R3, R5, #0 LDR R3, R5, #0 ; inGlobal; inGlobal NOT R3, R3 NOT R3, R3 ADD R3, R3, #1 ADD R3, R3, #1 ADD R2, R2, R3 ADD R2, R2, R3 ; R2 is difference; R2 is difference NOT R2, R2 NOT R2, R2 ; negate; negate ADD R2, R2, #1 ADD R2, R2, #1 ADD R0, R0, R2 ADD R0, R0, R2 ; R0 = R0 - R2; R0 = R0 - R2 STR R0, R5, #-2 STR R0, R5, #-2 ; outLocalB (offset = -2); outLocalB (offset = -2)

Page 47: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

47

Special Operators: +=, *=, Special Operators: +=, *=, etc.etc.

Arithmetic and bitwise operators can be combined with assignment Arithmetic and bitwise operators can be combined with assignment operator.operator.

StatementStatement Equivalent assignmentEquivalent assignment

x += y;x += y; x = x + y;x = x + y;

x -= y;x -= y; x = x - y;x = x - y;

x *= y;x *= y; x = x * y;x = x * y;

x /= y;x /= y; x = x / y;x = x / y;

x %= y;x %= y; x = x % y;x = x % y;

x &= y;x &= y; x = x & y;x = x & y;

x |= y;x |= y; x = x | y;x = x | y;

x ^= y;x ^= y; x = x ^ y;x = x ^ y;

x <<= y;x <<= y; x = x << y;x = x << y;

x >>= y;x >>= y; x = x >> y;x = x >> y;

All have sameprecedence and

associativity as =and associateright-to-left.

Page 48: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

48

Special Operator: ConditionalSpecial Operator: Conditional

SymbolSymbol OperationOperation UsageUsage PrecedencePrecedence AssocAssoc

?:?: conditionalconditional x?y:zx?y:z 1616 l-to-rl-to-r

•If x is TRUE (non-zero), result is y; else, result is z.If x is TRUE (non-zero), result is y; else, result is z.

•Like a MUX, with x as the select signal.Like a MUX, with x as the select signal.

x

y z

1 0

Page 49: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

49

Questions?Questions?

Page 50: 1 Introduction to “C” HLL’s and the Basic Syntax Patt and Patel Ch. 11 & 12

50