[PL] Chapter 8

subin·2024년 7월 20일

PL/프로그래밍언어

목록 보기
7/9
post-thumbnail

Selection, Iteration에 대한 내용 (선택문, 반복문)

  • selection: if else, switch
  • iteration: for, while
  • pretest logical loop: 일정 조건의 만족까지 반복을 표현하기 위한 loop문

Control structor → 구조적 프로그래밍

  • goto문 사용하지 않고 시작과 끝지점이 일정
  • 정리
    • 순차구조(concatenation): 구문 순서에 따라 순서대로 수행
    • 선택구조(selection): 프로그램 상태에 따라 여러 구문들 중 하나를 선택해서 수행 → if, switch
    • 반복구조(repetition): 구문을 반복하여 수행, pretest logical loop로 대표 → while, for
  • 셋을 만족하는 것이 structured program
  • c/c++은 이 셋에 더해 goto 사용하므로 구조적 프로그램이 아님
  • python, java는 구조적 프로그래밍

Selection statements

two-way selection

  • if else

    c/c++javapython
    control expression 의 form과 typeexpression while(1) 됨 → arithmetic 일반수식boolean expressionwhile(1) 안됨, while(true)여야함arithmetic 일반 수식 허용
    then, else clauses 표현한줄짜리면 그냥 씀 statement 2개 이상이면 중괄호로 묶어서 표현한줄짜리면 그냥 씀statement 2개 이상이면 중괄호로 묶어서 표현들여쓰기로 작성
    nested selectors가 있을 때 표현 방법if와 else의 숫자가 다를때 else는 항상 가장 가까이 붙어있는 if와 동작하도록 함else는 항상 가장 가까이 붙어있는 if와 동작하도록 함else는 같은 레벨에 위치한 if와 묶음
    • nested selector: 4가지 언어 모두 허용 → 쓰고 싶은만큼 사용 가능

multiple-way selection

  • switch (if else로 구현 가능)
    • python에는 없음. 대신 if-elif-else 로 표현
  • Design Issues:
    1. What is the form and type of the control expression?
      • switch문 안의 control expression
      • c,c++,java: 수식(integer type)
      • python: 각각의 조건마다 boolean 혹은 arithmetic 수식
    2. How are the selectable segments specified?
      • 여러개의 control flow 중 하나의 segment는 어떻게 표현할 것인가
      • c,c++,java: control expression에 따른 code segment는 case로 한다.
      • python: elif 로 한다. elif 뒤에 오는 것에 포함되는 것이 code segment
      • statement sequence가 될 수도, block이 될 수도, compound statement가 될 수도 있다. (명령어 한줄만 되는 것은 아님)
    3. Is execution flow through the structure restricted to include just a single selectable segment?
      • single selectable segment만 되느냐 multiple이 되느냐
      • break 안넣고 case 만족시키면 밑에 있는 것들 모두 실행됨
      • ⇒ 여러개 이상 실행할 수 있도록 함
    4. How are case values specified?
      • case값은 어떻게 표현할 것인가
      • 대부분 integer, 혹은 boolean의 true false
    5. What is done about unrepresented expression values?
      • 표현되지 않은 것들은 어떻게 할 것인가 (case에 안걸리거나, elif에 안걸리는 것들)
      • default, else문으로 처리
  • 기계어는 multiple-way selection 없음
    • 기계어의 conditional branch는 결국 2개 중에 1개 ⇒ 바로 다음걸로 가거나, 레이블로 점프하거나

Iterative Statements

  • for문: counter 기반의 loop문
  • while문 → pretest, do while → posttest : logically based loop

Design Issues:

  1. How is iteration controlled?
    • counter, logical expression에 따라 for, while로 나뉨
  2. Where is the control mechanism in the loop?
    • 맨 뒤 또는 맨 앞. break는 control 제어, exit은 프로세스 종료
    • 선택적으로 가능함, 허용은 된다 (break를 통해. c/c++은 goto로)

Counter-controlled Loops = For문

  • Design Issues:
    1. What are the type and scope of the loop variable?
      • 3개 for ( 1 ; 2 ; 3 )
      • 1: initial expression
      • 2: terminal expression
      • 3: step size
      • 이 3개에서 사용되는 변수: loop variable, integer 사용
      • 2개 이상 쓸 수 있음
    2. Should it be legal for the loop variable or loop parameters to be changed in the loop body, and if so, does the change affect loop control?
      • loop variable을 loop body에서도 변경 가능하게 할 것인가, 초기의 3개의 expression만 제어하도록 할 것인가.
      • 4개 언어 모두 loop body에서의 변경 허용함
    3. Should the loop parameters be evaluated only once, or once for every iteration?
      • loop parameter를 한번만 평가할 것인가, loop를 돌 때마다 평가할 것인가.
      • c, c++, java
        • 1번 위치의 initial expression은 1번만 평가
        • 2,3번 위치의 terminal expression과 step size는 루프 돌때마다 매번 평가
        • c에 대한 loop control은 중간에 변경 가능 : break, goto
    • 위에서 선언하지 않고 initial expression에서 변수 선언해도 된다는 말
  • Java는 control expression boolean만 됨 ⇒ 참,거짓으로 평가되는 수식만 가능하다는 뜻

