SlideShare uma empresa Scribd logo
1 de 12
Baixar para ler offline
Scope Rule & Storage Class
2
Storage Classes
§ Local 변수
– Function안에서 선언되는 variable
– 선언된 function 안에서만 사용 가능
– Function이 호출될 때 function 내부에 선언된 local variable
들은 시스템 스택에 생성되었다가 return하면 없어진다.
• 이후 그 Function이 다시 호출되면, 새로운 영역의 memory가
할당되며, 이전의 값은 유지되지 않는다.
int sum( int k ) {
int a ;
a = k + 3 ;
return a ;
}
3
Storage Classes
§ Local 변수
void func(void) {
int k = 0;
printf( “%dn”, k ) ;
k = 10 ;
printf( “%dn”, k ) ;
}
#include <stdio.h>
void func(void);
int main(void) {
float f = 0 ;
printf( “%fn”, f ) ;
func() ;
func() ;
return 0;
}
4
Storage Classes
§ Global 변수
– Function block 밖에서 선어된 변수
– 모든 함수에서 사용 가능
– 프로그램이 시작할 때 생성된 후 프로그램이 종료될 때까지
메모리에 존재
• 생성된 후 자동으로 0으로 초기화 된다.
int g ;
int main()
{
printf( “%dn”, g );
my_func();
printf( “%dn”, g );
return 0;
}
void my_func()
{
g = 10;
}
5
Storage Classes
§ Global 변수
void func(void) {
int k = 0;
printf( “%d %dn”, k, ++g );
k = 10;
printf( “%d %dn”, k, ++g );
}
#include <stdio.h>
int g;
void func(void);
int main(void) {
printf( “%dn”, g );
func();
printf( “%dn”, g );
return 0;
}
6
Storage Classes
§ static 변수
– global변수와 매우 유사
• 프로그램 시작할 때 생성되었다가 프로그램 끝날 때까지 메모리에
존재
• 변수가 생성된 이후 자동적으로 0으로 초기화가 됨
– Function내부에서 선언된 경우
• 선언된 function 내에서만 접근 가능
– Function 외부에서 선언된 경우
• 선언된 source file내에서만 접근 가능 (추후 여러 파일로 프로그램
작성하기 참고)
7
Storage Classes
§ static 변수
void func(void)
{
static int s ;
int k = 0;
printf( “%d %dn”, k, ++s ) ;
k = 10 ;
printf( “%d %dn”, k, ++s ) ;
}
#include <stdio.h>
void func(void);
int main(void)
{
func() ;
func() ;
return 0;
}
8
Scope Rules
§ static 변수
– 예제: 함수가 몇 번째 호출 되었나?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void do_nothing(void) ;
int main(void)
{
int j ;
srand( time(NULL) ) ;
for( j = 0 ; j < 10 ; j++ )
if( rand() % 2 ) do_nothing() ;
return 0;
}
void do_nothing(void)
{
static int cnt ;
printf( “do_nothing is called %d time(s)n”, ++cnt ) ;
}
9
Storage Classes
§ register 변수
– memory 중에서 가장 빠른 register를 사용하도록 요청
– int만 register로 선언가능
– register로 선언하지 않아도 register에 할당될 수 있고,
register로 선언했어도 register에 할당되지 않을 수 있음
[Ex]
int main() {
register int i; /* register i 와 같음 */
for(i = 0; i < LIMIT; ++i) {
…
}
}
10
const
§ const
– 값을 수정할 수 없는 변수를 선언할 때 type의 앞에 사용
– 선언할 때 반드시 초기화해야 함. 초기화후 값 변경 불 가능
– 변수의 값을 바꿀 수 없도록 선언하는 것.
• 상수를 선언하는 것 아님
[Ex] const int a = 1;
[Ex] const int a = 1;
a = 4; /* error!! */
a++; /* error!! */
11
Scope Rules
§ Scope Rules
– 어느 특정 identifier의 접근 가능성 여부 판단
– declaration statement위치에 따라 접근 범위 결정
– block안에서 선언된 identifier
• 그 block안에서 만 접근 가능
• 그 block이 수행될 때 변수가 생성되었다가 수행이 끝나면 변수
가 없어짐
– block 밖에서 선언된 identifier
• 기본적으로 모든 block에서 접근 가능
• 프로그램이 시작할 때 생겼다가 프로그램이 끝날 때 없어짐.
12
Scope Rules
§ Scope Rules
#include <stdio.h>
int g ;
void function() {
static int a ;
printf(“a=%d g=%d”, a, g);
}
int main(void) {
int a = 3, b = 4;
{
int b=5;
printf(“%d %d”, a, b, g);
}
printf(“%d %d”, a, b, g);
function() ;
}
각각의 변수가 언제 생겼다가
언제 없어지는가?
어느 변수가 어느 변수를
의미하는가?

