1 / 28

Lexical Elements, Operators, and the C System

2. chapter. Lexical Elements, Operators, and the C System. 내 용. Characters and Lexical Elements Comments Keywords Identifiers Constants String Constants. 내 용. Operators and Punctuators Precedence and Associativity of Operators Increment and Decrement Operator Assignment Operators

Download Presentation

Lexical Elements, Operators, and the C System

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 2 chapter Lexical Elements, Operators,and the C System

  2. 내 용 • Characters and Lexical Elements • Comments • Keywords • Identifiers • Constants • String Constants

  3. 내 용 • Operators and Punctuators • Precedence and Associativity of Operators • Increment and Decrement Operator • Assignment Operators • the C System • Style

  4. Characters and Lexical Elements • 컴파일러 • 언어의 문법을 확인하는 프로그램 • 전처리기가 먼저 작동하므로 전처리기도 컴파일러의 일부로 간주 • 프로그램을 이루는 문자들을 토큰으로 모아 구별 • 토큰(tokens) • C언어에서 사용되는 어휘 요소들 • 키워드, 식별자, 상수, 문자열 상수, 연산자, 구두점

  5. Characters and Lexical Elements • 프로그램에서 사용할 수 있는 문자

  6. Characters and Lexical Elements • token의 종류 • identifier : letters, digits, ‘_’로 구성된 token • operator : 연산자 • punctuator : { } , ; ( ) • keyword : c에서 특별한 의미를 갖는 예약어 • Token사이의 공백문자(white space) • 허용되며 적절한 공백문자의 사용으로 보다 프로그램 이해력을 향상 Space, tab, new line

  7. Comments • /*와*/ 사이에 있는 문장 • Compiler 에 의해 무시되는 문장 • 프로그램의 수행과는 무관 • 프로그램 흐름의 이해를 높이기 위한 문장 • 프로그램 작성자, 작성일, 목적, 설명 등을 표시 • 주석문의 예 /* a commnet */ /*** another comment **//*****/ /* * A comment ca be written in this fashion * to set it off from the surrounding code. */ /*************************** * If you wish, you can * * put comments in a box. * ***************************/

  8. Keywords • 하나의 token으로 간주되며 program에서 특별한 의미를 갖는 예약어

  9. Identifiers • 함수명, 변수명 등을 말한다 • 영문자(a-z, A-Z), 숫자(0-9), underscore (_)로 구성 • 영문자 나 underscore(_) 로 시작 • 대, 소문자 구별 • 255자 까지 가능, 그러나 첫 31자 까지만 인식 • Keywords 는 사용될 수 없다

  10. Identifiers • C 에서 사용할 수 없는 식별자의 예 • 인식되는 식별자의 길이 • ANSI C : 31자 • C컴파일러와 운영체제에 따라 8자까지 인식되는 경우도 있음 not#me /* 특수문자 #는 사용할 수 없다 */ 101_south/* 식별자는 숫자로 시작할 수 없다 */ -pius/* ‘_’를 ‘-’로 실수하기 쉽다 */

  11. Constants • 정수형 상수(Integer Constants) • 8진수, 10진수, 16진수로 표현 • 실수형 상수(Float Constants) • 부동소수점 상수라고도 함. • 6장에서 자세히… • 상수의 예 0 /*10진 상수 */ 77 /*10진 상수 */ 0123/* 8진 상수 */ -49/* 상수 수식 */ 123.0/* 부동소수점형 상수 */

  12. String Constants • 문자형 상수(Character Constants) • 단일 따옴표(’)로 둘러 싸인 문자 • 문자열 상수(String Constants) • 이중 따옴표(“”)로 둘러 싸인 문자 • Compiler에 의해 배열(Array) 형태로 저장 • Character constants와 구분 예 ‘a’ /* 문자 */ “a” /* 문자열 */

  13. String Constants • 공백에 의해 구분되는 두개의 문자열은 compiler에 의해 단일문자열로 간주 "abc" "def" 는 ”abcdef"와 같다.

  14. Operators and Punctuators • 산술 연산자의 예 • 구두점 • 괄호(()), 중괄호({}), 쉼표(,), 세미콜론(;) • main뒤에 오는 괄호는 연사자처럼 취급됨 • Unary Operators • +, - : 양수, 음수 표현 • 오른쪽에서 왼쪽방향으로 계산 나머지 연산 + - * / %

  15. Operators and Punctuators • 이항연산자(Binary operator) • 왼쪽에서 오른쪽 방향으로 계산 • + , - , * , / , % • *, /, % 가 +, - 보다 우선순위가 높다. • 왼쪽에서 오른쪽 방향으로 계산 • %연산자 • 나머지를 계산 • Operand의 type이 정수가 아닌 경우 error • 배수 구하기 등에 사용 5%2=2 -7%2=-1

  16. Precedence and Associativity of Operators 1 + 2 - 3 + 4 - 5 는 (((1 +3) - 3) + 4) - 5 와 같다.

  17. Increment and Decrement Operators • 증가 연산자 Postfix k++ Prefix ++k • 감소 연산자 Postfix k-- Prefix --k k=k+1 k=k-1 Prefix : operand가 사용되기 전에 먼저 증가/감소 시킴 Postfix : operand가 사용된 후에 증가/감소 시킴

  18. Increment and Decrement Operators • 틀린 사용 예 • 선언/초기화와 예 777++; ++(a * b - 1) ;

  19. Assignment Operators • Compiler는 = 을 연산자로 인식 • variable을 위한 메모리 공간에right_side의 값이 할당된다 • 모든 연산자 중에서 우선순위가 가장 낮다. • 오른쪽에서 왼쪽으로의 결합성을 갖는다 • 예 variable = right_side b = 2; c = 3; a = b + c; /* a = (b = 2) + (c = 3) */ a = b = c = 0; /* a = ( b = (c = 0) ) ) */

  20. Assignment Operators • 대입 연산자의 종류 • 예 = += -= *= / = %= >>= <<= &= ^= |= j *= k +3 은 j = j * (k +3)과 동일, j = j * k + 3 과는 다름 • int k = 5; • k += 2; /* k = k + 2, k=7 */ • k -= 2; /* k = k - 2, k=5 */ • k *= 2; /* k = k * 2, k=10 */ • k /= 2; /* k = k / 2, k=5 */ • k %= 2; /* k = k % 2, k=1 */

  21. Assignment Operators • 대입문이 계산되는 과정을 보여주는 예

  22. 예제 : 2의 멱승 /* Some powers of 2 are printed. */ #include <stdio.h> int main(void) { intexponent = 0, power_of_tow = 1; while (++exponent <= 10) printf("%5d", power_of_two *= 2); printf("\n"); return 0; } 2 4 8 16 32 64 128 256 512 1024

  23. The C System • 전처리기(Preprocessor) • #로 시작되는 줄은 전처리기 명령 • 전처리기 명령은 컴파일러가 아닌 전처리기에 의해 처리됨 • 예 • #define • compile 전에symbol을 모두value로 바꾸어 줌 #include <stdio.h> #define PI 3.14159 #include "filename" #define symbol value

  24. The C System • #include • 컴파일 전에 주어진 파일의 복사본을 include문 대신 삽입 • 삽입되는 파일은 헤더파일(header file)로서 확장자명은 ‘~.h’ • 헤더파일의 주된 목적 : • 함수의 프로토타입(prototype)을 제공하기 위함 • stdio.h에 들어있는 내용 예 intprintf(const char *format, ...); intscanf(const char *format, ...);

  25. The C System • 표준 라이브러리(The Standard Library) • 많은 유용한 함수 제공으로 다양하고 강력한 C system의 구현 가능 • 보다 신속한 수행을 위해 컴파일된 함수 제공 • 제공되는 함수 사용을 위해 함수 호출문과 그 함수를 호출하기 위한 함수 프로토타입의 제공 필요 • 표준 라이브러리: 컴파일된 함수들로 구성. • 표준 헤더 파일 : 주로 함수 프로토타입들을 포함하는 파일로서 라이브러리 함수를 사용하기 위해서는 그 함수 프로토타입이 정의된 헤더파일의 include가 필요

  26. 예제 : 난수(정수형) 출력 /* Printing random numbers. */ #include <stdio.h> #include <stdlib.h> int main(void) {    int i, n;    printf("\n%s\n%s", "Some randoml distributed integers will be printed.",     "How many do you want to see?  "); scanf("%d", &n);    for (i=0; I < n; ++i) {        if (i % 6 == 0)   printf("\n");       printf("%9d", rand());   }   printf("\n");    return 0; } rand()함수는 0~32767사이의 난수(정수)를 return해주는 library함수로 이 함수의prototype은 stdlib.h에 정의됨

  27. 예제 : 난수(정수형) 출력 • 11을 입력했을 경우 Some randomly distributed integers will be printed. How many do you want to see?  11     16838     5758    10113     17515    31051     5627     23010     7419    16212      4086     2749

  28. Style • Space의 절약 보다 Readability 가 중요 y = 2; z = 3; x = ( y = 2) + (z = 3); x = y + z; • Compound Assignment의 선호 a += 7; a = a + 7; • program readability의 향상을 위해 주석 삽입 필요 • Program의 작성일, 작성자, program의 목적, block단위 또는 line단위의 수행 방법 등을 반드시 표시

More Related