Microsoft Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Phone Interview
Static variables will be initialized once only, no matter how many times the function is terminated. Coz there scope will be the whole program.
I mistakenly written "declared"... :)...
Yeah, my first answer is compiler error will prevent program execution. Second answer is 66,0
Yeah, my first answer is compiler error will prevent program execution. Second answer is 66,0
66 0
coz while printing 'g' it would take the local variable..and static and global variables retain values.
do you remember ..one question was from recursion..and we have to tell the output..i gues f(1)..?
Error..!!! come
undefined reference to 'add'.
it's a tricky question
otherwise answer will be 66,0
#include<stdio.h>
int g = 0;
int Add(int i)
{
static int s=0;
s =s+i;
g=g+i;
return s;
}
int main()
{
int ,j;
for(int i=1;i<=11;i++)
{ int g=0;s=0;
j = add(i);
}
printf("%d,%d",j,g);
return 0;
}
in this g declared in for loop then scop of g inside for loop. and printf outside for loop so it will print globa g i.e 66 coz global ge updated in add function.
ans ids 66,66
I remember that in the original question, the variable g was declared inside the for loop not in the main. So the output will be 66, 66
yes , you are right as in loop s is every time initialize with 0 so answer will be 11,0
It is 66, 0
- Prathamesh March 08, 2012Static variables will be declared once only and though g is declared globally, it is also declared inside main again, so while printing g, the one which declared locally will be preferred and not the one which is declared globally.