Mais conteúdo relacionado

Mais procurados

Learning Node Book, Chapter 5
Learning Node Book, Chapter 5Learning Node Book, Chapter 5
Learning Node Book, Chapter 5Ji Hun Kim
 
11장 윈도우 스레드 풀
11장 윈도우 스레드 풀11장 윈도우 스레드 풀
11장 윈도우 스레드 풀홍준 김
 
호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFE호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFEChangHyeon Bae
 
[OpenTRS-001] Hotel California
[OpenTRS-001] Hotel California[OpenTRS-001] Hotel California
[OpenTRS-001] Hotel CaliforniaTheori
 
Startup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSStartup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSCirculus
 
Lightning talk - 11
Lightning talk - 11Lightning talk - 11
Lightning talk - 11DonggyuKim21
 
[Windows via c/c++] 4장 프로세스
[Windows via c/c++] 4장 프로세스[Windows via c/c++] 4장 프로세스
[Windows via c/c++] 4장 프로세스종빈 오
 
Scope and Closure of JavaScript
Scope and Closure of JavaScript Scope and Closure of JavaScript
Scope and Closure of JavaScript Dahye Kim
 
[Pl in c++] 9. 다형성
[Pl in c++] 9. 다형성[Pl in c++] 9. 다형성
[Pl in c++] 9. 다형성MinGeun Park
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort[Algorithm] Shell Sort
[Algorithm] Shell SortBill Kim
 
windows via c++ Ch 5. Job
windows via c++ Ch 5. Jobwindows via c++ Ch 5. Job
windows via c++ Ch 5. JobHyosung Jeon
 
7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성HyeonSeok Choi
 
Promise 패턴 공부
Promise 패턴 공부Promise 패턴 공부
Promise 패턴 공부HongGun Yoo
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises우영 주
 
C 언어 스터디 02 - 제어문, 반복문, 함수
C 언어 스터디 02 - 제어문, 반복문, 함수C 언어 스터디 02 - 제어문, 반복문, 함수
C 언어 스터디 02 - 제어문, 반복문, 함수Yu Yongwoo
 

Mais procurados (19)

함수적 사고 2장
함수적 사고 2장함수적 사고 2장
함수적 사고 2장
 
Learning Node Book, Chapter 5
Learning Node Book, Chapter 5Learning Node Book, Chapter 5
Learning Node Book, Chapter 5
 
11장 윈도우 스레드 풀
11장 윈도우 스레드 풀11장 윈도우 스레드 풀
11장 윈도우 스레드 풀
 
호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFE호이스팅, 클로저, IIFE
호이스팅, 클로저, IIFE
 
[OpenTRS-001] Hotel California
[OpenTRS-001] Hotel California[OpenTRS-001] Hotel California
[OpenTRS-001] Hotel California
 
Startup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JSStartup JavaScript 8 - NPM, Express.JS
Startup JavaScript 8 - NPM, Express.JS
 
Lightning talk - 11
Lightning talk - 11Lightning talk - 11
Lightning talk - 11
 
tcp ip study
tcp ip studytcp ip study
tcp ip study
 
[Windows via c/c++] 4장 프로세스
[Windows via c/c++] 4장 프로세스[Windows via c/c++] 4장 프로세스
[Windows via c/c++] 4장 프로세스
 
Scope and Closure of JavaScript
Scope and Closure of JavaScript Scope and Closure of JavaScript
Scope and Closure of JavaScript
 
[Pl in c++] 9. 다형성
[Pl in c++] 9. 다형성[Pl in c++] 9. 다형성
[Pl in c++] 9. 다형성
 
[Algorithm] Shell Sort
[Algorithm] Shell Sort[Algorithm] Shell Sort
[Algorithm] Shell Sort
 
windows via c++ Ch 5. Job
windows via c++ Ch 5. Jobwindows via c++ Ch 5. Job
windows via c++ Ch 5. Job
 
