I understand that the control flow will go to one of the "case" and
"default" entries in the following example. The code lines 4 and 5 are
not in any of those entries.
Code line 4 & 5 are in the same scope. I want to know why the variable
"b" is defined at line 4 but the assignment at line 5 is skipped. When
are declaration and statement executed respectively? Is declaration
executed at compiling time but statement executed at run-time?
Thank you.
...
{
int b; /*line 4*/
b=20; /*line 5*/
case 1:
printf("b is %d\n",b);
break;
default:
printf("b is %d\n",b);
break;
}
An assignment statement is like any other statement. It is executed
when the control flow of the program "passes through" that statement.
Consider this snippet:
int silly_func(int x)
{
int y = 0;
if (x < -10)
{
y = -1;
}
else if (x > 10)
{
y = 1;
}
return y;
}
The first line inside the brace is a declaration with an initializer,
so y is always initialized to 0 at the start of the function. As to
the two assignment statements, either the first, the second, or
neither of them will be executed. The control flow of the program
does not "pass through" a statement that is controlled by a
conditional expression that happens to be false.
This is not just a property of the braces that I used after the "if"
and "else if". You could remove them and result would be the same.
Nor is it a special property of "if" and other conditional statements.
Look at this similar (in result) example:
int sillier_func(int x)
{
int y = 0;
if (x < -10)
goto negative;
if (x > 10)
goto positive;
goto all_done;
negative:
y = -1;
goto all_done;
positive:
y = 1;
all_done:
return y;
}
This function must perform exactly the same as the first. If y is
between -11 and INT_MIN, it must return -1. If y is between 11 and
INT_MAX, it must return 1. Otherwise, y is between -10 and +10
inclusive, and the function returns 0.
Here the assignments are at the same level, which also happens to be
the same level as the declaration and initializer. But the goto
statements cause just one, or neither, of the assignment statements to
be initialized.
When the flow of control goes "around", instead of "through" a
statement, that statement is not executed.
This also applies to declarations with initializers, although
technically an initializer is not a statement. If the flow of control
goes "around", rather than "through" a declaration with an
initializer, which can only happen in a switch statement, the object
has scope through the end of the block, but is not initialized either.
Note that if you did this in a switch statement:
switch (x)
{
int b = 0;
case 1: printf("b = %d\n", b); break;
}
....you produce undefined behavior when x is 1 because b is an
uninitialized automatic variable.