Moät soá kieán thöùc cô sôû veà laäp trình baèng ngoân ngöõ C

Phaâàn tröôùc | Muïc luïc | Phaâàn sau

XVI. Moät soá kieåu döõ lieäu vaø haøm thoâng duïng

Noäi dung:

 

Kieåu döõ lieäu enum

Kieåu döõ lieäu khai baùo caùc haèng integers coù ñònh danh.

enum tag_name {enumeration_list} variable_list;

tag_name vaø variable_list laø khoâng baét buoäc.

Ví duï:

enum automobile {sedan, pick_up, sport_utility};

Trong ñònh nghóa treân, sedan =0, pick_up=1, sport_utility=2. vaø ta coù theå khai baùo bieán

enum automobile  domestic, foreign;
 

Coù theå ñònh nghóa chung nhö sau:

enum automobile {sedan, pick_up, sport_utility} domestic, foreign;

Thay vì caùc giaù trò nguyeân maëc ñònh, ta coù theå ñònh nghóa caùc giaù trò khaùc baèng caùch sau:

enum automobile {sedan = 60, pick_up = 30, sport_utility = 10};

Ví duï:

1:  /* Defining enum data types */
2:  #include <stdio.h>
3:  /* main() function */
4:  main()
5:  {
6:     enum language {human=100,
7:                    animal=50,
8:                    computer};
9:     enum days{SUN,
10:              MON,
11:              TUE,
12:              WED,
13:              THU,
14:              FRI,
15:              SAT};
16:
17:    printf("human: %d,  animal: %d,  computer: %d\n",
18:       human, animal, computer);
19:    printf("SUN: %d\n", SUN);
20:    printf("MON: %d\n", MON);
21:    printf("TUE: %d\n", TUE);
22:    printf("WED: %d\n", WED);
23:    printf("THU: %d\n", THU);
24:    printf("FRI: %d\n", FRI);
25:    printf("SAT: %d\n", SAT);
26:
27:    return 0;
28: }
 
Keát quaû:
 
human: 100,  animal: 50,  computer: 51
SUN: 0
MON: 1
TUE: 2
WED: 3
THU: 4
FRI: 5
SAT: 6

Ví duï söû duïng enum:

1:  /* Using the enum data type */
2:  #include <stdio.h>
3:  /* main() function */
4:  main()
5:  {
6:     enum units{penny = 1,
7:                nickel = 5,
8:                dime = 10,
9:                quarter = 25,
10:               dollar = 100};
11:    int money_units[5] = {
12:               dollar,
13:               quarter,
14:               dime,
15:               nickel,
16:               penny};
17:    char *unit_name[5] = {
18:              "dollar(s)",
19:              "quarter(s)",
20:              "dime(s)",
21:              "nickel(s)",
22:              "penny(s)"};
23:    int cent, tmp, i;
24:
25:    printf("Enter a monetary value in cents:\n");
26:    scanf("%d", &cent);  /* get input from the user */
27:    printf("Which is equivalent to:\n");
28:    tmp = 0;
29:    for (i=0; i<5; i++){
30:       tmp = cent / money_units[i];
31:       cent -= tmp * money_units[i];
32:       if (tmp)
33:         printf("%d %s ", tmp, unit_name[i]);
34:    }
35:    printf("\n");
36:    return 0;
37: }
 
Keát quaû:
 
Enter a monetary value in cents:
141
Which is equivalent to:
1 dollar(s) 1 quarter(s) 1 dime(s) 1 nickel(s) 1 penny(s)

Leänh ñònh kieåu typedef

Trong C, ta coù theå duøng leänh typedef ñeå ñònh kieåu döõ lieäu tuøy yù khaùc vôùi caùc kieåu maëc ñònh.

Ví duï:

typedef  int  TWO_BYTE;

vôùi ñònh nghóa treân, ta coù theå khai baùo

TWO_BYTE i, j;

Ví duï:

1:  /* Using typedef definitions */
2:  #include <stdio.h>
3:  #include <stdlib.h>
4:  #include <string.h>
5:
 