Jvm
JvmJvm
Jvm
 
7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성7가지 동시성 모델 - 데이터 병렬성
7가지 동시성 모델 - 데이터 병렬성
 
Promise 패턴 공부
Promise 패턴 공부Promise 패턴 공부
Promise 패턴 공부
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
C 언어 스터디 02 - 제어문, 반복문, 함수
C 언어 스터디 02 - 제어문, 반복문, 함수C 언어 스터디 02 - 제어문, 반복문, 함수
C 언어 스터디 02 - 제어문, 반복문, 함수
 
ES6-02
ES6-02ES6-02
ES6-02
 

Destaque

2 2. operators
2 2. operators2 2. operators
2 2. operators웅식 전
 
7 mid term summary
7 mid term summary7 mid term summary
7 mid term summary웅식 전
 
10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스웅식 전
 
12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array웅식 전
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer웅식 전
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io웅식 전
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main웅식 전
 

Destaque (9)

2 2. operators
2 2. operators2 2. operators
2 2. operators
 
6. function
6. function6. function
6. function
 
7 mid term summary
7 mid term summary7 mid term summary
7 mid term summary
 
10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스10장 문자열클래스와파일클래스
10장 문자열클래스와파일클래스
 
7. arrays
7. arrays7. arrays
7. arrays
 
12 1. multi-dimensional array
12 1. multi-dimensional array12 1. multi-dimensional array
12 1. multi-dimensional array
 
11. array & pointer
11. array & pointer11. array & pointer
11. array & pointer
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io
 
15 2. arguement passing to main
15 2. arguement passing to main15 2. arguement passing to main
15 2. arguement passing to main
 

Semelhante a 7. variable scope rule,-storage_class

[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?NAVER D2
 
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...Seok-joon Yun
 
헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리은숙 이
 
프론트엔드스터디 E04 js function
프론트엔드스터디 E04 js function프론트엔드스터디 E04 js function
프론트엔드스터디 E04 js functionYoung-Beom Rhee
 
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화sung ki choi
 
클린코드 17장
클린코드 17장클린코드 17장
클린코드 17장진화 손
 
Javascript 함수(function) 개념, 호출패턴, this, prototype, scope
Javascript 함수(function) 개념, 호출패턴, this, prototype, scopeJavascript 함수(function) 개념, 호출패턴, this, prototype, scope
Javascript 함수(function) 개념, 호출패턴, this, prototype, scopeYoung-Beom Rhee
 
Effective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshinEffective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshinDong Chan Shin
 
Windws via c/c++ chapter 6
Windws via c/c++ chapter 6Windws via c/c++ chapter 6
Windws via c/c++ chapter 6SukYun Yoon
 
C언어 세미나 - 함수
C언어 세미나 - 함수C언어 세미나 - 함수
C언어 세미나 - 함수SeungHyun Lee
 
Api design for c++ pattern
Api design for c++ patternApi design for c++ pattern
Api design for c++ patternjinho park
 
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
[C++ Korea] Effective Modern C++ Study item14 16 +신촌[C++ Korea] Effective Modern C++ Study item14 16 +신촌
[C++ Korea] Effective Modern C++ Study item14 16 +신촌Seok-joon Yun
 
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++Min-soo Park
 
Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심흥배 최
 
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)Kyoungchan Lee
 
Api design for c++ ch3 pattern
Api design for c++ ch3 patternApi design for c++ ch3 pattern
Api design for c++ ch3 patternjinho park
 
Multi-thread : producer - consumer
Multi-thread : producer - consumerMulti-thread : producer - consumer
Multi-thread : producer - consumerChang Yoon Oh
 

Semelhante a 7. variable scope rule,-storage_class (20)

