함수원형 (function prototype) -...

53
Advanced Networking Tech. Lab. Yeungnam University (yuANTL) Programming Language Prof. Young-Tak Kim 4 - 21 함수 원형 (Function Prototype) 함수 원형(function prototype): 컴파일러에게 함수에 대하여 미리 알리는 것 int compute_sum(int n); int main(void) { int sum; sum = compute_sum(100); printf(“sum=%d \n”, sum); } int compute_sum(int n) { int i; int result = 0; for(i = 1; i <= n; i++) result += i; return result; } compute_sum()함수 이름이랬지컴파일러

Upload: others

Post on 09-Sep-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 21

함수 원형 (Function Prototype)

함수 원형(function prototype): 컴파일러에게 함수에대하여 미리 알리는 것

int compute_sum(int n);int main(void){

int sum;sum = compute_sum(100);printf(“sum=%d \n”, sum);

}int compute_sum(int n){

int i;int result = 0;for(i = 1; i <= n; i++)

result += i;return result;

}

compute_sum()은함수 이름이랬지…

컴파일러

Page 2: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 22

함수 원형의 형식

함수 원형(function prototype) : 미리 컴파일러에게함수에 대한 정보를 알리는 것

(예) int get_integer(void); int combination(int n, int r);

(예) int get_integer(void); int combination(int, int);

반환형 함수이름(매개변수1, 매개변수2, ... );

자료형만 적어주어도 됨!

Page 3: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 23

함수 원형을 사용하지 않는 예제

int compute_sum(int n){

int i;int result = 0;for(i = 1; i <= n; i++)

result += i;return result;

}

int main(void){

int sum;sum = compute_sum(100);printf(“sum=%d \n”, sum);

}

함수 정의가 함수 호출보다 먼저 오면 함수 원형을 정의하지않아도 된다.

그러나 일반적인 방법은 아니다.

Page 4: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 24

함수 원형과 헤더 파일보통은 헤더 파일에 함수 원형이 선언되어 있음

Page 5: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 25

라이브러리 함수라이브러리 함수(library function): 컴파일러에서

제공하는 함수 표준 입출력: scanf(), printf() 수학 연산: sqrt(), rand(), sin(), cos() 문자열 처리: strcat(), strcpy(), strcmp(), strlen() 시간 처리: time() 오류 처리: exception handling 데이터 검색과 정렬: search, sorting

Page 6: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 26

난수 (random number) 함수

난수(random number)는 규칙성이 없이 임의로생성되는 수이다.

난수는 암호학이나 시뮬레이션, 게임 등에서 필수적이다.

rand() 난수를 생성하는 함수 0부터 RAND_MAX까지의 난수를 생성

Page 7: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 27

1부터 45 사이로 제한된 난수 생성

printf("%d ", 1+(rand()%45));

하지만 실행할 때마다 항상 똑같은 난수가 발생된다.

42 18 35 41 45 20

Page 8: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 28

실행할 때마다 다르게 하려면

매번 난수를 다르게 생성하려면 시드(seed)를 다르게하여야 한다. srand( (unsigned)time( NULL ) );

#include <stdlib.h>#include <stdio.h>#include <time.h>

#define MAX 45int main( void ){

int i;

srand( (unsigned)time( NULL ) );for( i = 0; i < 6; i++ )

printf("%d ", 1+rand()%MAX );return 0;

}

Seed를 설정하는 가장 일반적인 방법은 현재의 시각을 시드로 사용하는 것이다. 현재 시각은 실행할 때마

다 달라지기 때문이다.

Page 9: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 29

32,767보다 더 큰 난수의 생성

rand() 함수의 한계 rand() randomly generates 0 ~ RAND_MAX (32,767) integer value if big random numbers (e.g., 0 ~ 500,000) are necessary, rand()

cannot be used

32,767보다 더 큰 난수로 구성된 배열 생성 genBigRandArray(int mA[], int bigRandMax) generates non-duplicated big random numbers

in the range of 0 ~ bigRandMax-1,where bigRandMax can be bigger than RAND_MAX (32,767)

as result, the non-duplicated random numbers are contained in mA[]

Page 10: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 30

BigRand()

Generation of random numbers with bigRandMax> 32767

unsigned int uint_32, bigRand;

uint_32 = ((unsigned int)rand() << 15) | rand(); // bitwise left shift, bitwise ORbigRand = uint_32 % bigRandMax;

uint_32(represented

by 30 valid bits)

014rand() << 15

014rand() :

0 ~ 32767(represented by

15 bits)

bigRand(0 ~ bigRandMax-1)

bitwise OR