6:  enum constants{ITEM_NUM = 3,
7:                 DELT='a'-'A'};
8:  typedef char *STRING[ITEM_NUM];
9:  typedef char *PTR_STR;
10: typedef char BIT8;
11: typedef int BIT16;
12:
13: void Convert2Upper(PTR_STR str1, PTR_STR str2);
14:
15: main()
16: {
17:    STRING str;
18:    STRING moon = {"Whatever we wear",
19:                   "we become beautiful",
20:                   "moon viewing!"};
21:    BIT16 i;
22:    BIT16 term = 0;
23:
24:    for (i=0; i<ITEM_NUM; i++){
25:      str[i] = malloc((strlen(moon[i])+1) * sizeof(BIT8));
26:      if (str[i] == NULL){
27:        printf("malloc() failed.\n");
28:        term = 1;
29:        i = ITEM_NUM;  /* break the for loop */
30:      }
31:      Convert2Upper(moon[i], str[i]);
32:      printf("%s\n", moon[i]);
33:    }
34:    for (i=0; i<ITEM_NUM; i++){
35:      printf("\n%s", str[i]);
36:      free (str[i]);
37:    }
38:
39:    return term;
40: }
41: /* function definition */
42: void Convert2Upper(PTR_STR str1, PTR_STR str2)
43: {
44:    BIT16 i;
45:
46:    for (i=0; str1[i]; i++){
47:      if ((str1[i] >= `a') &&
48:          (str1[i] <= `z'))
49:        str2[i] = str1[i] - DELT;
50:      else
51:        str2[i] = str1[i];
52:    }
53:    str2[i] = `\0';  /* add null character */
54: }
 
Keát quaû:
 
Whatever we wear
we become beautiful
moon viewing!
 
WHATEVER WE WEAR
WE BECOME BEAUTIFUL
MOON VIEWING!

Haøm ñeä quy

Trong C cho pheùp moät haøm coù theå goïi leân chính baûn thaân cuûa noù, haøm ñoù goïi laø haøm ñeä quy.

Sau ñaây laø ví duï haøm ñeä quy coäng soá nguyeân töø 1 ñeán 100.

Ví duï:

1:  /* Calling a recursive function */
2:  #include <stdio.h>
3:
4:  enum con{MIN_NUM = 0,
5:           MAX_NUM = 100};
6:
7:  int fRecur(int n);
8:
9:  main()
10: {
11:    int i, sum1, sum2;
12:
13:    sum1 = sum2 = 0;
14:    for (i=1; i<=MAX_NUM; i++)
15:      sum1 += i;
16:    printf("The value of sum1 is %d.\n", sum1);
17:    sum2 = fRecur(MAX_NUM);
18:    printf("The value returned by fRecur() is %d.\n", sum2);
19:
20:    return 0;
21: }
22: /* function definition */
23: int fRecur(int n)
24: {
25:    if (n == MIN_NUM)
26:      return 0;
27:    return  fRecur(n - 1) + n;
28: }
 
Keát quaû:
 
The value of sum1 is 5050.
The value returned by fRecur() is 5050.
 

Ghi chuù

Haøm ñeä quy coù thuaän lôïi laø cho thaáy thuaät toaùn roõ raøng, caùch vieát ñôn giaûn. Tuy nhieân thöôøng laø chaïy chaäm vì noù ñoøi hoûi nhieàu boä nhôù ñeå löu tröõ caùc bieán haøm trung gian (stacks).

Cho neân cuõng khoâng neân söû duïng nhieàu neáu khoâng caàn thieát.

Baøi taäp

  1. Caùc giaù trò haèng soá baèng bao nhieâu?
enum months { Jan, Feb, Mar, Apr,
              May, Jun, Jul, Aug,
              Sep, Oct, Nov, Dec };
  1. Caùc giaù trò haèng soá baèng bao nhieâu?
enum tag { name1,
           name2 = 10,
           name3,
           name4 };
  1. Vieát moät chöông trình coù tính ñeä quy.

Phaâàn tröôùc | Muïc luïc | Phaâàn sau