A Book on C Written by University of Inchon No. 5-1 함수 정의 (1) 함수가 수행할 작업을 기술한 C 코드를 함수정의 (function definition) 라고 한다. int factorial(int n) /* header */

Slides:



Advertisements
Similar presentations
3. 메소드와 변수 SCJP 자격증 프로젝트 발표자 : 최선웅. 1. 메 소 드 개 념 2. 메 소 드 양 식 3. 메 소 드 변 수 4. 메 소 드 예 제 5. 참 고 문 헌 / 자 료 목 차.
Advertisements

1 08 배열. 한국대학교 객체지향연구소 2 C 로 배우는 프로그래밍 기초 2 nd Edition 배열  동일한 자료유형의 여러 변수를 일괄 선언  연속적인 항목들이 동일한 크기로 메모리에 저장되는 구조  동일한 자료 유형이 여러 개 필요한 경우에 이용할 수 있는.
제2장 C 언어의 확장 C++(1).
ㅎㅎ 구조체 구조체 사용하기 함수 매개변수로서의 구조체 구조체 포인터와 레퍼런스 구조체 배열.
쉽게 풀어쓴 C언어 Express 제11장 포인터 C Express Slide 1 (of 27)
2장. 프로그램의 기본 구성. 2장. 프로그램의 기본 구성 2-1"Hello, World!" 들여다 보기 /* Hello.c */ #include int main(void) { printf("Hello, World! \n"); return 0;
9장. C 언어의 핵심! 함수. 9장. C 언어의 핵심! 함수 9-1 함수의 정의와 선언 main 함수 다시 보기 : 함수의 기본 형태 { } 그림 9-1.
제 9 장 구조체와 공용체.
Report #2 - Solution 문제 #1: 다음과 같이 프로그램을 작성하라.
컴퓨터 프로그래밍 기초 [Final] 기말고사
쉽게 풀어쓴 C언어 Express 제9장 함수와 변수 C Express.
3장. 변수와 연산자. 3장. 변수와 연산자 3-1 연산자, 덧셈 연산자 연산자란 무엇인가? 연산을 요구할 때 사용되는 기호 ex : +, -, *, / 3-1 연산자, 덧셈 연산자 연산자란 무엇인가? 연산을 요구할 때 사용되는 기호 ex : +, -, *, /
제4장 블록 및 유효범위 Reading Chap. 5 © 숙대 창병모.
제 6장. 생성자와 소멸자 학기 프로그래밍언어및실습 (C++).
10장 함수.
제 3장. C보다 나은 C++ II.
11장. 포인터 01_ 포인터의 기본 02_ 포인터와 Const.
8장 함수 함수의 필요성 라이브러리 함수와 사용자 정의 함수 함수의 정의, 원형, 호출 배열을 함수 인자로 전달 재귀호출.
컴퓨터 프로그래밍 기초 #02 : printf(), scanf()
6주차: Functions in C and Others
23장. 구조체와 사용자 정의 자료형 2.
쉽게 풀어쓴 C언어 Express 제9장 함수와 변수 C Express Slide 1 (of 33)
14장. 포인터와 함수에 대한 이해.
14. 예외처리.
C#.
13. 연산자 오버로딩.
C 2장. C 프로그램 시작하기 #include <stdio.h> int main(void) { int num;
C 프로그래밍 C언어 (CSE2035) (Chap11. Derived types-enumerated, structure, and union) (1-1) Sungwook Kim Sogang University Seoul, Korea Tel:
Method & library.
사용자 함수 사용하기 함수 함수 정의 프로그램에서 특정한 기능을 수행하도록 만든 하나의 단위 작업
어서와 C언어는 처음이지 제14장.
27장. 모듈화 프로그래밍.
3장 상수 변수 기본 자료형 키워드와 식별자 상수와 변수 기본 자료형 형변환 자료형의 재정의.
제 6장 함수 Hello!! C 언어 강성호 김학배 최우영.
쉽게 풀어쓴 C언어 Express 제14장 포인터 활용 C Express Slide 1 (of 22)
19. 함수 포인터와 void 포인터.
Lesson 2. 기본 데이터형.
Chapter6 : JVM과 메모리 6.1 JVM의 구조와 메모리 모델 6.2 프로그램 실행과 메모리 6.3 객체생성과 메모리
함수와 변수 컴퓨터시뮬레이션학과 2016년 봄학기 담당교수 : 이형원 E304호,
컴퓨터 프로그래밍 기초 - 10th : 포인터 및 구조체 -
2장. 변수와 타입.
프로그래밍 기초와 실습 Chapter 11 Recursion.
처음으로 배우는 C 프로그래밍 제4부 복합 데이터 형 제 7 장 배열.
김선균 컴퓨터 프로그래밍 기초 - 7th : 함수 - 김선균
컴퓨터 프로그래밍 기초 - 8th : 함수와 변수 / 배열 -
5장 선택제어문 if 선택문 switch-case 선택문 다양한 프로그램 작성 조건 연산자.
Chapter 08. 함수.
컴퓨터 프로그래밍 기초 [01] Visual Studio 설치 및 사용방법
Fucntion 요약.
9장. C 언어의 핵심! 함수. 9장. C 언어의 핵심! 함수 9-1 함수의 정의와 선언 main 함수 다시 보기 : 함수의 기본 형태 { } 그림 9-1.
( Windows Service Application Debugging )
함수(Function) ◈ 함수의 개념 및 사용 이유 ◈ 함수 정의, 호출 및 선언 ◈ 지역변수와 전역변수 ◈ return 문
제 6 장 함수(functions).
디버깅 관련 옵션 실습해보기 발표 : 2008년 5월 19일 2분반 정 훈 승
에어 PHP 입문.
7주차: Functions and Arrays
제 8장. 클래스의 활용 학기 프로그래밍언어및실습 (C++).
함수, 모듈.
C언어 프로그래밍의 이해 Ch03. 기본 자료형, 변수와 상수.
컴퓨터 프로그래밍 기초 - 9th : 배열 / 포인터 -
Numerical Analysis Programming using NRs
Static과 const 선언 조 병 규 한 국 교 통 대 학 교 SQ Lab..
9장. C 언어의 핵심! 함수. 9장. C 언어의 핵심! 함수 9-1 함수의 정의와 선언 main 함수 다시 보기 : 함수의 기본 형태 { } 그림 9-1.
동적메모리와 연결 리스트 컴퓨터시뮬레이션학과 2016년 봄학기 담당교수 : 이형원 E304호,
1. 지역변수와 전역변수 2. auto, register 3. static,extern 4. 도움말 사용법
29장. 템플릿과 STL 01_ 템플릿 02_ STL.
어서와 C언어는 처음이지 제21장.
개정판 누구나 즐기는 C언어 콘서트 제13장 동적 메모리 출처: pixabay.
함수 정의, void 자료형 함수 원형선언 함수 호출 변수 영역 규칙 재귀 함수
Presentation transcript:

