Reputation: 506837
While browsing the code of my friend I came to notice this:
switch(State &state = getState()) {
case Begin: state = Search; break;
// other stuff similar
}
What is with the variable in the switch header? He is using GCC so I think this might be a GCC extension. Any idea?
Upvotes: 1
Views: 232
Reputation: 75130
It's not a secret or a GCC extension. Variables are allowed to be declared in the conditions of things like if
s, while
s, and switch
es. For example:
while (char c = cin.get()) { ... }
or
if (int* something = (int*)malloc(4)) { // but don't use malloc in C++
// ...
}
After they are declared an initialised, they are converted to a bool
value and if they evaluate to true
the block is executed, and the block is skipped otherwise. Their scope is that of the construct whose condition they are declared in (and in the case of if
, the scope is also over all the else if
and else
blocks too).
In §6.4.1 of the C++03 standard, it says
Selection statements choose one of several flows of control.
selection-statement: if ( condition ) statement if ( condition ) statement else statement switch ( condition ) statement condition: expression type-specifier-seq declarator = assignment-expression
So as you can see, it allows type-specifier-seq declarator = assignment-expression
in the condition of an if
or switch
. And you'd find something similar in the section for the "repetition constructs".
Also, switch
es work on integral or enum
types or instances of classes that can be implicitly converted to an integral or enum
type (§6.4.4):
The value of a condition that is an initialized declaration in a switch statement is the value of the declared variable if it has integral or enumeration type, or of that variable implicitly converted to integral or enumeration type otherwise.
I actually learned of this FROM AN ANSWER YOU POSTED on the "Hidden Features of C++" question. So I'm glad I could remind you of it :)
Upvotes: 9