programing

C ++ switch 문 식 평가 보장

projobs 2021. 1. 16. 09:12
반응형

C ++ switch 문 식 평가 보장


스위치와 관련하여 표준은 다음과 같습니다. "switch 문이 실행되면 해당 조건이 평가되고 각 case 상수와 비교됩니다."

조건식이 한 번만 평가되고 각 컴파일러의 표준에 의해 보장된다는 의미입니까?

예를 들어, 함수가 부작용과 함께 switch 문 헤드에 사용되는 경우입니다.

int f() { ... }
switch (f())
{
    case ...;
    case ...;
}

f한 번만 호출 되는 것이 보장된다고 생각합니다 .

먼저 우리는

조건은 정수 유형, 열거 유형 또는 클래스 유형이어야합니다.

[6.4.2 (1)] (비 적분 항목은 여기에 적용되지 않음)

표현식 인 조건의 값은 표현식의 값입니다.

[6.4 (4)]. 더욱이,

조건의 값은 사용법이 명확한 "조건"이라고합니다.

[6.4 (4)] 즉, 우리의 경우 "조건"은 유형의 평범한 값 int이지 f. f조건 값을 찾는 데만 사용됩니다. 이제 제어가 switch명령문에 도달하면

그 상태가 평가됩니다

[6.4.2 (5)], 즉 "조건"으로 int반환 된 의 값을 사용합니다 f. 마지막으로 조건 (이 int아닌 유형의 값 f)은 다음과 같습니다.

각 케이스 상수와 비교

[6.4.2 (5)]. 이것은 f다시 부작용을 유발하지 않습니다 .

N3797의 모든 인용문. (또한 N4140 확인, 차이 없음)


N4296 읽기

페이지 10 para 14 :

전체 표현식과 관련된 모든 값 계산 및 부작용은 평가할 다음 전체 표현식과 관련된 모든 값 계산 및 부작용 전에 시퀀싱됩니다.

내가 파라의 첫 줄을 읽을 때. 10 (이상) :

전체 표현식은 다른 표현식의 하위 표현식이 아닌 표현식입니다.

나는 switch문장 의 조건이 완전 표현이고 각 조건 표현이 완전 표현 이라고 믿어야한다 (실행시 사소하지만).

A switch는 표현이 아닌 진술입니다 (6.4.2 및 기타 여러 곳 참조).

그래서 그것을 읽음 switch으로써 case상수 의 평가 전에 반드시에 대한 평가가 이루어져야합니다 .

그 어느 때보 다 많은 요점이 명백한 결론에 도달하기 위해 사양을 잘못 읽는 것으로 귀결됩니다.

내가 그 문장을 동료 검토하면 다음 수정안 ( 굵게 표시 )을 제안 할 것입니다 .

switch 문이 실행되면 해당 조건은 switch 문 실행 당 한 번씩 평가 되고 각 case 상수와 비교됩니다.


예, 표현식은 switch 문이 실행될 때 한 번만 평가됩니다.

§ 6.4 선택 문

4 [...] 표현식 인 조건의 값은 표현식 [...]의 값입니다. 조건의 값은 사용법이 분명한 "조건"이라고합니다.

즉,식이 평가되고 해당 값이 conditioncase에 대해 평가되는 것으로 간주됩니다 .


섹션 6.4.4 :

... 표현식 인 조건의 값은 switch 이외의 문에 대해 상황에 따라 bool로 변환 된 표현식의 값입니다 .... 조건의 값은 단순히 "조건"으로 참조됩니다. 모호하지 않다

내 이해에서 위의 인용문은 다음 의사 코드와 동일합니다.

switchCondition := evaluate(expression)

이제 견적 추가

... 조건이 평가되고 각 케이스 상수와 비교됩니다.

다음으로 번역되어야합니다.

foreach case in cases
    if case.constant == switchCondition
         goto case.block

그래서 네, 이것이 사실 인 것 같습니다.


이 코드가 hello한두 번 인쇄됩니까 ?

int main() {
    printf("hello\n");
}

글쎄요, 대답은 구체적인 switch진술 문구 보다는 표준이 설명하는 것에 대한 더 일반적인 이해에 있다고 생각합니다 .

As per Program execution [intro.execution] the standard describes the behaviour of some abstract machine that executes the program parsed according to the C++ grammar. It does not really define what 'abstract machine' or 'executes' mean, but they are assumed to mean their obvious computer science concepts, i.e. a computer that goes through the abstract syntax tree and evaluates every part of it according to the semantics described by the standard. This implies that if you wrote something once, then when the execution gets to that point, it is evaluated only once.

The more relevant question is "when the implementation may evaluate something not the way written in the program"? For this there is the as-if rule and a bunch of undefined behaviours which permit the implementation to deviate from this abstract interpretation.


The expression is guaranteed that is evaluated only once by the flow of control. This is justified in the standard N4431 §6.4.2/6 The switch statement [stmt.switch] (Emphasis mine):

case and default labels in themselves do not alter the flow of control, which continues unimpeded across such labels. To exit from a switch, see break, 6.6.1. [ Note: Usually, the substatement that is the subject of a switch is compound and case and default labels appear on the top-level statements contained within the (compound) substatement, but this is not required. Declarations can appear in the substatement of a switch-statement. — end note ]

ReferenceURL : https://stackoverflow.com/questions/31206205/c-switch-statement-expression-evaluation-guarantee

반응형