A Book on C Written by University of Inchon No. 5-1 함수 정의 (1) 함수가 수행할 작업을 기술한 C 코드를 함수정의 (function definition) 라고 한다. int factorial(int n) /* header */ { /* body starts here */ int i, product = 1; for(i = 2; i <= n; ++i) product *= i; return product; } 처음의 int 는 컴파일러에게 함수의 리턴 값이 int 이라는 것을 알려준다. 이 함수를 호출하기 위해서는 factorial(7) 과 같은 수식을 사용하면 된다.

A Book on C Written by University of Inchon No. 5-2 함수 정의 (2) void wrt_address(void) { printf("%s\n%s\n%s\n%s\n%s\n\n", " **********************", " ** SANTA CLAUS *", " ** NORTH POLE *", " ** EARTH *", " **********************",); } 앞부분의 void 는 이 함수는 리턴 값이 없음을 컴파일러에게 알려준다. 두 번째 void 는 인자가 없음을 알려준다.

A Book on C Written by University of Inchon No. 5-3 함수 정의 (3) 함수 정의의 예를 보자. void nothing(void){} /* this function does nothing */ double twice(double x) { return(2.0 * x); } int all_add(int a, int b) { int c;..... return(a + b + c); }

A Book on C Written by University of Inchon No. 5-4 함수 정의 (4) 함수형이 정의되지 않은 경우에는 기본적으로 int 형을 가지게 된다. 함수형을 정확히 명시해 주는 것이 좋은 프로그래밍 습관이다. all_add(int a, int b) {..... 함수의 몸체 부분 안에서 선언된 변수를 지역 (local) 변수라고 하고, 함수 밖에서 선언된 변수를 전역 (global) 변수라고 한다. 다음 예제를 보자.

A Book on C Written by University of Inchon No. 5-5 함수 정의 (5) #include int a=33; /* a is external and initialized to 33 */ int main(void) { int b = 77; /* b is local to main() */ printf("a = %d\n", a); /* a is global to main() */ printf("b = %d\n", b); return 0; }

A Book on C Written by University of Inchon No. 5-6 함수 정의 (6) 프로그램을 작은 함수들의 모임으로 작성하는 데는 중요한 이유가 있다. 1.프로그램의 작성이나 디버깅(debugging) 작업이 훨씬 수월하다. 2.프로그램의 유지와 보수도 쉽게 된다.

A Book on C Written by University of Inchon No. 5-7 return 문 (1) return; return ++a; return(a * b); 함수가 실행되다가 return 문을 만나게 되면 함수는 종료되고, 제어는 함수를 호출한 다음 명령문으로 돌아가게 된다. float f(char a, char b, char c) { int i;..... return i; /* the value returned will be converted to a float */ }

A Book on C Written by University of Inchon No. 5-8 return 문 (2)  return 문은 없거나 여러 개를 포함할 수도 있다. double absolute_value(double x) { if (x >= 0.0) return x; else return -x; }

A Book on C Written by University of Inchon No. 5-9 return 문 (3) 함수가 값을 리턴하더라도 그 값을 꼭 사용할 필요는 없다. while(...) { getchar(); /* get a char, but do nothing with it */ c = getchar(); /* c will be processed */..... }

A Book on C Written by University of Inchon No 함수 원형 함수는 호출되어 사용되기 전에 선언되어야 한다. 함수원형은 컴파일러에게 인자의 형 (type) 과 인자의 개수, 그리고 리턴되는 값의 형을 알려준다. double sqrt(double, double); void f(char c, int i); f(char, int); 두예문은 동등한 함수원형의 선언이다. 함수원형ㅇ느 컴파일러가 프로그램을 더 철저히 검사할 수 있게 한다. return value type

A Book on C Written by University of Inchon No 거듭 제곱표를 생성하는 예제 (1) long power(int, int); void prn_heading(void); void prn_tbl_powers(int); int main(void) { prn_heading(); prn_tbl_of_powers(N);..... void prn_tbl_of_powers(int n) { printf("\n:::: A TABLE OF POWERS ::::\n\n");..... }

A Book on C Written by University of Inchon No 거듭 제곱표를 생성하는 예제 (2) void prn_tbl_of_powers(int n) {..... for(i = 1; i <= n; ++i) { for(j = 1; j <= n; ++j) if(j == 1) printf("%ld", power(i, j)); else printf("%ld", power(i, j)); putchar('\n');..... long power(int m, int n) {..... for(i=1 ; i<=n; ++i) product *= m; return product;.....

A Book on C Written by University of Inchon No 컴파일러 관점에서의 함수선언 (1) 만약 함수선언이나 정의 또는 함수원형의 선언 전에 함수 f(x) 가 호출되었다면, 컴파일러는 기본적으로 다음과 같은 형태로 함수가 선언되었다고 가정한다. int f(); /* default declaration */ int f(x) /* traditional C style */ double x; {..... int f(double x) /* ANSI C style */ {.....

A Book on C Written by University of Inchon No 함수정의 순서의 다른 형태 /* The use of an alternate style is to remove the list of function prototype */ #include #define N 7 void prn_heading(void) {..... } long power(int m, int n) {..... } void prn_tbl_powers(int n) {..... } int main(void) { prn_heading(); prn_tbl_powers(N);.....

A Book on C Written by University of Inchon No 함수 호출과 값에 의한 호출 (1) 프로그램은 항상 main() 함수부터 수행된다. 함수는 함수의 이름과 괄호 안의 인자 리스트를 작성하여 호출된다. 모든 인자는 값에 의한 호출 (call by value) 로 전달된다. int main(void) {..... prn_heading(); prn_tbl_powers(N);.....

A Book on C Written by University of Inchon No 함수 호출과 값에 의한 호출 (2) /* We illustrate the concept of "call by value" */..... int n=3, sum, compute_sum(int); printf("%d\n", n); /* 3 is printed */ sum = compute_sum(n); printf("%d\n", n); printf("%d\n", sum);..... } int compute_sum(int n) { /* sum the integers of 1 to n */... for( ; n > 0; --n) sum += n; /*stored value of n is changed*/ return sum; }

A Book on C Written by University of Inchon No 대형 프로그램의 개발 (1) #includes..... #defines list of fct prototypes pgm.h #include "pgm.h"..... #include "pgm.h"..... #include "pgm.h"..... main.cfct.cprn.c

A Book on C Written by University of Inchon No 대형 프로그램의 개발 (2) 일반적으로 대형 프로그램에서는 각각 별도의 디렉토리에.h 파일과.c 파일을 작성하게 된다. 헤더파일 pgm.h 는 #include, #defines, 열거형 변수 선언, 구조체와 공용체 그리고 다른 프로그램 구성 원소를 포함하고, 마지막으로 함수원형들을 맨 아래에 포함하고 있을 것이다. 헤더파일 pgm.h 는 모든 C 파일의 서두에 사용되어 프로그램과 프로그램 사이를 연결하는 역할을 하게 된다.

A Book on C Written by University of Inchon No 대형 프로그램의 개발 (3) /* A simple example of a large program */ #include /* In file pgm.h: */ #include #define N 3 void fct1(int k); void fct2(void); void prn_info(char *); #include "pgm.h" /* In file main.c: */ int main(void) {..... scanf(" %c", &ans); if(ans == 'y' || ans == 'Y') prn_info("pgm"); for(i=0 ; i < n; ++i) fct1(i);..... }

A Book on C Written by University of Inchon No 대형 프로그램의 개발 (4) #include "pgm.h" /* In file fct.c */ void fct1(int n) {..... for(i = 0; i < n; ++i) fct2(); } void fct2(void) { printf("Hello from fct2()\n"); } #include "pgm.h" /* In file prn.c */ void prn_info(char *pgm_name) { }

A Book on C Written by University of Inchon No 대형 프로그램의 개발 (5) 다음과 같이 컴파일될 수 있다. cc -o pgm main.c fct.c prn.c 컴파일러는 세 개의.c 파일을 컴파일 하고 세 개의.o 파일로 구성된 하나의 실행 가능한 pgm 파일을 만든다.

A Book on C Written by University of Inchon No 단 정 (1) #include int f(int a, int b); int g(int c); int main(void) {..... scanf("%d%d", &a, &b);..... c = f(a, b); assert(c > 0); /* an assertion */.....

A Book on C Written by University of Inchon No 단 정 (2)  assert() 에 인자로 전달된 관계식이 거짓 값을 갖는 경우 시스템은 메시지를 출력하고 프로그램을 중단시킨다. 인자 a 는 1 이나 -1 값을 가지고 b 의 예상 구간을 [7, 11] 안에 있다고 가정해 보자. int f(int a, int b) {..... assert(a == 1 || a == -1); assert(b >= 7 && b <= 11);..... }

A Book on C Written by University of Inchon No 유효범위 규칙 (1) 기본적인 유효범위 규칙은 변수가 선언된 블록 안에서만 그 변수를 이용할 수 있는 것이다. { int a = 2; /* outer block a */ printf("%d\n", a); /* 2 is printed */ { int a = 5; /* inner block a */ printf("%d\n", ++a); /* 5 is printed */ } /* back to the outer block */ printf("%d\n", ++a); /* 3 is printed */ }

A Book on C Written by University of Inchon No 유효범위 규칙 (2) /* We illustrate hidden variables in the nested blocks */ { int a=1, b=2, c=3; printf("%3d%3d%3d\n", a, b, c); /* */ { int b=4; float c=5.0; printf("%3d%3d%5.1f\n", a, b, c); /* */ a = b; { int c; c = b; printf("%3d%3d%3d\n", a, b, c); /* */ } printf("%3d%3d%5.1f\n", a, b, c); /* */ } printf("%3d%3d%3d\n", a, b, c); /* */ }

A Book on C Written by University of Inchon No 유효범위 규칙 (3) 블록 밖에서 선언된 변수가 블록 안에서 다시 선언되지 않았으면 블록 안에 서도 유효하다. 정수형 변수 a 는 바깥쪽 블록에서 선언되고는 다시 선언되지 않았다. 그러므로 블록 안에서 같은 변수로 사용될 수 있다.

A Book on C Written by University of Inchon No 유효범위 규칙 (4) 병렬 블록과 중첩 블록 { int a, b;..... { /* inner block 1 */ float b;..... /* int a is known, but not int b */ }..... { float a;..... /* int b is known, but not int a */ /* nothing in inner block 1 in known */ }.... }

A Book on C Written by University of Inchon No 유효범위 규칙 (5) 디버깅을 위한 블록 구조의 이용 { /* debugging starts here */ static int cnt = 0; printf("*** debug: cnt = %d v = %d\n", ++cnt, v); }

A Book on C Written by University of Inchon No 기억영역 클래스 (1)  C 언어에서 사용되는 변수는 두 가지 속성을 가진다. 하나는 형 (type) 이고 또 다른 하나는 기억영역 클래스 (storage class) 이다. auto extern register static 함수의 몸체 부분에서 선언된 변수는 디폴트로 자동 기억영역 클래스이다. 키워드 auto 를 사용하여 자동 기억영역 클래스임을 명시적으로 선언 할 수도 있다. auto int a, b, c; auto float f; 지역변수들은 블록을 빠져 나가게 되면 모두 메모리에서 제거되어 사용할 수 없게 된다. 그러므로 변수가 저장하고 있던 값들을 잃게 된다.

A Book on C Written by University of Inchon No 기억영역 클래스 (2) 블록과 함수간에 정보를 교환하기 위한 방법 중 외부 변수를 사용하는 방법이 있다. 변수를 함수 밖에서 선언하면, 프로그램이 종료할 때까지 메모리에 계속 남아 있다. 외부변수 (external variable) 들은 전역변수 (global variables) 로 취급되어 외부 변수 선언 뒤에 있는 블록이나 함수가 끝나더라도 사라지지 않고 변수로 존재하게 된다. 다음 예제는 외부 변수의 사용 예이다.

A Book on C Written by University of Inchon No 기억영역 클래스 (3)..... int a=1, b=2, c=3; /* global variables */ int f(void); int main(void) { printf("%3d\n", f()); /* 12 is printed */ printf("%3d%3d%3d\n", a, b, c);..... /* is printed */ } int f(void) { int b, c; /* b and c are local */ a = b = c = 4; /* global b, c are masked */ return (a+b+c); }

A Book on C Written by University of Inchon No 기억영역 클래스 (4)  file1.c 에 저장 #include int a=1, b=2, c=3; /* external variables */ int f(void); int main(void) { printf("%3d\n", f()); printf("%3d%3d%3d\n", a, b, c);..... }  file2.c 에 저장 int f(void) { extern int a; /* look for it elsewhere */ int b, c; a = b = c = 4; return (a + b + c); }

A Book on C Written by University of Inchon No 기억영역 클래스 (5) 위 예문의 두 파일은 분리되어 컴파일 될 수 있다. 두 번째 파일에서 extern 의 사용은 컴파일러에게 이 변수가 현재 파일 내의 어디서나 선언되어 있거나 또는 다른 파일 내에 선언되었음을 알려준다. 외부변수는 프로그램 실행되는 동안 전체에 걸쳐 존재하기 때문에 함수들에 값을 전달하는 용도로 사용될 수 있다. 함수 안으로 정보를 전달하는 데는 두 가지 방법이 있다. 하나는 외부 변수를 사용하는 것이고, 다른 하나는 매개변수를 사용하는 방식이다.

A Book on C Written by University of Inchon No 기억영역 클래스 (6) 모든 함수는 외부 저장영역 클래스를 사용한다. extern double sin(double); extern double sin(double x) {..... 기억영역 클래스 register 는 컴파일러에게 변수를 가능하다면 고속 메모리인 레지스터에 저장되도록 지시하다. { register int i; for(i=0; i < LIMIT; ++i) {..... } } /* block exit will free the register */

A Book on C Written by University of Inchon No 기억영역 클래스 (7) 정적 변수는 두가지 중요한 용도로 사용된다. 기본적인 용도는 그 블록으로 다시 들어갈 때 지역 변수로 선언된 변수가 이전의 값을 유지하고 있게 하는 것이다. void f(void) { static int cnt = 0; ++cnt; if(cnt%2 == 0)..... /* do something */ else..... /* do something different */ }

A Book on C Written by University of Inchon No 정적 외부 변수 (1) 정적 외부 변수는 유효범위의 제한이 있는 외부변수이다. 정적 외부 변수의 유효범위는 그들이 선언된 소스 파일의 아래 나머지 부분이다. 그러므로 해당 파일 안에서 정적 외부 변수 선언보다 앞서서 정의된 함수나 다른 파일에서 정의된 함수들은 정적 외부 변수의 값을 사용할 수 없다. void f(void) {..... /* v is not available here */ } static int v; /* static external variable */ void g(void) {..... /* v can be used here */ }

A Book on C Written by University of Inchon No 정적 외부 변수 (2) /* A family of pseudo random number generators. */..... static unsigned seed = INITIAL_SEED; /* external, but private to this file */ unsigned random(void) { seed =(MULTIPLIER * seed + INCREMENT)% MODULUS; return seed; } double probability(void) { seed =(MULTIPLIER * seed + INCREMENT)% MODULUS; return(seed / FLOATING_MODULUS); }

A Book on C Written by University of Inchon No 정적 외부 변수 (3)  static 의 마지막 용도는 함수정의와 원형을 위한 저장영역 클래스 명시자로 사용되는 것이다. 정적 함수들은 그들이 선언된 파일 내에서만 사용될 수 있다. static int g(void); /* function prototype */ void f(int a) /* function definition */ { /* g() is available here,..... but not in other files */ } static int g(void) /* function definition */ {..... }

A Book on C Written by University of Inchon No 디폴트 초기화  C 언어에서 외부 변수와 정적 변수는 프로그래머가 초기화하지 않아도 시스템에 의해 0 으로 초기화된다. 이와 같은 방식으로 초기화 되는 것에는 배열, 문자열, 포인터, 구조체, 공용체가 있다. 반면에, 자동 변수와 레지스터 변수는 일반적으로 시스템에 의해 초기화되지 않는다.

A Book on C Written by University of Inchon No 재귀 호출 (1) 함수가 자기 자신을 호출하는 것을 재귀호출이라 한다. #include int main(void) { printf("The universe is never ending!"); main(); return 0; }

A Book on C Written by University of Inchon No 재귀 호출 (2) int sum(int n) { if(n <= 1) return n; else return (n + sum(n - 1)); } 재취호출 함수 sum() 은 다음 테이블에서 설명된 것처럼 실행된다.

A Book on C Written by University of Inchon No 재귀 호출 (3) int factorial(int n) { /* recursive version */ if (n <= 1) return 1; else return (n * factorial(n -1)); } 위 예문은 시스템이 제공하는 정수 범위의 한계를 초과하지 않는다면 옳은 값을 계산할 것이다..

A Book on C Written by University of Inchon No 재귀 호출 (4) 대부분 간단한 재귀 함수를 반복 계산 함수 (iterative functions) 로 다시 작성하는 것이 가능하다. int factiorial(int n) { /* iterative version */ int product = -1; for( ; n>1; --n) product *= n; return product; }

A Book on C Written by University of Inchon No 재귀 호출 (5) /* write a line backwards. */ #include void wrt_it(void); int main(void) {..... wrt_it(void);..... } void wrt_it(void) { int c; if((c = getchar()) != '\n') wrt_it() putchar(c); } Input a line: sing a song of sixpence ecnepxis fo gnos a gnis

A Book on C Written by University of Inchon No 재귀 호출 (6) 많은 알고리즘은 재귀호출 방식이나 반복계산 방식을 사용하고 있다. 전형적으로, 재귀호출이 더 간결하고, 같은 계산을 하는 데 더 적은 변수가 필요하다. 이번에는 간단한 예인 피보타치 수열 계산의 효율성에 대해 고찰해 보자. int fibonacci(int n) { if( n <= 1 ) return n; else return(fibonacci(n-1) + fibonacci(n-2)); }

A Book on C Written by University of Inchon No 재귀 호출 (7)