Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ switch statement expression evaluation guarantee

Regarding switch the standard states the following. "When the switch statement is executed, its condition is evaluated and compared with each case constant."

Does it mean that the condition expression evaluated once and once only, and it is guaranteed by the standard for each compiler?

For example, when a function is used in the switch statement head, with a side effect.

int f() { ... } switch (f()) {     case ...;     case ...; } 
like image 474
mikk Avatar asked Jul 03 '15 11:07

mikk


1 Answers

I think it is guaranteed that f is only called once.

First we have

The condition shall be of integral type, enumeration type, or class type.

[6.4.2 (1)] (the non-integral stuff does not apply here), and

The value of a condition that is an expression is the value of the expression

[6.4 (4)]. Furthermore,

The value of the condition will be referred to as simply “the condition” where the usage is unambiguous.

[6.4 (4)] That means in our case, the "condition" is just a plain value of type int, not f. f is only used to find the value for the condition. Now when control reaches the switch statement

its condition is evaluated

[6.4.2 (5)], i.e. we use the value of the int that is returned by f as our "condition". Then finally the condition (which is a value of type int, not f), is

compared with each case constant

[6.4.2 (5)]. This will not trigger side effects from f again.

All quotes from N3797. (Also checked N4140, no difference)

like image 51
Baum mit Augen Avatar answered Oct 10 '22 21:10

Baum mit Augen