NVIDIA Interview Question
Software Engineer / Developersvoid f();
main()
{
int i;
for(i=1;i<=3;i++)
f();
}
void f()
{
int x=1; /* (or) auto int x=1 */
x++;
printf("%d",x);
}
output : 2 2 2
because the scope and life of x variable(by default it is called as auto variable) is with in the function f(). but if we declare x as static then the life of x is persist in between calling functions & static variables initialized only once for the program.
void f();
main()
{
int i;
for(i=1;i<=3;i++)
f();
}
void f()
{
static int x=1;
x++;
printf("%d",x);
}
output : 1 2 3
Static keyword results in only one instance of the variable.the memory for the is allocated at compile time
- sudarson October 24, 2010