De presentatie wordt gedownload. Even geduld aub

De presentatie wordt gedownload. Even geduld aub

P. 1 Deel I: Programmeertaal C 7. Andere verschillen met Java Prof.Dr.Ir. Filip De Turck.

Verwante presentaties


Presentatie over: "P. 1 Deel I: Programmeertaal C 7. Andere verschillen met Java Prof.Dr.Ir. Filip De Turck."— Transcript van de presentatie:

1 p. 1 Deel I: Programmeertaal C 7. Andere verschillen met Java Prof.Dr.Ir. Filip De Turck

2 p. 2 Vakgroep Informatietechnologie Overzicht 1. const in plaats van final 2. Inline functies 3. Afwezigheid van excepties 4. Type aliasing 5. main() functie 6. Standaard bibliotheek 7. Bitvelden en -operatoren 8. Opsommingen 9. Abstracte datatypes

3 p. 3 Vakgroep Informatietechnologie 1. const in plaats van final Java assignatie meestal bij declaratie met final keyword vb.: public (static) final int CONSTANTE = 2; C (cfr. Deel 6.3) assignatie altijd bij declaratie met const keyword sizeof(constante) en &constante mogelijk vb.: (static) const int constante = 2; ander gebruik:  in array- en pointer-argumenten van functies  constante pointers: enkel initialisatieadres geldig => niet wijzigbaar! constante variabelen: 1 assignatie

4 p. 4 Vakgroep Informatietechnologie 2. Inline functies C inline functies: door inline keyword in functiedeclaratie compiler kopieert code van functie waar ze opgeroepen wordt vermijdt overhead oproeping functie via stack => snelheidswinst => meestal voor kleine, snel uit te voeren functies dikwijls in header file ipv declaratie vb.: inline int max (int a, int b) { if (a > b) return a; else return b; } Java kent dit niet: compiler beslist over optimalisaties

