04.01 - 블록 (block)
블록 (=복합 명령문)
복합 명령문(compound statement)이라고도 불리는 블록(block)은 마치 한 명령문같이 보이는 명령문의 그룹이다. 블록은 {
기호로 시작하고 }
기호로 끝나며, 기호 사이에 실행할 명령문을 배치한다. 블록은 단일 명령문이 허용되는 모든 위치에서 사용할 수 있고, 블록 끝에는 세미콜론(;
)이 필요하지 않다.
지금까지 포스트에서 함수를 작성할 때 이미 블록을 사용해본 경험이 있다.
int add(int x, int y)
{ // 시작 블록 (start a block)
return x + y;
} // 끝 블록 (end a block)
int main()
{ // start a block
// 여러 명령문 (multiple statements)
int value(0);
add(3, 4);
return 0;
} // end a block (no semicolon)
블록은 다른 블록 내부에 중첩될 수 있다. 지금까지는 if
문에서 조건이 true
일 때 단일 명령문을 실행했다. 그러나 블록은 단일 명령문이 허용되는 모든 위치에서 사용할 수 있으므로 중첩된 명령문 블록을 사용하여 조건이 true
인 경우 if
문에서 여러 명령문을 실행할 수 있다.
#include <iostream>
int main()
{
std::cout << "Enter an integer: ";
int value;
std::cin >> value;
if (value >= 0)
{ // start of nested block
std::cout << value << " is a positive integer (or zero)" << std::endl;
std::cout << "Double this number is " << value * 2 << std::endl;
} // end of nested block
else
{ // start of another nested block
std::cout << value << " is a negative integer" << std::endl;
std::cout << "The positive of this number is " << -value << std::endl;
} // end of another nested block
return 0;
}
블록 내부에 블록을 배치할 수도 있다.
int main()
{
std::cout << "Enter an integer: ";
int value;
std::cin >> value;
if (value > 0)
{
if ((value % 2) == 0)
{
std::cout << value << " is positive and even" << std::endl;
}
else
{
std::cout << value << " is positive and odd" << std::endl;
}
}
return 0;
}
중첩된 블록(nested block) 수에는 제한이 없다.
번역: 이 포스트의 원문은 http://www.learncpp.com/cpp-tutorial/41-blocks-compound-statements/ 입니다.
'C++ 이야기 > 04. 스코프' 카테고리의 다른 글
C++ 04.06 - 스코프, 주기 및 링크 요약 (Scope, duration, and linkage summary) (1) | 2018.06.28 |
---|---|
C++ 04.05 - static, 정적 변수 (2) | 2018.06.28 |
C++ 04.04 - 전역 변수가 나쁜 이유 (Why global varibles are evil) (0) | 2018.06.28 |
C++ 04.03 - 전역 변수와 링크 (Global variable and linkage) (1) | 2018.06.28 |
C++ 04.02 - 지역 변수, 스코프 그리고 주기 (Local variables, scope and duration) (0) | 2018.06.28 |
댓글 로드 중…