7.1~17 Control flow

주홍영·2022년 3월 12일
0

Learncpp.com

목록 보기
74/199

https://www.learncpp.com/cpp-tutorial/control-flow-introduction/

챕터7에서는 제어문에 대해서 이야기하고 있다
기본적인 내용이 많으므로 간략하게 요약하고 나머지 내용은 생략하겠다

conditional statement : if, switch
jump : goto, continue, break
function calls : function call, return
Loops : for, while, do while
Halts : std::exit(), std::abort()
Exceptions : Try, throw, catch

switch(x)
{
	case 1:
    	break;
    case 2:
    	break;
    case 3:
    	break;
    default:

break를 빼먹지 말것
swich문은 if문과 비슷한 모습

참고로 case 1:에서 int타입 변수를 선언했다고 가정하자
그래도 다른 case에서 모두 사용할 수 있다
왜냐하면 swicth문 전체가 하나의 블락이니까 scope는 swtich문 전체이므로

#include <iostream>
#include <cmath> // for sqrt() function

int main()
{
    double x{};
tryAgain: // this is a statement label
    std::cout << "Enter a non-negative number: ";
    std::cin >> x;

    if (x < 0.0)
        goto tryAgain; // this is the goto statement

    std::cout << "The square root of " << x << " is " << std::sqrt(x) << '\n';
    return 0;
}

goto는 위와 같은 활용법으로 사용한다
switch의 case처럼 statement label로 흐름이 이동한다
활용법은 기억하되
사용은 지양한다

Break 는 오직 루프문 또는 switch문 내에서만 사용가능 하다
(실험 결과 if문에서는 동작하지 않는다)
현재 진행되고 있는 루프 혹은 switch를 종료한다

Continue 는 루프문에서 루프를 종료하고 다음 루프로 곧바로 넘어가는 것이다
즉 루프를 실행하고 있는 와중에 continue를 만나면 나머지 statement를 실행하지 않고
그냥 다음루프로 넘어간다

profile
청룡동거주민

0개의 댓글