본문 바로가기

프로그래밍/C language

3. Control Flow

3.1 Statements and Blocks

- expression 뒤에 semicolon이 붙을 경우 그것은 statement가 된다.
- Block은 declaration과 statement를 하나로 묶은 것으로, compound statement라고도 함
문법적으로 하나의 statement와 동일하다.
ex) if문이나 function문

3.2 If-Else

- Decision을 표현할 때 사용, brace(중괄호)를 사용하는 것이 의도를 잘 보여주어서 좋음
- if (expr)

    statement1
  else
    statement2

3.3 Else-If

- Multi-way decision을 표현할 때 사용, 순서대로 evaluated 됨
- if - else if - else 문을 사용하는 binary search를 if-else문으로
변형함으로써, 실행시간을 단축시키는 효과를 얻을 수 있었음

3.4 Switch

- Multi-way decision을 표현할 때 사용
- Expression이 특정 case에 해당하는 constant값을 만족시킬 때, 그 부분이 실행


-  switch (expr){
case const-expr : Statements
case const-expr : Statements
...
default : Statements  => 기본적으로 실행되는 문장, 논리적으로 없어도 되지만 명시적으로 표현하는 것이 좋음
}


- Statements 마지막에 break;를 붙이면 switch문을 빠져나감
break문이 없을 경우, 그다음 case에 대해서도 검사하게 됨
따라서, statements의 끝부분마다 특별한 경우가 아니면 명백히 break를 써주는 것이 권장됨
이럴 경우, 추후에 변형이나 추가에 robust 해 지게 됨

3.5 Loops -While and For

- 반복되는 것은 control 하기 위한 loop
- 구조는 아래와 같고, expr 또는 expr2가 non-zero이면 statement가 실행됨


- while(expr)
     statement 


- for(expr1;expr2;expr3)
     statement


- expr1,3는 생략 가능, initialization과 step을 밟아가는 iteration에 적합
- expr1,3은 ', '를 사용하여 여러 가지 변수를 초기화하거나, step을 밟아갈 수 있음
이때, evaluation은 left to right 순서임
- expr1,3에는 control과 관련되지 않은 다른 expr가 들어가지 않도록 하는 것이 좋음

3.6 Loops-Do-while


-  do{
    statement
  }while(expr);


- evaluate -> execute 순서가 아닌, execute -> evaluate 순서로 진행되는 loop 
따라서 반드시 한 번은 실행이 됨
- 이것은, 어떠한 예외의 상황에서도 한 번의 실행을 보장함

3.7 Break and Continue

- break문은 for, while, do-whlile, switch문에 쓰이면서 innermost의 loop 또는 switch를 탈출시켜준다.
- continue문은 loop문에서만 쓰이며, 다음번 iteration이 실행된다.


- ex) loop문 내부의 continue를 포함한 switch문 예시
while(expr){
    switch(expr){
    case const-expr : Statements
         break; // while문이 아닌 switch문을 빠져나옴
    case const-expr : Statements
         continue; // while문의 다음 iteration으로 넘어감
    case const-expr : Statements
    } 
}

3.8 Goto and Labels

- Goto문은 labeling 된 곳으로 가서 그곳의 statement를 실행한다.
- 거의 쓰이지 않으며, goto문의 사용은 코드의 유지보수와 이해를 어렵게 만든다.
- 중첩된 loop문을 여러 번의 복잡한 break를 쓰지 않고 빠져나올 수 있다.
- ex) for(...)
           for(...)
               if(disaster)
                   goto error;
error:
     statement


- 이것은 약간의 반복에 대한 비용과 추가 변수 공간을 감수하고 다음과 같이 구현할 수도 있다.
ex) for(...)
        for(...)
            if(disaster)
                 error = 1;
if(error)
    statement
else
    statement

'프로그래밍 > C language' 카테고리의 다른 글

6. Structures  (0) 2021.08.14
5. Pointer and Arrays  (0) 2021.08.11
4. Function and Program Structure  (0) 2021.03.29
About C language bulletin board  (0) 2021.03.29
2. Types, Operators, and Expressions  (0) 2021.03.29