uint_32 % bigRandMax

Page 11: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 31

genBigRandArray()1. Procedure genBigRandArray(int mA[], int bigRandMax) 2. char *flag; 3. unsigned int uint_32;4. unsigned int bigRand; 5. int count = 0;

6. srand (time(0)); // use current time as seed; needs #include <ctime>7. flag = (char *)malloc(sizeof(char) * bigRandMax);8. while (count < range) {9. uint_32 = ((long) rand() << 15) | rand();

// generation by bit-wise shift of 15-bit rand short integer// and bit-wise or

10. bigRand = uint_32 % bigRandMax;11. if (flag[bigRand] == 1) { // if this bigRand was already generated12. continue;13. } else {14. flag[bigRand] = 1; // else, use this bigRand, and mark the flag15. mA[count++] = bigRand;16. }17. } // end while18. END Procedure

Page 12: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 32

유틸리티 함수 (Utility Function)

함수 설명

exit(int status) exit()를 호출하면 호출 프로세스를 종료시킨다.

int system(const char *command)system()은 문자열 인수를 운영 체제의 명령어 셀에게

전달하여서 실행시키는 함수이다.

#include <stdlib.h>#include <stdio.h>int main( void ){

system("dir");printf("아무 키나 치세요\n");getch();system("cls");return 0;

}

C 드라이브의 볼륨에는 이름이 없습니다.볼륨 일련 번호: 507A-3B27c:\source\chapter02\hello\hello 디렉터리2011-11-28 오후 04:32 <DIR> .2011-11-28 오후 04:32 <DIR> ..2011-11-16 오전 11:01 20 binary.bin...4개 파일 5,296 바이트3개 디렉터리 69,220,450,304 바이트 남음아무 키나 치세요

Page 13: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 33

수학 라이브러리 함수(Math Library Function)

Page 14: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 34

// 삼각 함수 라이브러리

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

int main( void ){

double pi = 3.1415926535;double x, y;

x = pi / 2; y = sin( x ); printf( "sin( %f ) = %f\n", x, y ); y = sinh( x ); printf( "sinh( %f ) = %f\n",x, y ); y = cos( x ); printf( "cos( %f ) = %f\n", x, y ); y = cosh( x ); printf( "cosh( %f ) = %f\n",x, y );

}

예제여러 수학 함수들을 포함하는 표준 라이브러리

sin( 1.570796 ) = 1.000000 sinh( 1.570796 ) = 2.301299 cos( 1.570796 ) = 0.000000 cosh( 1.570796 ) = 2.509178

Page 15: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 35

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

#define RAD_TO_DEG (45.0/atan(1))

int main(void) {

double w, h, r, theta;

printf("밑변과 높이를 입력하시오:"); scanf("%lf %lf", &w, &h);

r = sqrt(w * w + h * h); theta = RAD_TO_DEG * atan2(h, w);

printf("빗변= %f 각도= %f\n", r, theta); return 0;

}

예제

상수를 정의하는 전처리 명령문

밑변과 높이를 입력하시오: 10.0 10.0 빗변= 14.142136 각도= 45.000000

Page 16: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 36

수학 라이브러리 함수들 abs(int x), fabs(double x)

abs(-9) // 9를 반환 fabs(-3.67) // 3.67을 반환

pow(double x, double y) 인수 x의 y-거듭제곱인 xy 을 계산한다. pow( 2.0, 3.0 ); // 8.0을 반환

sqrt(double x) 주어진 수의 제곱근을 구한다. 만약에 음수가 입력되면 오류가 발생한다. sqrt( 9.0 ); // 3.0을 반환

ceil(double x) ceil은 x보다 작지 않은 가장 작은 정수를 반환 ceil( -2.9 ); // -2.0을 반환 ceil( 2.9 ); // 3.0을 반환

floor(double x) floor()는 x보다 크지 않은 가장 큰 정수를 반환한다. floor( -2.9 ); // -3.0을 반환 floor( 2.9 ); // 2.0을 반환

Page 17: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 37

변수 (variable)

변수의 속성 : 이름, 타입, 크기, 값 + 범위, 생존 시간, 연결

범위(scope) : 변수가 사용 가능한 범위, 가시성 생존 시간(lifetime) : 메모리에 존재하는 시간 연결(linkage) : 다른 영역에 있는 변수와의 연결 상태

3x x

생성

소멸

생존시간

범위 연결

Page 18: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 38

변수 (variable)

함수

함수

지역 변수(local variable)

지역 변수(local variable)

전역 변수(global variable)

변수의 범위(scope of variable)

전역 변수(Global Variable)

