Você está na página 1de 73

C Compiler Training that Sticks

8051

Agenda
C

Language Review Examples Programs

What is C?

High-level programming language One of the most popular general purpose programming languages available First developed in 1972 by Dennis Ritchie at AT&T Bell Labs Advantages of C Readability Maintainability Portability

A Word of Caution

C IS CASE SENSITIVE Var VAR Use for, not FOR etc.

A Simple C Program
/*This is my 1st C program Port 1 will be loaded with 0xAA and Port 3 with 0xF6. Everything between the star and forward slash is ignored by compiler*/ #include <stdio.h> void main(void){ P1 = 0xAA; P3 = 0xF6; while(1){ asm{NOP;} used }

//Assembler instruction

Dissecting a C Program

The first line is a comment A comment starts with a /* and ends with a */ Everything in between is ignored Comments can cross more than one line Document code, enhance readability Comments affect only size of text file Shortform notation for commenting out a single line: two slashes, // Comments cannot be nested

Dissecting a C Program
/* Comments do not increase the size of the executable, nor does it affect performance */ /* Comments do not increase the */ /* size of the executable, nor */ /* does it affect performance */ // Comments do not increase the // size of the executable, nor // does it affect performance

Dissecting a C Program

#include <stdio.h> Line 2 is a preprocessor directive Tells the compiler to look for a file and place the contents of that file at the directive stio.h is a header file Contains prototypes and macros for functions and registers

Dissecting a C Program

Angle brackets <stdio.h> tell the preprocessor to look in another directory for the file

Double quotes stdio.h tell the preprocessor to look in the current directory for the file

Dissecting a C Program

Every C program must have one, and only one, main( ) function Can be anywhere in your source code Program execution starts with main( ) Programs always end with main( ) The body of the function main( ) is located between the curly braces { and the }

The Basics of the C Program

A C program is composed of basic elements such as: keywords constants variables expressions statements and statement blocks

ANSI C Keywords
auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsinged void volatile while

Expressions

An expression is a combination of constants, variables and operators Examples


(2 + 3) * 10 80/4 i return 0 10 * (4 + 5) 6 6 + i

Precedence of Operators

All expressions are evaluated according to the precedence of its operators What do the following expressions reduce to?
2 + 3 * 10 (2 + 3) * 10

Precedence of Operators

All expressions are evaluated according to the precedence of its operators What do the following expressions reduce to?
2 + 3 * 10 (2 + 3) * 10 = 2+(3*10) = 32 =5*10 =50 * has higher precedence than + () has higher precedence than *

Operator Precedence Table


( ) [ ] . -> - ~ ! * & ++ -- sizeof * / % + << >> < > <= >= == != & l to r r to l r to l l to r l to r l to r l to r l to r l to r ^ | && || ?: = *= /= %= += -= <<= >>= &= ^= |= l to r l to r l to r l to r r to l r to l r to l r to l r to l

Statements

A statement is a complete instruction, ending with a semicolon A statement is made up of one or more expressions
i = 1; j = 6 % 4; return 0; Var1 = (2 + 3) * 10; BinValue = i + j;

Statement Blocks

A group of statements is a statement block beginning with a curly brace ({) and ending with a curly brace (}) A statement block is treated like a single statement by the compiler
for() { s3 = s1 + s2; MulValue = s3 * c; }

Data Types

Defines the size and type of data that a variable holds Only five data types in ANSI C

void char -> int -> long -> float -> double

8 Bits 16 Bits 32 Bits 32 Bits

->1 ->2 ->4 ->4

Byte Bytes Bytes Bytes

void Data Type


Represents no data type Used most commonly with functions