Logically-Controlled Loops

  • 반복을 boolean expression 의 true, false 여부에 따라 결정
  • Design issues:
    • Pretest or posttest?
      • pretest: while, 4가지 언어 모두 제공
      • posttest: do while, python은 제공 x
        • c,c++ 는 control expression에 arithmetic 가능, goto를 이용한 unconditional branch 제공
        • java는 boolean만 허용, loop body 처음부터 끝까지 다 실행
    • Should the logically controlled loop be a special case of the counting loop statement or a separate statement?

User located Loop control mechanisms

  • break, continue
  • 사용자가 지정한 방식에 의해, 특정 키워드 넣으면 특정 위치에서 반복문 빠져나올 수 있게 하는 것
  • Design issues for nested loops
    1. Should the conditional be part of the exit?
      • break 나 continue 지원?
      • 넷 다 지원
    2. Should control be transferable out of more than one loop?
      • iteration 2개 이상 빠져 나오기 가능?
      • java만 가능함
      • 3언어는 unlabeled exit를 지원
      • java: labeled continue, labeled break → outer:로 루프문 레이블 지정, break outer하면 모든 블록 나감

Iteration Based on Data Structures

  • 자료구조 정의 후, 노드를 순회하며 null이 될때까지 반복문 수행하게 할 수 있음 ⇒ counter기반도, logic기반도 아님, 자료구조 기반임
  • C에서는 프로그래밍언어차원에서 지원X (직접 구현)
  • Python: 지원 (list) ⇒ 그냥 for로 모두 지원
  • Java: 지원 → iterable interface로 가능 ⇒ foreach for (String myElement : myList) {...}
  • C++: 언어자체는 X, vector는 가능 (c보다는 제공하지만 python, java처럼 완벽하게는 X)

Unconditional Branching

  • goto: C, C++, C# 지원
  • goto로 인해 structured program 깨진다. readability ⬇️ reliability ⬇️ writability ⬆️
  • structured program은 모든 control structure의 입구와 출구가 하나

Guarded Commands

  • CSP 모델에서 사용,

  • CSP: communicate sequential processes, 상호작용하는 sequential process, concurrent programming을 가정한 모델

  • parallel programming: 리소스 여러개, 복수개의 리소스에서 동시에 시작하도록 코딩

  • sequential programming: 리소스 하나, 하나의 control flow가 한개

  • 상호작용(통신하려면) ⇒ 프로세스가 컴퓨터에서 동작할 때 PC counter 값 1개, 이 1개가 명령어를 제어. pc counter가 2개 이상으로 쪼개질때 parallel, concurrent program이라고 함

    • concurrent programming: 독립적인 sequential process 여러개가 상호작용하면서 돌아가는 프로그래밍 모델 → CSP

    • 상호작용하려면 필요한 것
      1. communication
      2. Synchronization

      ⇒ 커뮤니케이션과 동기화가 가정된 모델이 CSP

  • CSP모델에서 프로그래밍을 어떻게 할 것인지 제안한 동시성 프로그래밍 모델

  • control flow에 대한 규칙을 제공해야함 ⇒ 3가지에 대해 정의해야 함

    • sequential: 정의할 필요 없음. 순서대로 실행되는 것
    • selection: If 지원
      • if 로 시작하고 fi 로 끝남
    • iteration: Do 지원
      • do 로 시작하고 od 로 끝남
  • 디버깅이 필요 없는 언어, 코딩해서 돌아가면 동작이 100% 확실한 언어 ⇒ 컴파일되면 그냥 돌아감

  • true가 여러개면 그 중 어떤 것이 실행될지 모름 → 하나이상 true면 됨

  • 모두 false면 runtime error

  • false면 실행 안됨

  • true면 뭐가 실행될지 모름 → 랜덤순서로 다 돌다가 남은게 모두 false면 반복문 종료

  • 반복문이 종료되었다는것만으로 디버깅 안해도 코드 만족 확인 가능

  • ⇒ valification이 매우 쉽다

0개의 댓글