지역 변수(Local Variable)

Page 19: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 39

전역 변수 (Global Variable) 와지역 변수 (Local Variable)

Page 20: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 40

이름이 같은 지역 변수

Page 21: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 41

지역 변수의 생존 기간

{

int x;

………

}

x블록

생존시간

생성

소멸

Page 22: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 42

#include <stdio.h>

int main(void){

int i;

for(i = 0;i < 5; i++) {

int temp = 1; printf("temp = %d\n", temp); temp++;

}return 0;

}

지역 변수 예제

temp = 1 temp = 1 temp = 1 temp = 1 temp = 1

블록이 시작할 때 마다생성되어 초기화된다.

1212121212temp

Page 23: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 43

함수의 인수#include <stdio.h>int inc(int counter);

int main(void){

int i;

i = 10;printf("함수 호출전 i=%d\n", i);inc(i);printf("함수 호출후 i=%d\n", i);return 0;

}함수 호출전 i=10 함수 호출후 i=10

함수의 인수도일종의 지역변수

int inc(int counter) {

counter++; return counter;

}

10

10i 11

Page 24: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 44

전역 변수 (Global Variable)

전역 변수(global variable)는 함수 외부에서 선언되는변수이다.

전역 변수의 범위는 소스 파일 전체이다. int x = 123;

void sub1(){

x = 456;}

void sub2(){

x = 789;}

전역 변수

Page 25: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 45

전역 변수의 초기값과 생존 기간#include <stdio.h>int counter; // 전역 변수

void set_counter(int i){

counter = i; // 직접 사용 가능

} int main(void){

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

counter = 100; // 직접 사용 가능

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

set_counter(20);printf("counter=%d\n", counter);

return 0; }

counter=0 counter=100 counter=20

*전역변수의 초기값 : 0*생존기간 : 프로그램 시작부터 종료

20i 010020

Page 26: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

전역 변수의 사용// 전역 변수를 사용하여 프로그램이 복잡해지는 경우

#include <stdio.h>void f(void);

int i;int main(void){

for(i = 0; i < 3; i++) {

f(); } return 0;

} void f(void){

for(i = 0; i < 5; i++) printf("#\n");

}

출력은어떻게될까요?

#####

0123456i

( O )( X )

( O )

Page 27: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 47

전역 변수의 사용

거의 모든 함수에서 사용하는 공통적인 데이터는 전역변수로 한다.

일부의 함수들만 사용하는 데이터는 전역 변수로 하지말고 함수의 인수로 전달한다.

전역변수의 경우, 그 값이 다양한 함수에서 변경될 수있어 올바른 값의 범위를 유지하는 데에 어려움이 있을수 있으므로, 가급적 사용하지 않도록 한다.

Page 28: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 48

같은 이름의 전역 변수와 지역 변수// 동일한 이름의 전역 변수와 지역 변수

#include <stdio.h>

int sum = 1; // 전역 변수

int main(void){

int sum = 0; // 지역 변수

printf("sum = %d\n", sum);

return 0; }

sum = 0

지역 변수가전역변수를 가린다.

1sum

0sum

<전역변수 sum>

<지역변수 sum>

Page 29: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 49

생존 기간 정적 할당(static allocation): 프로그램 실행 시간 동안 계속 유지

자동 할당(automatic allocation): 블록에 들어갈때 생성 블록에서 나올때 소멸

Page 30: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 50

저장 유형 지정자 static#include <stdio.h>void sub(void);

int main(void){

int i; for(i = 0;i < 3; i++)

sub(); return 0;

} void sub(void){

int auto_count = 0; static int static_count = 0;

auto_count++; static_count++; printf("auto_count=%d\n", auto_count); printf("static_count=%d\n", static_count);

}

auto_count=1 static_count=1 auto_count=1 static_count=2 auto_count=1 static_count=3

정적 지역 변수로써static을 붙이면 지역변수가

정적변수로 된다.

자동 지역 변수

01 0123static_countauto_count

Page 31: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 51

저장 유형 지정자 register

레지스터(register)에 변수를 저장.

register int i; for(i = 0;i < 100; i++) sum += i;

CPU안의 레지스터에변수가 저장됨

Page 32: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 52

저장 유형 지정자 extern

#include <stdio.h>

int x; // 전역 변수

extern int y; // 현재 소스 파일의 뒷부분에 선언된 변수

extern int z; // 다른 소스 파일의 변수

int main(void){

extern int x; // 전역 변수 x를 참조한다. 없어도된다.

x = 10; y = 20; z = 30;

return 0; } int y; // 전역 변수

int z;