[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?
 
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
 
Exception&log
Exception&logException&log
Exception&log
 
헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리헷갈리는 자바스크립트 정리
헷갈리는 자바스크립트 정리
 
프론트엔드스터디 E04 js function
프론트엔드스터디 E04 js function프론트엔드스터디 E04 js function
프론트엔드스터디 E04 js function
 
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화
제프리 리처의 Windows via C/C++ : 8장 유저 모드에서의 스레드 동기화
 
ES6 for Node.js Study 2주차
ES6 for Node.js Study 2주차ES6 for Node.js Study 2주차
ES6 for Node.js Study 2주차
 
클린코드 17장
클린코드 17장클린코드 17장
클린코드 17장
 
Javascript 함수(function) 개념, 호출패턴, this, prototype, scope
Javascript 함수(function) 개념, 호출패턴, this, prototype, scopeJavascript 함수(function) 개념, 호출패턴, this, prototype, scope
Javascript 함수(function) 개념, 호출패턴, this, prototype, scope
 
Effective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshinEffective c++ chapter1 2_dcshin
Effective c++ chapter1 2_dcshin
 
강의자료4
강의자료4강의자료4
강의자료4
 
Windws via c/c++ chapter 6
Windws via c/c++ chapter 6Windws via c/c++ chapter 6
Windws via c/c++ chapter 6
 
C언어 세미나 - 함수
C언어 세미나 - 함수C언어 세미나 - 함수
C언어 세미나 - 함수
 
Api design for c++ pattern
Api design for c++ patternApi design for c++ pattern
Api design for c++ pattern
 
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
[C++ Korea] Effective Modern C++ Study item14 16 +신촌[C++ Korea] Effective Modern C++ Study item14 16 +신촌
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
 
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++
NHNNEXT 개경프14 Subway Rocket Team Study 3rd C++
 
Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심Modern C++ 프로그래머를 위한 CPP11/14 핵심
Modern C++ 프로그래머를 위한 CPP11/14 핵심
 
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
GopherCon Korea 2015 - Python 개발자를 위한 Go (이경찬)
 
Api design for c++ ch3 pattern
Api design for c++ ch3 patternApi design for c++ ch3 pattern
Api design for c++ ch3 pattern
 
Multi-thread : producer - consumer
Multi-thread : producer - consumerMulti-thread : producer - consumer
Multi-thread : producer - consumer
 

Mais de 웅식 전

15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization웅식 전
 
12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation웅식 전
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function웅식 전
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing웅식 전
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef웅식 전
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement웅식 전
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib웅식 전
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io웅식 전
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types웅식 전
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)웅식 전
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료웅식 전
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)웅식 전
 
13th chapter12 slide
13th chapter12 slide13th chapter12 slide
13th chapter12 slide웅식 전
 
Week12 chapter11
Week12 chapter11 Week12 chapter11
Week12 chapter11 웅식 전
 

Mais de 웅식 전 (20)

15 3. modulization
15 3. modulization15 3. modulization
15 3. modulization
 
14. fiile io
14. fiile io14. fiile io
14. fiile io
 
13. structure
13. structure13. structure
13. structure
 
12 2. dynamic allocation
12 2. dynamic allocation12 2. dynamic allocation
12 2. dynamic allocation
 
10. pointer & function
10. pointer & function10. pointer & function
10. pointer & function
 
9. pointer
9. pointer9. pointer
9. pointer
 
5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
5 1. character processing
5 1. character processing5 1. character processing
5 1. character processing
 
15 1. enumeration, typedef
15 1. enumeration, typedef15 1. enumeration, typedef
15 1. enumeration, typedef
 
4. loop
4. loop4. loop
4. loop
 
3 2. if statement
3 2. if statement3 2. if statement
3 2. if statement
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib
 
2 3. standard io
2 3. standard io2 3. standard io
2 3. standard io
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types
 
Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)Goorm ide 교육용버전 for skku(학생)
Goorm ide 교육용버전 for skku(학생)
 
구름 기본 소개자료
구름 기본 소개자료구름 기본 소개자료
구름 기본 소개자료
 
Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)Goorm ide 소개 슬라이드(교육용 버전)
Goorm ide 소개 슬라이드(교육용 버전)
 
W14 chap13
W14 chap13W14 chap13
W14 chap13
 
13th chapter12 slide
13th chapter12 slide13th chapter12 slide
13th chapter12 slide
 
Week12 chapter11
Week12 chapter11 Week12 chapter11
Week12 chapter11
 

