CHAPTER 9
PROGRAM STRUCTURE

[IMAGE: An Quarter-Size Version of The Joy of C Front Cover]
Our previous programs have had a simple structure. This chapter deals with more complex program organizations. We finish up our description of variables local to particular functions and introduce variables accessible by any function. While discussing variables, we present the storage classes that control their lifetime, location, and visibility. We then show how header files simplify accessing variables and functions defined in other files, and how we can have variables and functions accessible only within a single file. This chapter concludes with a case study: an initial implementation of a set data type.

Jump to: [Previous Chapter | Next Chapter]


  1. LOCAL VARIABLES
  2. GLOBAL VARIABLES
  3. STORAGE CLASSES
  4. TYPE QUALIFIERS
  5. USER-DEFINED TYPES
  6. HEADER FILES
  7. PRIVATE VARIABLES AND FUNCTIONS
  8. CASE STUDY: ABSTRACT DATA TYPES

Objectives





예)

main module: main function을 포함하는 프로그램의 기본 모듈

graphics module: graphics 관련 function들로 구성된 프로그램 file들

communication module, text processing module, ...


                              main.c
                              ----------------------
                              #include "module1.h"
                              #include "module2.h"

                              main()
                              {
                                   ProcA();
                                   ProcB();
                              }


module1.h                                                    module2.h
--------------                                               ---------------
void ProcA(void);                                            void ProcB(void);


module1.c                                                    module2.c
--------------                                               ---------------
#include "module1.h"                                         #include "module2.h"

void ProcA(void)                                             void ProcB(void)
{                                                            {
. . .                                                        . . .
}                                                            }





변수의 사용 범위 (영향을 미치는 범위, scope), 수명




Global variable (전역 변수): Function 외부에서 정의되어 그 후 모든 function에서 사용 가능. 프로그램 수행 시 계속 존재 (메모리를 할당받아 프로그램 종료 시까지 사용 가능)



Local variable (지역 변수): Function 내부 또는 block 내에서 정의되어 그 function 또는 block 내에서만 사용 가능. Function 실행이 끝나면 자동 소멸.


예)

int g;              // global variable g declaration

void func(void)
{
   int i;           // local variable i 선언

   . . . 
}



Storage class - 자료가 유지되어야 할 기간 및 범위 결정


Storage class 종류

  1. auto: automatic, default storage class (특별한 정의가 없으면 자동으로 auto로 지정)

  2. static: 기억 장소를 영구히 할당

  3. extern: external, 다른 file에서 정의된 global variable 공유

  4. register: 가능한 한 CPU register 이용 (고속 수행이 가능하다). 컴퓨터 기종에 따라 사용 제한


예)

static int g;    // 변수 g는 이 변수가 선언된 file 내에서만 사용 가능
float f;         // 변수 f는 다른 file에서도 참조 가능.
                 // 단, extern float f; 를 선언해 주어야 한다.

void func1(void) // Function func1은 다른 file에서도 호출 가능.
                 // 단, function prototype을 정의해 주어야 한다.
{
   static int i; // 변수 i는 func1 실행이 끝나도 값을 유지.
   int d;        // 변수 d는 func1 실행이 끝나면 값이소멸
   . . .
}

static func2(void) // Function func2는 다른 file에서 호출 불가능
{
   . . .
}



변수의 초기화 (Variable Initialization)

  • 변수는 사용하기 전에 반드시 초기화하여야 한다.

  • 초기화하지 않은 auto와 register 변수는 변수에 할당된 메모리에 저장된 임의의 값을 사용한다.

  • 초기화하지 않은 global과 static 변수는 0으로 compile시 초기화된다.


    변수 초기화 예)

  • auto와 register 변수 초기화: [자료형 변수명 = 식(expression)]
              int a = 10;
              char ch = 'A';
              int b = a + ch;
    


  • global과 static 변수 초기화: [자료형 변수명 = 수식(numeric expression)]
              static int a = 10;
              static double d = 3.141592;
              int b = 10 * 20;
              int c = a * b;     // Wrong
              int d = getchar(); // Wrong
    

    여러 개의 서로 연관된 자료에 대해 특정 값을 부여하려면

    방법 1) #define 문 사용

    #define SUNDAY 0
    #define MONDAY 1
    #define TUESDAY 2
    #define WEDNESDAY 3
    #define THURSDAY 4
    #define FRIDAY 5
    #define SATURDAY 6

    방법 2) Enumeration type 사용

    enum { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } ;

    enum type의 정의 : enum tag_name { list of elements };
    enum variable 정의 : enum tag_name list of variables ;
    enum tag_name { list of elements } list of variables
    ;

  • 각각의 element에 특정값을 부여할 수 있고 특정 값을 부여하지 않을 경우 첫번째 element에 0을 배정하고 다음 element 부터 1 씩 증가.

    예)

    enum MONTH { JAN = 1, FEB, MAR, ..., NOV, DEC };
    enum MONTH BirthMonth, SalaryMonth, ... ;


    Enumeration type과 같이 하나, 둘, 셀 수 있는 형태의 자료를 scalar type이라 한다. C에서 scalar type들은 자동적으로 integer로 처리된다. 그러므로 enum type의 element들도 연산에 사용될 수 있다. (그러나 상수로 취급되기 때문에 새로운 값을 assign할 수 없다.)


    Type Qualifiers : const, volatile

    const : 특정 변수를 상수처럼 취급. 변수 값이 초기화 된 후 값 변경이 불가능.

    예) const int MAXVAL = 100;
    #define MAXVAL 100 과의 차이는?


    새로운 data type의 정의 : typedef

    typedef data_structure type_name;

    예)

    typedef unsigned char BYTE;
    BYTE a, b, c;
    typedef enum { FALSE, TRUE } bool; bool x, y, z;
    typedef char * string; typedef enum { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } WEEK_DAY ;


    Interface Design (Random Number Library)

    Algorithms


    실습) 다음과 같은 산수 교육용 프로그램을 작성하라.

    임의의 두 수의 더하기 또는 빼기를 연습한다. (더하기 또는 빼기를 임의로 선택)

    사용 예)

    계산해 보세요. 23 + 5 ? 28
    맞았읍니다. 참 잘했어요.

    계산해 보세요. 35 - 17 ? 20
    다시 해 보세요. 35 - 17 ? 18
    맞았읍니다. 참 잘했어요.

    계산해 보세요. 17 - 20 ? 20
    다시 해 보세요. 17 - 20 ? 18
    다시 해 보세요. 17 - 20 ? 0
    다시 해 보세요. 17 - 20 ? -1
    다시 해 보세요. 17 - 20 ? -3
    맞았읍니다. 참 잘했어요.

    계산해 보세요. 35 - 17 ? [ctrl-z]
    종료


    Assignment #7 (기간: 1주일)

    위 프로그램을 저학년용으로 다음과 같이 수정 보완하라.

    10장 (Pointer) 읽어 오기


    [ Table Of Contents | Previous Chapter | Next Chapter]