extern1.c

extern2.c

컴파일러에게 변수가 다른곳에서 선언되었음을 알린다.

Page 33: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 53

연결 (Linkage)연결(linkage): 다른 범위에 속하는 변수들을 서로

연결하는 것 외부 연결

내부 연결

무연결

전역 변수만이 연결을 가질 수 있다.

Page 34: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 54

외부 연결 (External Linkage)

전역 변수를 extern을 이용하여서 서로 연결

Page 35: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 55

연결 예제

#include <stdio.h>int all_files; // 다른 소스 파일에서도 사용할 수 있는 전역 변수

static int this_file; // 현재의 소스 파일에서만 사용할 수 있는 전역 변수

extern void sub();

int main(void){

sub(); printf("%d\n", all_files); return 0;

}

extern int all_files;void sub(void){

all_files = 10; }

linkage1.c

linkage2.c

10

연결

0

010

Page 36: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 56

함수앞의 static

#include <stdio.h>

extern void f2();int main(void){

f2();return 0;

}

static void f1(){

printf("f1()이 호출되었습니다.\n");}

void f2(){

f1();printf("f2()가 호출되었습니다.\n");

}

main.c

sub.c

Static이 붙는 함수는 파일안에서만 사용할 수 있다.

Page 37: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 57

저장 유형 정리

일반적으로는 자동 저장 유형 사용 권장

자주 사용되는 변수는 레지스터 유형 (register)

변수의 값이 함수 호출이 끝나도 그 값을 유지하여야 할필요가 있다면 지역 정적 (local static)

만약 많은 함수에서 공유되어야 하는 변수라면 외부 참조변수

저장 유형 키워드 정의되는 위치 범위 생존 시간

자동 auto 함수 내부 지역 임시

레지스터 register 함수 내부 지역 임시

정적 지역 static 함수 내부 지역 영구

전역 없음 함수 외부 모든 소스 파일 영구

정적 전역 static 함수 외부 하나의 소스 파일 영구

외부 참조 extern 함수 외부 모든 소스 파일 영구

Page 38: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 58

가변 매개 변수#include <stdio.h>

#include <stdarg.h>

int sum( int, ... );

int main( void )

{

int answer = sum( 4, 4, 3, 2, 1 );

printf( "합은 %d입니다.\n", answer );

return( 0 );

}

int sum( int num, ... )

{ int answer = 0;

va_list argptr;

va_start( argptr, num );

for( ; num > 0; num-- )

answer += va_arg( argptr, int );

va_end( argptr );

return( answer );

}

합은 10입니다.

Page 39: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 59

재귀(recursion)란?

알고리즘이나 함수가 수행 도중에 자기 자신을 다시호출하여 문제를 해결하는 기법

팩토리얼의 정의

