"Jakob Bieling" <ar****************@rot13.com> schrieb im Newsbeitrag
news:ds*************@news.t-online.com...
Now I was wondering if this is valid code (reference to the appropriate
section/paragraph in the Standard would be nice, as I do not really know
where to look for this kind of thing) and where else I am able to declare
variables (except the obvious "for (int i ...)" case).
For the record, I am asking this out of interest, not because I want to
start declaring my variables in all kinds of funny places :)
There is only one funny place to declare/define a variable -- at the top of
a function body. Variables should be defined as late as possible, and that
is the time of its first use. And of cause a variable should always be
initialized immediately.
That's one of the reason why in C++ you can define a variable almost
everywhere, where you can write a statement, and even at some other places
for statements. The only thing you must not do, you must never jump over a
definition. So the following code is not valid:
switch (something)
{
case 1:
int i = 1;
...
break;
case 2:
...
}
You cannot define a variable inside a switch, but if you write clean code
and such a variable is only used in one case, you can make it valid by using
a compound statement, which restricts the scope of such a variable:
switch (something)
{
case 1:
{
int i = 1;
...
}
break;
case 2:
...
}
Regards
Heinz