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?
It’s not a secret or a GCC extension. Variables are allowed to be declared in the conditions of things like
ifs,whiles, andswitches. For example:or
After they are declared an initialised, they are converted to a
boolvalue and if they evaluate totruethe 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 ofif, the scope is also over all theelse ifandelseblocks too).In §6.4.1 of the C++03 standard, it says
So as you can see, it allows
type-specifier-seq declarator = assignment-expressionin the condition of aniforswitch. And you’d find something similar in the section for the "repetition constructs".Also,
switches work on integral orenumtypes or instances of classes that can be implicitly converted to an integral orenumtype (§6.4.4):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 🙂