21

)!1(*1

!

nn

nnn

Page 40: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 60

팩토리얼 (Factorial) 구하기

팩토리얼 프로그래밍 #2: (n-1)! 팩토리얼을 현재 작성중인 함수를 다시 호출하여 계산(재귀 호출)

int factorial(int n){

if( n <= 1 ) return(1);else return (n * factorial(n-1) );

}

3!를계산하려면3! = 3*2!

2!를계산하려면2! = 2*1!

1!은 1

2!는? 1!는?

12

3!는?

6

3!은?

3n

Page 41: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 61

팩토리얼 구하기

팩토리얼의 호출 순서

factorial(3) = 3 * factorial(2) = 3 * 2 * factorial(1) = 3 * 2 * 1 = 3 * 2 = 6

factorial(2){

if( 2 <= 1 ) return 1; else return (2 * factorial(2-1) );

}

factorial(1){

if( 1 <= 1 ) return 1;.....

}

②③

factorial(3){

if( 3 <= 1 ) return 1; else return (3 * factorial(3-1) );

}

Page 42: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 62

재귀 알고리즘의 구조

재귀 알고리즘은 다음과 같은 부분들을 포함한다. 재귀 호출을 하는 부분 재귀 호출을 멈추는 부분

else return n * factorial(n-1);

int factorial(int n){

재귀호출을 하는 부분

재귀를 멈추는 부분

}

if( n == 1 ) return 1;

만약 재귀 호출을 멈추는 부분이 없다면?. 시스템 오류가 발생할 때까지 무한정 호출하게 된다.

Page 43: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 63

피보나치 수열 (Fibonacci Series)의계산 #1

순환 호출을 사용하면 비효율적인 예 피보나치 수열

0,1,1,2,3,5,8,13,21,…

순환적인 구현

otherwisenfibnfibnn

nfib)1()2(

1100

)(

int fib(int n){

if( n==0 ) return 0;if( n==1 ) return 1;return (fib(n-1) + fib(n-2));

}

Page 44: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 64

피보나치 수열의 계산

순환 호출을 사용했을 경우의 비효율성 같은 항이 중복해서 계산됨 예를 들어 fib(6)을 호출하게 되면 fib(3)이 4번이나 중복되어서 계산됨 이러한 현상은 n이 커지면 더 심해짐

fib(6)

fib(4) fib(5)

fib(2) fib(3)fib(3) fib(4)

fib(2) fib(3) fib(1) fib(2) fib(1) fib(2) fib(2) fib(3)

Page 45: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 65

이진수 (Binary Number) 출력하기

정수를 이진수로 출력하는 프로그램 작성순환 알고리즘으로 가능

Page 46: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 66

이진수 형식으로 출력하기

// 2진수 형식으로 출력

#include <stdio.h>

void print_binary(int x);

int main(void)

{

print_binary(9);

return 0;

}

void print_binary(int x)

{

if( x > 0 )

{

print_binary(x / 2); // 순환 호출

printf("%d", x % 2); // 나머지를 출력

}

}

1001

Page 47: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 67

함수 오버로딩 (Function Overloading)

동일한 함수 이름 double avg(double d1, double d2); double avg(double d1, double d2, double d3); double avg(int d1, int d2); double avg(int d1, int d2, int d3);

다른 매개변수 목록

Separate function definitionsFunction "signature" Function name & parameter list Must be "unique" for each function definition

Allows same task performed on different data

Page 48: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 68

함수 오버로딩의 예: average()

Function computes average of 2 numbers:double average(double n1, double n2){

return ((n1 + n2) / 2.0);}

Now compute average of 3 numbers:

double average(int n1, int n2, int n3){

return ((double)(n1 + n2 + n3) / 2.0);}

Same name, two functions

Page 49: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 69

Overloaded Average() Cont’d

Which function gets called?

Depends on function call itself: avg = average(5.2, 6.7); Calls "two-parameter average()"

avg = average(6, 8, 4); Calls "three-parameter average()"

Compiler resolves invocation based onsignature of function call "Matches" call with appropriate function Each considered separate function

Page 50: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 70

Overloading Resolution

1st: Exact Match Looks for exact signature Where no argument conversion required

2nd: Compatible Match Looks for "compatible" signature where

automatic type conversion is possible: 1st with promotion (e.g., int double)

– No loss of data 2nd with demotion (e.g., double int)

– Possible loss of data

Page 51: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 71

Overloading Resolution Example

Given following functions: 1. void f(int n, double m);

2. void f(double n, int m);3. void f(int n, int m);

These calls:f(98, 99); Calls #3f(5.3, 4); Calls #2f(4.3, 5.2); Calls ???

Avoid such confusing overloading

Page 52: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 72

Automatic Type Conversion and Overloading Example

Miles-per-Gallondouble mpg(double miles, double gallons){

return (miles/gallons);}

Example function calls:mpgComputed = mpg(5, 20); Converts 5 & 20 to doubles, then passes

mpgComputed = mpg(5.8, 20.2); No conversion necessary

mpgComputed = mpg(5, 2.4); Converts 5 to 5.0, then passes values to function

Page 53: 함수원형 (Function Prototype) - KOCWcontents.kocw.net/KOCW/document/2015/yeungnam/kimyoungt... · 2016. 9. 9. · Advanced Networking Tech. Lab. Yeungnam University (yuANTL)Programming

Advanced Networking Tech. Lab.Yeungnam University (yuANTL)

Programming LanguageProf. Young-Tak Kim4 - 73

Homework 4

4.1 중복되지 않는 big random number array 생성 표준 라이브러리 <stdlib.h>에 포함된 rand() 함수는 0 ~ RAND_MAX (32767)

범위의 난수를 생성하므로, 더 큰 범위의 난수 (예를 들어 0 ~ 100,000)는 사용할수 없다.

이와 같이 RAND_MAX를 초과하는 범위의 난수 (즉, unsigned int가 표현할 수 있는범위: 0 ~ 230-1)를 발생시킬 수 있는 big_rand() 함수의 pseudo code를 작성하라. (Hint: 15비트 단위의 난수를 발생시키는 rand()함수를 두번 호출하여, 이 값을unsigned long의 상위 15비트와 하위 15비트로 각각 사용하는 방법을 고려할 것.)

genBigRandArray(int mA[], int range)의 pseudo code를 작성하라. 위 pseudo code를 기반으로 C program을 작성하라.