5 p. 5 Vakgroep Informatietechnologie 3. Afwezigheid van excepties Java klasse Exception:  abstraheert fouten en situaties die niet mogen voorkomen  voorgedefinieerde klassen voor systeem- en geheugentoegangsfouten  uitbreidbaar door overerving voor applicatiegedefinieerde fouten Excepties opvangbaar door applicatie door “exception handlers”  try{… //code possibly generating error }catch(Exception e){… //exception handler } C applicatiegedefinieerde fouten door definitie return waarde  vb.: int fseek(FILE *stream, long pos, int from)  zoekt een bepaalde positie in een bestand: als dit lukt return 0, anders return 1 systeem- en geheugenfouten: geen ondersteuning!  niet gealloceerd geheugen lezen/beschrijven (vb. buiten grenzen van array )  kan leiden tot corrupte data en rare output  moeilijk op te sporen: niet noodzakelijk compiler warning of vastlopend programma Opvangen van fouten?

6 p. 6 Vakgroep Informatietechnologie 4. Type aliasing Alias: andere naam typedef keyword laat toe alias te definiëren voor gelijk welk type  Zelfgedefinieerd typedef struct boek { char titel[N]; int aantal_blz; int prijs; } boek;  Systeemtype typedef unsigned char byte;// 1 byte typedef unsigned short word;// 2 bytes typedef unsigned long dword;// 4 bytes gebruikt als afkorting of verduidelijking bestaat niet in Java

7 p. 7 Vakgroep Informatietechnologie 5. Main functie Java public static void main(String[] args)){ //uit te voeren code } args is een array van String objecten elementen zijn opdrachtlijnargumenten C int main(int argc, char **argv){ //uit te voeren code } return type en parameters optioneel, kortste versie: void main() Indien aanwezig:  argv is een array van karakter strings  argc is de lengte van argv  argv[0] = naam van programma; argv[1] = argument1; … ;  argv[argc-1] =laatste argument  argv[argc] = NULL Uitvoerbaar programma

8 p. 8 Vakgroep Informatietechnologie 6. Standaard bibliotheek Java bibliotheken voor I/O, netwerkondersteuning, GUIs, etc. zeer uitgebreide API C bibliotheek van functies, types en macro’s = de C Standaard Bibliotheek (Eng.: Standard Library) beperkt om portabiliteit hoog te houden  vb. geen ondersteuning voor GUIs  bibliotheken voor GUIs meestal platformspecifiek

9 p. 9 Vakgroep Informatietechnologie 6. Standaard bibliotheek sample Some essential macros and additional type declarations Access to environment; dynamic memory allocation; miscellaneous utilities Streamed input and output of characters String handling Classification of characters (upper/lower case, alphabetic/numeric etc) Implementation-defined limits for integral types Implementation-defined limits for floating-point types Mathematical functions Diagnostic utilities

10 p. 10 Vakgroep Informatietechnologie 6. Standaard bibliotheek sample Error identification Regional/national variations in character sets, time formats, etc Support for functions with variable numbers of arguments Representations of time, and clock access Handling of exceptional run-time events Restoration of execution to a previous state C95 additionally provides the following headers: Alphabetic names for operators

11 p. 11 Vakgroep Informatietechnologie 7. Bitvelden en -operatoren 1. Bitvelden: concept 2. Bitvelden: definitie 3. Toepassing: device register 4. Bitoperatoren 5. Bitmasks

12 p. 12 Vakgroep Informatietechnologie 7.1 Bitvelden: concept C heeft ingebouwde methodes om de individuele bits in een byte te bewerken Beperkt geheugen: vb. 8 booleans in 1 byte Device registers: ieder bit heeft een betekenis Encryptie: routines moeten toegang hebben tot individuele bits of reeksen van bits Doel Toepassing typedef struct dag { unsigned maand:4; unsigned dag:5; unsigned jaar:12; } dag; sizeof(dag)  4 = veelvoud van woordbreedte 04812162031 maanddagjaar????

13 p. 13 Vakgroep Informatietechnologie 7.2 Bitvelden: definitie bit_veld ::= {int | unsigned} 1 {naam} opt : constante_gehele_uitdr Declaratie  bitvelden zonder teken: ondubbelzinnig  bitvelden met teken: representatie machine-afhankelijk (tekenbit of 2-complement?)  anonieme bitvelden: voor opvulling (padding)  anoniem bitveld met lengte 0: opvullen tot volgende woord Beperkingen  geen rijen van bitvelden  geen adresbepaling via &  geen directe dereferentie, wel -> toegelaten !

14 p. 14 Vakgroep Informatietechnologie 7.3 Bitvelden: device registers Boot Area 0x0000 0000 RAM ROM 0x0001 0000 0x000F 0000 0xF000 0000 Memory Mapped I/O 0xF001 0000 Serial Port Status Port 0xF001 0004 0xF001 0008 DataPort Timer 0 Timer 1 0xF001 000C Bits 7: Received Signal (RS) Bits 6: Telephone Ringing (TR) Bits 5: Data Set Ready (DSR) Bits 4: Clear to Send (CTS) Bits 3: Change in receiving Line (CHR) Bits 2: Trailing Edge Detected (TED) Bits 1: Change in Data Set Ready (CDSR) Bits 0: Change in Clear To Send (CCTS) 01234567 CTS RSTR CCTS

15 p. 15 Vakgroep Informatietechnologie 7.3 Opgave: dedicated system development  Ontwerp een datastructuur van het type struct en met bitvelden die het status register beschrijft.  Schrijf de code die ervoor zorgt dat deze datastructuur naar het correcte adres verwijst. ( 0xF001 0000 )  Op welke manier kan men deze code ontwikkelen en (beperkt) testen op een host systeem waar deze seriële hardware niet eens op bestaat?

16 p. 16 Vakgroep Informatietechnologie 7.3 Statusregister (1): datastructuur /* Device Register Bit level access*/ struct statusType { unsigned CCTS : 1; unsigned CDSR : 1; unsigned TED : 1; unsigned CHR : 1; unsigned CTS : 1; unsigned DSR : 1; unsigned TR : 1; unsigned RS : 1; } status; status = getportstatus; if ( status.cts) printf(“Clear To Send. \n”);

17 p. 17 Vakgroep Informatietechnologie 7.3 Statusregister (2): op adres 0xF001 0000 #include #define SIMULATION struct statusType {... } status;... #ifdef SIMULATION statusType * getPortStatus = NULL; getPortStatus = (statusType *) malloc(sizeof(statusType)); printf("SIMULATION> Serial Status Register 0x" ) ; bitPrint(getPortStatus); #else volatile statusType * const getPortStatus = (statusType * )0xF001000; printf("TARGET> Serial Status Register 0x" ) ; bitPrint(getPortStatus); #endif

18 p. 18 Vakgroep Informatietechnologie 7.4. Bitoperatoren Principe  elke variabele-inhoud kan ook als bitpatroon geïnterpreteerd worden  bitpatronen zijn (doorgaans) systeemafhankelijk Operatoren bitcomplement (unair)~(niet !) bitsgewijze EN&(niet &&) bitsgewijse OF|(niet ||) bitsgewijze XOF^ schuif links<< schuif rechts>> BITSGEWIJZE operatoren Schuif- operatoren

19 p. 19 Vakgroep Informatietechnologie 7.4 Bitsgewijze operatoren int main(void) { int a=12345; int b=67890; printf("\na=\t");print_patroon(a); printf("\nb=\t");print_patroon(b); printf("\n~a=\t");print_patroon(~a); printf("\na&b=\t");print_patroon(a&b); printf("\na|b=\t");print_patroon(a|b); printf("\na^b=\t");print_patroon(a^b); printf("\n"); return 0; } a=00000000 00000000 00110000 00111001 b=00000000 00000001 00001001 00110010 ~a=11111111 11111111 11001111 11000110 a&b=00000000 00000000 00000000 00110000 a|b=00000000 00000001 00111001 00111011 a^b=00000000 00000001 00111001 00001011

20 p. 20 Vakgroep Informatietechnologie 7.4. Bitoperatoren: schuifoperatoren uitdrukking << gehele_uitdrukking Schuif links  effect: schuift rechts van gehele_uitdrukking nullen in (= * 2 gehele_uitdrukking )  resultaattype: cf. gehele promotieregels!

21 p. 21 Vakgroep Informatietechnologie 7.4. Bitoperatoren: schuif links int main(void) { int a=3; int i; for(i=0;i<6;i++) { a<<=i; printf("\na= %d\t",a);print_patroon(a); } return 0; } a= 300000000 00000000 00000000 00000011 a= 600000000 00000000 00000000 00000110 a= 2400000000 00000000 00000000 00011000 a= 19200000000 00000000 00000000 11000000 a= 307200000000 00000000 00001100 00000000 a= 9830400000000 00000001 10000000 00000000 (a=3) a= -311111111 11111111 11111111 11111101 a= -611111111 11111111 11111111 11111010 a= -2411111111 11111111 11111111 11101000 a= -19211111111 11111111 11111111 01000000 a= -307211111111 11111111 11110100 00000000 a= -9830411111111 11111110 10000000 00000000 (a=-3)

22 p. 22 Vakgroep Informatietechnologie 7.4. Bitoperatoren: schuifoperatoren (2) uitdrukking >> gehele_uitdrukking Schuif rechts  effect: schuift rechts gehele_uitdrukking nullen/enen in (= / 2 gehele_uitdrukking )  resultaattype: cfr. gehele promotieregels!  Types zonder teken:  steeds 0-en inschuiven  Types met teken  ofwel: tekenbit inschuiven  ofwel: 0-en inschuiven (JAVA : >> operator schuift 0-en in)

23 p. 23 Vakgroep Informatietechnologie 7.4. Bitoperatoren: schuif rechts oefening #include int main(void) { int a=INT_MAX-3; int i; for(i=0;i<6;i++) { a>>=i; printf("\na= %d\t",a);print_patroon(a); } a= 214748364401111111 11111111 11111111 11111100 a= 107374182200111111 11111111 11111111 11111110 a= 26843545500001111 11111111 11111111 11111111 a= 3355443100000001 11111111 11111111 11111111 a= 209715100000000 00011111 11111111 11111111 a= 6553500000000 00000000 11111111 11111111 (a=INT_MAX-3) a= -214748364410000000 00000000 00000000 00000100 a= -107374182211000000 00000000 00000000 00000010 a= -26843545611110000 00000000 00000000 00000000 a= -3355443211111110 00000000 00000000 00000000 a= -209715211111111 11100000 00000000 00000000 a= -6553611111111 11111111 00000000 00000000 (a=-INT_MAX+3)

24 p. 24 Vakgroep Informatietechnologie 7.5 Masks: testen van bitpatroon in register #defineCCTS7 #defineCDSR6 #defineTED5 #defineCHR4 #defineCTS3 #defineDSR2 #defineTR 1 #defineRS 0 struct statusType { unsigned CCTS : 1; unsigned CDSR : 1; unsigned TED : 1; unsigned CHR : 1; unsigned CTS : 1; unsigned DSR : 1; unsigned TR : 1; unsigned RS : 1; } status; Statusregister : 0xF001 0000 7 6543210 CTS Mask 10000000 CTS RS TR CCTS & CTS0000000 RSTR CCTS

25 p. 25 Vakgroep Informatietechnologie 7.5 Masks (2) void main () { volatile char * getPortStatus; unsigned const char mask = 1; unsigned char tmpMask = 0; char bitpattern ; tmpMask = (mask << CTS); getPortStatus = (volatile char *) malloc(sizeof(char)); bitpattern = *getPortStatus; if (bitpattern & tmpMask) printf("MASK vsn> Clear To Send. \n"); } if ( status.cts) printf(“Clear To Send. \n”);

26 p. 26 Vakgroep Informatietechnologie 7.5 Masks: uitlezen van een register 76543210 Read Dataport : 0xF001 0004 01111000 >> 4 Read 00 00 Write Read & 76543210

27 p. 27 Vakgroep Informatietechnologie 7.5 Masks: uitlezen van een register (2) #define READ4 void main () { volatile char * getDataPort; unsigned const char readWriteMask = 0x0F ; unsigned char tmpMask = 0; unsigned char bitpattern, inputRegister; tmpMask = (readWriteMask << READ); getDataPort = (volatile char *)malloc(sizeof(char)); bitpattern = *getDataPort; bitpattern &= tmpMask; inputRegister = (bitpattern >> READ); printf("SIMULATION> Serial Status Register value %"); bitPrint(&inputRegister, sizeof(char)); }

28 p. 28 Vakgroep Informatietechnologie 8. Enum opsommingstypes: concept Gehele types met beperkt bereik zinvolle namen geven Voorbeeld Doel enum seizoen {lente, zomer, herfst, winter}; enum maand {januari, februari, maart, …};  wordt intern als geheel type gestockeerd  mag overal gebruikt worden waar geheel type toegelaten is  “syntactic sugar”, te gebruiken om code duidelijker te maken  sinds versie 5.0 ook aanwezig in Java

29 p. 29 Vakgroep Informatietechnologie 8. Opsommingstypes: syntax enum tag_naam{,naam{=constante_uitdr} opt } 1+ ; Voorbeeld definitie enum seizoen {lente, zomer, herfst, winter}; enum maand {januari, februari, maart, …}; typedef enum dag_{ma=1,di,wo,don,vr,za,zo=10} dag; int main(void) { dag i; for(i=ma;i<zo;i++) printf("i=%d\n",i); i=15; } afkorting via typedef mogelijk ! i=1 i=2 i=3 … i=9

30 p. 30 Vakgroep Informatietechnologie 8. Opsommingen: maanden Schrijf een functie maandString die gegeven een variabele van het type maand, een string teruggeeft met de tekstuele voorstelling van de maand in kwestie. Gebruik typedef om het type maand zelf te definiëren !

31 p. 31 Vakgroep Informatietechnologie 8. Maanden: oplossing #include enum maand { JAN= 0, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OKT, NOV, DEC }; typedef enum maand maandType; char * maandString(maandType); int main(){ maandType nieuweMaand; for (nieuweMaand = JAN; ; ){ if ((int)nieuweMaand > (int)DEC) break; printf("%s \n", maandString(nieuweMaand)); nieuweMaand = maandType ((int) nieuweMaand + 1); } return 0; } char * maandString(maandType dezeMaand){ static char *maandString [] = { "January","February","March", "April", "May","June","July","August", "September","October", "November", "December" }; return (maandString[dezeMaand]); }

32 p. 32 Vakgroep Informatietechnologie 9. Abstracte datatypes 1. Definitie 2. ADT’s en programma organisatie 3. Voorbeeld: de stapel

33 p. 33 Vakgroep Informatietechnologie 9.1 Definitie interface module  in afzonderlijke headerfile  via #include in andere modules te gebruiken module A ADT.c ADT.h interface implementatie  functieprototypes  macro’s  constanten  typedefs

34 p. 34 Vakgroep Informatietechnologie 9.1 Abstract Data Types in C Voorbeeld FILE :  Type van het ADT: FILE  Operaties: fopen(), fclose(), fprintf(),... typedef struct { int_cnt; unsigned char*_ptr; unsigned char*_base; int_bufsiz; short_flag; short_file; char*__newbase; void*_lock; unsigned char*_bufendp; } FILE;

35 p. 35 Vakgroep Informatietechnologie 9.1 ADT: (interface) definitie = inhoud en operaties van een type ZONDER de implementatie ADT.c ADT.h interface implementatie 1 ADT2.c implementatie 2 bevat beschrijving van ADT

36 p. 36 Vakgroep Informatietechnologie 9.2 ADT’s en programma organisatie  Een toepassing die gebruik maakt van een ADT bestaat minstens uit 3 bestanden:  een interface: de datatypes en de functies/operaties die toegelaten zijn op de ADT  een implementatie: van de functies en operaties  een toepassings- of client programma: die gebruikt enkel de functies van de ADT om abstracte operaties uit te voeren. ADT.o ADT.cADT.hClient.c interfaceimplementatietoepassing

37 p. 37 Vakgroep Informatietechnologie 9.2 Compiling & Linking Compiler Client.c ADT.h stdio.h Client.o Linker Client.exe libc.a ADT.o ADT.c Compiler

38 p. 38 Vakgroep Informatietechnologie 9.3 ADT voorbeeld: stapel of stack = LIFO-structuur 1 2 3 push(1) push(2) push(3) 3 pop inhoud: stapel van gehele getallen bewerkingen: push: element bijplaatsen op de stapel -> indien vol … ? pop: element afhalen van de stapel -> indien leeg …? 3

39 p. 39 Vakgroep Informatietechnologie 9.3 Stapel : gegevens & datatypes #defineSIZE25 typedef struct { intd[SIZE]; int tos; } stack; Gegevens van stack  opslag gehele getallen -> via int-array met vooropgegeven lengte  bijhouden “top of stack” -> via geheel getal int

40 p. 40 Vakgroep Informatietechnologie 9.3 Stapel: operaties push: element bijplaatsen op de stapel  geeft +1 indien gelukt  geeft 0 indien niet gelukt pop: element afhalen van de stapel  geeft +1 indien gelukt  geeft 0 indien niet gelukt  bovenste stapelelement als waarde 2de argument int push(stack*,int); int pop(stack*,int*);

41 p. 41 Vakgroep Informatietechnologie 9.3 De include file: stack.h #defineSIZE25 #define EMPTY-1 typedef struct { int d[SIZE]; int tos; } stack; int push(stack*,int); int pop(stack*,int*); implementatie- onafhankelijk

42 p. 42 Vakgroep Informatietechnologie 9.3 Implementatie: stack.c #include "stack.h" int push(stack* s,int i) { int r; if(r=!full(s)) { s->tos++; s->d[s->tos]=i; } return r; } int pop(stack* s,int* i) { int r; if(r=!empty(s)) { *i=s->d[s->tos]; s->tos--; } return r; }

43 p. 43 Vakgroep Informatietechnologie 9.3 Gebruik stapel: reverse.c #include #include "stack.h" int main(void) { int g; stack s; reset(&s); do { printf("Geef een positief getal :"); scanf("%d",&g); if(g>0) push(&s,g); } while(g>0); printf("Afbeelden van de getallen : "); while( pop(&s,&g) ) printf("%d\t",g); }

44 p. 44 Vakgroep Informatietechnologie 9.3 Voorbeelden van ADT’s  Bewerken van bestanden met libc  datatype: FILE  operaties: fopen, fclose, fprinf,...  Implementatie van een stapel : LIFO  datatype: Item  typedef int Item  typedef float Item  operaties:  pop, push,...

45 p. 45 Vakgroep Informatietechnologie 9. Samenvatting: Abstracte Datatypes  DataStructuur  De organisatie van gegevens: structuren, tabel,...  DataType  Een datastructuur waarvan we ook de typische operaties in rekening brengen: zoeken, bijvoegen, verwijderen,...  Abstract Data Type  Een datatype waar we een onderscheid maken tussen de definities van de data en de operaties en hun implementatie


Download ppt "P. 1 Deel I: Programmeertaal C 7. Andere verschillen met Java Prof.Dr.Ir. Filip De Turck."

Verwante presentaties


Ads door Google