Reputation: 161
main()
{
int a = 5, b = a, sum;
sum = a + b;
printf("sum is %d",sum);
}
In this C Program, will variable b
be initialized at compile time or at run time?
Is it compile time initialization?
(C language)
Upvotes: 1
Views: 160
Reputation: 15793
depends on whether the compiler/interpreter implemented the algorithm of constant propagation or not.
C standard does not impose not to use constant propagation. If one detects that that variable is not mutated it can be replaced with the precomputed value. The as-if rule says that one can do whatever optimization we want as time as the result is the expected one.
Upvotes: 1
Reputation: 234665
No, variables should not always be initialised with literals, although some folk like to insure that variables are initialised at the point of declaration (and some firms insist on it) in order to avoid the reading of uninitialised variables in poorly crafted code.
As for any run-time behaviour: the as-if rule applies. Your source code merely describes what you want the behaviour to be, not the machine code that will be generated. Your variables will probably not exist in the compiled binary, which will be equivalent to
int main()
{
printf("sum is %d", 10);
}
(The expression int a = 5, b = a
is well-defined since ,
is a sequencing point, so a
is initialised at the time its value is read to assign to b
.)
Upvotes: 2