조건문

컴퓨터 과학에서 조건문(條件文, conditional)이란 어떤 조건이 주어질 때 어떤 동작을 수행하도록 하는, 즉 주어진 조건의 만족 여부에 따라 선택적으로 실행하고자 할 때 사용되는 문장이다. 프로그래머가 명시한 불리언 자료형 조건이 참인지 거짓인지에 따라 달라지는 계산이나 상황을 수행하는 프로그래밍 언어의 특징이다.

If 플로 다이어그램.
If-then-else 플로차트.

C 언어에서의 조건문

C에서는 if를 사용하여 조건문을 만든다. if의 조건이 참이 아닐 때 수행할 동작은 else 문에서 지정 가능하며, if와 else 사이에 else if를 통해 새로운 조건을 넣을 수 있다. C의 영향을 받은 C++, 자바 등도 같은 형식을 따른다.

#include <stdio.h>int main(void){     int a = 2, c = 5;     if(a == c){          printf("a는 c와 같다.");     }     else {          printf("a는 c와 다르다.");     }     return 0;}

이 소스는 a라는 변수에 2를 저장하고 c라는 변수에 5를 저장한 뒤, a와 c가 같은지 확인하고 출력한다. 이 소스는 밑의 소스처럼 좀 더 줄일 수 있다.

#include <stdio.h>int main(void){     int a = 2, c = 5;     a == c ? printf("a는 c와 같다.") : printf("a는 c와 다르다.");     return 0;}

위의 소스는 삼항 연산자를 사용해 if를 사용한 소스와 같은 동작을 수행하는 프로그램을 작성한 것이다. 그러나 이 소스는 else if처럼 다른 조건에서 동작하는 지의 여부를 알 수 없다.

#include <stdio.h>int main(void){     int a = 2, c = 5;     if(a > c){          printf("a는 c보다 크다.");     } else if(a < c) {          printf("a는 c보다 작다.");     } else {          printf("a는 c와 같다.");     }     return 0;}

이 소스는 else if까지 추가시켜서 만든 조건문이다.

case와 switch 문

switch 문 (일부 언어의 경우 case 문이나 다방향 브랜치라고도 함)은 지정된 상수의 값을 비교한 다음, 일치하는 첫 상수에 따라 동작을 취한다.

파스칼:C:셸 스크립트:
case someChar of  'a': actionOnA;  'x': actionOnX;  'y','z':actionOnYandZ;  else actionOnNoMatch;end;
switch (someChar) {  case 'a': actionOnA; break;  case 'x': actionOnX; break;  case 'y':  case 'z': actionOnYandZ; break;  default: actionOnNoMatch;}
case $someChar in   a)    actionOnA; ;;   x)    actionOnX; ;;   [yz]) actionOnYandZ; ;;  *)     actionOnNoMatch  ;;esac

언어별 비교 참조

프로그래밍 언어구조화된 ifswitch 선택산술 if패턴 일치[A]
thenelseelse–if
에이다아니요아니요
C, C++불필요[B]Fall-through아니요아니요
C 샤프불필요[B]아니요아니요
코볼불필요[B]아니요아니요
에펠아니요아니요
F#불필요[C]아니요
포트란 90아니요
불필요[B]아니요아니요
하스켈필요불필요[B]불필요[C]아니요
자바불필요[B]Fall-through[1]아니요아니요
ECMAScript (자바스크립트)불필요[B]Fall-through[2]아니요아니요
메스메티카아니요
오베론아니요아니요
아니요아니요
PHPFall-through아니요아니요
파스칼, 오브젝트 파스칼 (델파이)불필요아니요아니요
파이썬아니요아니요아니요
퀵베이직아니요아니요
루비아니요case w/ Regexp[D]
스칼라불필요[B]Fall-through아니요
SQL[S][S]아니요아니요
비주얼 베이직, 클래식아니요아니요
비주얼 베이직 닷넷아니요아니요
윈도우 파워셸Fall-through아니요아니요

같이 보기

각주

내용주
  1. ^ This refers to pattern matching as a distinct conditional construct in the programming language – as opposed to mere string pattern matching support, such as regular expression support.
  2. 1 2 3 4 5 The often-encountered else if in the C family of languages, and in COBOL and Haskell, is not a language feature but a set of nested and independent if then else statements combined with a particular source code layout. However, this also means that a distinct else–if construct is not really needed in these languages.
  3. 1 2 In Haskell and F#, a separate constant choice construct is unneeded, because the same task can be done with pattern matching.
  4. ^ In a Ruby case construct, regular expression matching is among the conditional flow-control alternatives available. For an example, see this Stack Overflow question.
  5. 1 2 SQL has two similar constructs that fulfill both roles, both introduced in SQL-92. A "searched CASE" expression CASE WHEN cond1 THEN expr1 WHEN cond2 THEN expr2 [...] ELSE exprDflt END works like if ... else if ... else, whereas a "simple CASE" expression: CASE expr WHEN val1 THEN expr1 [...] ELSE exprDflt END works like a switch statement. For details and examples see Case (SQL).
참조주

외부 링크