void CombineValues(void){ //Changes global values }

char Data Type

Represents a single character or an 8-bit number, i.e., A or 7 To define a variable as a char use:
char variablename;

To define multiple variables use:


char variablename1; char variablename2;

Another way of defining:


char variablename3, variablename4;

Character Constants

Single characters can be represented using single quotes, such as: A The ASCII value of the character is the value used in the expression x = A; //0x41

int Data Type

Integer numbers are whole numbers Result of integer division is truncation The length of an integer varies from one machine to another, typically 16-bits To define a variable as an int use: int variablename;

float Data Type

Floating point numbers contain both real and fractional parts Has at least 6 digits of precision To define a variable as float use: float variablename; Supported as 32-bit value in MCS51

Data Type Modifiers

These four data type modifiers can be applied to data types char and int signed unsigned short long

Sign Bit

The difference between a signed number and an unsigned number is the interpretation of the MSb For signed numbers, the MSb indicates a positive number when 0 and a negative number when 1 For unsigned numbers all bits are used to determine the value The default value of data types is unsigned

Sign Bit

The range of unsigned char is 0 to 255 {0, 1, , 255} The range of signed char is -128 to +127 {0x80, 0x81, , 0xFE,0xFF,0x00,,0x7F}

Changing Data Sizes


long and short are used to increase or decrease the size used by the data type short int x; reduces a 16-bit integer to 8bits

may be used without int: short x;

long int x; doubles a 16-bit integer to 32bits

may be used without int: long x;

Anatomy of a C Function
Function Type Function Name Argument List to Function

char add (char x, char y){ char result; result = x + y; return (result); }

Start of Function Body of Function End of Function Body and Function

Function Type

The function type is used to signify what type of value the function returns Can be any valid C data type void functions do not return a value The function add( ) returns a char

Function Names

A function name should be chosen to reflect what the function does Function names cannot start with numbers Function names cannot contain asterisk, arithmetic signs, or dot (.) Functions cannot contain minus signs or apostrophes

Function Arguments

Arguments are used to pass information TO a function Multiple arguments are separated by commas A function that does not receive any arguments is considered to be void int status(void){ // This function will return data of type int }

Function Body

The open curly brace ({) signifies the start of the

function body

The closed curly brace (}) denotes the end of the

function body

The statements in between are the statement block The function completes when the statement block is finished executing

Global Variables

Defined outside functions Variable can be used by ALL functions


// Globally defined register

unsigned char FlagReg;

void TestFlags(void){ FlagReg = FlagReg & 0x86; }// end of function void main(void){ FlagReg = FlagReg + 5; TestFlags(); }

//Call function

Local Variables

Defined inside a functions e.g. Temp Variable can be used ONLY by that function
// Globally defined register

unsigned char Online;

void ChangeVal(void){ unsigned char Temp; // Local variable Temp = P1 + 0x21; Online = Temp & 0x0F; }// end of function void main(void){ ChangeVal(); }

//Call function

Making Function Calls


#include <stdio.h>

char add( char x, char y){ char result; result = x + y; return (result); }
void main(void){ char sum; sum = add(5,12); P1 = sum; }

/* This function adds two chars */ //define a LOCAL result variable /* add parameters */ /* return result to caller */

/* defines a local variable */ // calculate sum of 5 and 12 // place result on Port 1

Quiz

What is wrong with this function?


int int_add(int x, int y){ char sum; sum = x + y; return (sum); }

Quiz

Answer Types different, answer limited to char! Change to same type


int int_add(int x, int y){ int sum; sum = x + y; return (sum); }

Quiz

What is wrong with this function?


int AddUp(char x, int y){ int sum; sum = x + y; return (sum); }

Quiz

Answer Types different ! Change to same type


int int_add(char x, int y){ int sum; sum = (int)x + y; //change x to an integer return (sum); }

for Loop

General form: for(expr1;expr2;expr3){ statement1; statement2; . . . } Example

for Loop
expr1
?-expr2
T F

statement1

statement2
... expr3

while Loop

General form: while(expr1){ statement1; statement2; . . . }

while Loop
?-expr1
T
F

statement1 statement2 ...

do-while Loop

General form: do{ statement1; statement2; . . . } while(expr1);

do-while Loop
statement1 statement2 ... expr1
T F

break Statement

break is used to jump out of a loop General form: break;


i=0; do{ if (i==10){ break; } i++; }while(1);

break Statement

break is used to jump out of a loop General form: break;


i=0; do{ if (i==10){ break; } i++; }while(1);

continue Statement

continue allows you to stay in loop but skip over statements within loop General form: continue;
for (i=1;i<6;i++){ if (i==3){ continue; } sum += i; }

continue Statement

continue allows you to stay in loop but skip over statements within loop General form: continue;
for (i=1;i<6;i++){ if (i==3){ continue; } sum += i; }

if Statement

Executes a statement block based on a condition General form:


if (expr){ statement1; statement2; . . . } else{ statement3; statement4; }

Optional

if Statement

Executes a statement block based on a condition General form: NB!! Not Value = 0x34
if (Value == 0x34){ statement1; statement2; . . . }

True False

else{ statement3; statement4; }

Optional

switch Statement

Replaces a group of if-else-if statements


switch(expr) { case expr1: statement1; break; case expr2: statement2; Optional break; . . . default: default-statement; //if no case break; }

Arrays

An array is a collection of values with the same data type Each value in the array is an element All elements are referenced by the name of the array with an offset Elements are stored in consecutive memory locations

Arrays

General form: data-type Array-name[array_size];

data-type indicates what data type the elements in the array will be Array-name is the name of the array Array_size defines how many elements are in the array E.g. char Keyboard[16];

Array name is Keyboard All data in Array is of type char Array has 16 locations (0 to 15)

Arrays

Arrays are accessed using an index Index starts at 0 and ends at arraysize - 1 The elements of the array are:
day[0], day[1], day[2], day[3], day[4], day[5], day[6] Data[0], Data[1], Data[2], Data[3], Data[4], Data[5], Data[6]

Elements may be initialized individually


day[0]=S; Data[1]= 56;

Or all together
char day[7]={S,M,T,W,T,F,S}; char Data[6]= {3,5,4,1,0,2};

Arrays

Accessing arrays using an index variable Array with name of List and 10 elements ints
int List[10], i; for(i=0;i<10;i++) { List[i] = i; }

Arrays and Strings

An array of characters is a string Strings must be terminated by a null character \0 Null characters have a value of 0
char Greet[7]={H,e,l,l,o,\0}; char Greet[7]={H,e,l,l,o,0};

Strings may be initialized individually

as shown above

Or all together
char Greet[]=Hello;

Compiler fill positions

Strings

What is the difference between the two statements? char ch = x; char str[ ] = x;

ch is a character constant str is a string constant str includes a null character

Pointers

Used for indirect access to program elements

single variables, arrays, structures, functions, etc.

Declared using splat notation: data-type *name;

where data-type is the data type of data the pointer is pointing to and name is the pointer name

Pointer functionality is similar to the @ use in assembler Pointers may be operated on just like any other variable

compiler automatically adjusts pointer registers to data size similar to array and index combination

Pointer Initialization

Pointers contain addresses


pointers must always be manually initialized & notation used to initialize pointers to single variables array name may be used to initialize array pointers
int Var; //declare a variable
int *VPtr; //declare pointer to int variable

char Array1[] = Hello; //declare and init an array char *APtr; //declare pointer to array

VPtr = &Var; APtr = Array1; Aptr = &Array1[0];

//initialize variable pointer //initialize array pointer //does same as previous line

OR char *APtr = Array1;

Pointer Operations

Use splat to get at the data pointed to by the pointer


interpret as the contents of called de-referencing the pointer

Suppose we have: char *Ptr1;

sets the pointer to point to address 0x20 sets the contents of address 0x20 to 0x34 Ptr1 += 5; adds 5 to the pointer to point to address 0x25 *Ptr1=0x67; 0x67 loaded into 0x25 *Ptr1 = *Ptrl + 2; adds 2 to the contents of address (*Ptr1 += 2) 0x25. Will become 0x67 +2 = 0x69 Ptr1=0x20; *Ptr1=0x34;

Pointer Operations

Pointer arithmetic

may increment or decrement pointers may add values to or subtract values from pointers pointer will always be modified by the number of bytes in the data type it is pointing to:
int *IntPtr; char *ChPtr; IntPtr++; bytes ChPtr++; byte

//pointer incremented by 2

//pointer incremented by 1

Pointers vs Arrays

Pointers are a more efficient way to pass data to functions

Arrays are always passed by reference (i.e. using the base address of the array) Array names may be used interchangeably with pointer names

array names used without indices are interpreted as the base address of the array

Pointers vs Arrays

Code example:
void Add(char *Ptr1, char Length) { while(Length != 0x00) //check if all elements complete { *Ptr1 += 0x03; //add 3 to array element Length--; //decrement loop count Ptr1++; //move to next element } } void main(void) { char Array[] = {0,1,2,3,4}; //define and initialize array char *APtr = Array; //define and init pointer to array Add(Array,5); Add(APtr,5); Add(&Array[0],5); } //call function using array variable //call function using pointer //call function using array element

Structures

Structures provide a method of grouping data

may contain data of different types, including pointers and arrays


members may be of different types may have multiple variables defined

Structure declaration

struct struct-name { type member1; type member2; . . . } variable-name;

Structure Tag

Member variables Variable

Declaring Structures

1 - First declare the template, then the variable name


struct Data { int Cntrl; int Speed; char Fault; };
Structure Tag

Member variables
No Variable

struct Data Motor1; void main (void){


Motor1.Cntrl = 0x7854; Motor1.Speed = 0xF38C; Motor1.Fault = 0x56; ------;

Declaring Structures

2 - Declare the template + The variable name


struct Data { int Cntrl; int Speed; char Fault; } Motor1, Motor2;
Structure Tag

Member variables
Variable Names

void main (void){


Motor1.Cntrl = 0x7854; Motor1.Speed = 0xF38C; Motor1.Fault = 0x56; Motor2.Speed = 0xF4CC; ------;

Accessing Structures

struct MyStruct { char Ch[20]; int Length; } StrData;

Structure members are accessed using dot notation variable-name.memberx Member may be used as a variable of the type of memberx
//character string variable //string length variable

StrData.Ch[0]=H; StrData.Ch[1]=i; StrData.Ch[2]=\0; StrData.Length=3;

//initialize //initialize //initialize //initialize

element 0 of string element 1 of string element 2 of string string length

Casting Variables

Allows variables of one type to be converted to a variable of another type

square peg in a round hole

precede variable to be cast with the desired data type enclosed in parens

What happens in this situation?


unsigned int x; unsigned char y; y=0x32; x=y; //define 16-bit integer //define 8-bit character //initialize y //set x equal to y

upper byte of x is unknown Different types!!!!

Casting Variables

Previous situation can be avoided by casting


unsigned int x; unsigned char y; y=0x32; x=(unsigned int)y; //define 16-bit integer //define 8-bit character //initialize y //set x equal to y

y is now treated like an integer during assignment upper byte of Y set to 0

Casting Variables

Situations in which to cast

copying smaller data type to a larger one


char -> int int -> long float -> double

assigning a pointer to a constant when in doubt...

ASK !!!!!!

Você também pode gostar