7. variable scope rule,-storage_class

  • 1. Scope Rule & Storage Class
  • 2. 2 Storage Classes § Local 변수 – Function안에서 선언되는 variable – 선언된 function 안에서만 사용 가능 – Function이 호출될 때 function 내부에 선언된 local variable 들은 시스템 스택에 생성되었다가 return하면 없어진다. • 이후 그 Function이 다시 호출되면, 새로운 영역의 memory가 할당되며, 이전의 값은 유지되지 않는다. int sum( int k ) { int a ; a = k + 3 ; return a ; }
  • 3. 3 Storage Classes § Local 변수 void func(void) { int k = 0; printf( “%dn”, k ) ; k = 10 ; printf( “%dn”, k ) ; } #include <stdio.h> void func(void); int main(void) { float f = 0 ; printf( “%fn”, f ) ; func() ; func() ; return 0; }
  • 4. 4 Storage Classes § Global 변수 – Function block 밖에서 선어된 변수 – 모든 함수에서 사용 가능 – 프로그램이 시작할 때 생성된 후 프로그램이 종료될 때까지 메모리에 존재 • 생성된 후 자동으로 0으로 초기화 된다. int g ; int main() { printf( “%dn”, g ); my_func(); printf( “%dn”, g ); return 0; } void my_func() { g = 10; }
  • 5. 5 Storage Classes § Global 변수 void func(void) { int k = 0; printf( “%d %dn”, k, ++g ); k = 10; printf( “%d %dn”, k, ++g ); } #include <stdio.h> int g; void func(void); int main(void) { printf( “%dn”, g ); func(); printf( “%dn”, g ); return 0; }
  • 6. 6 Storage Classes § static 변수 – global변수와 매우 유사 • 프로그램 시작할 때 생성되었다가 프로그램 끝날 때까지 메모리에 존재 • 변수가 생성된 이후 자동적으로 0으로 초기화가 됨 – Function내부에서 선언된 경우 • 선언된 function 내에서만 접근 가능 – Function 외부에서 선언된 경우 • 선언된 source file내에서만 접근 가능 (추후 여러 파일로 프로그램 작성하기 참고)
  • 7. 7 Storage Classes § static 변수 void func(void) { static int s ; int k = 0; printf( “%d %dn”, k, ++s ) ; k = 10 ; printf( “%d %dn”, k, ++s ) ; } #include <stdio.h> void func(void); int main(void) { func() ; func() ; return 0; }
  • 8. 8 Scope Rules § static 변수 – 예제: 함수가 몇 번째 호출 되었나? #include <stdio.h> #include <stdlib.h> #include <time.h> void do_nothing(void) ; int main(void) { int j ; srand( time(NULL) ) ; for( j = 0 ; j < 10 ; j++ ) if( rand() % 2 ) do_nothing() ; return 0; } void do_nothing(void) { static int cnt ; printf( “do_nothing is called %d time(s)n”, ++cnt ) ; }
  • 9. 9 Storage Classes § register 변수 – memory 중에서 가장 빠른 register를 사용하도록 요청 – int만 register로 선언가능 – register로 선언하지 않아도 register에 할당될 수 있고, register로 선언했어도 register에 할당되지 않을 수 있음 [Ex] int main() { register int i; /* register i 와 같음 */ for(i = 0; i < LIMIT; ++i) { … } }
  • 10. 10 const § const – 값을 수정할 수 없는 변수를 선언할 때 type의 앞에 사용 – 선언할 때 반드시 초기화해야 함. 초기화후 값 변경 불 가능 – 변수의 값을 바꿀 수 없도록 선언하는 것. • 상수를 선언하는 것 아님 [Ex] const int a = 1; [Ex] const int a = 1; a = 4; /* error!! */ a++; /* error!! */
  • 11. 11 Scope Rules § Scope Rules – 어느 특정 identifier의 접근 가능성 여부 판단 – declaration statement위치에 따라 접근 범위 결정 – block안에서 선언된 identifier • 그 block안에서 만 접근 가능 • 그 block이 수행될 때 변수가 생성되었다가 수행이 끝나면 변수 가 없어짐 – block 밖에서 선언된 identifier • 기본적으로 모든 block에서 접근 가능 • 프로그램이 시작할 때 생겼다가 프로그램이 끝날 때 없어짐.
  • 12. 12 Scope Rules § Scope Rules #include <stdio.h> int g ; void function() { static int a ; printf(“a=%d g=%d”, a, g); } int main(void) { int a = 3, b = 4; { int b=5; printf(“%d %d”, a, b, g); } printf(“%d %d”, a, b, g); function() ; } 각각의 변수가 언제 생겼다가 언제 없어지는가? 어느 변수가 어느 변수를 의미하는가?