int a-0; // Global accessible anywhere in file. void test (int b) Parameter stat
ID: 3748477 • Letter: I
Question
int a-0; // Global accessible anywhere in file. void test (int b) Parameter static int c-0 int d=0; //Static - retains its value over successive function calls //Loca if(b>_ 0) { int e; 7Local inside block Cat top of block) ANSI C99 only e a b+c+ d; // a,b,c,d are accessible anywhere in test // e is accessible only after this declaration inside the if-block. printf ("e %d ", e); printf (" c %d n", c); int main (O) //"a" is accessible in all functions in the file. test (1); test (2); Exercise 2.9: Hand-execute the code above and predict what gets printed out in your README. Do you think static variables are stored on the stack? Why or why not?Explanation / Answer
calls function test(1)
memory stack
a=0 1st step(stored in heap memory)
a=1 2nd step(stored in heap memory)
c=0 3rd(Stored in heap memory)
d=0 4th(stored in stack memory)
e=garbage value 5th(stored in stack memory)
e=1+1+0+0=2 6th(stored in stack memory)
c=1 7th(stored in stack memory)
As Soon as function gets executed completely,
e pops out of the memory stack
then d
Since, c is not stored in memory stack hence c is not poped out
calls function test(2)
memory stack
d=0 1st(stored in stack memory)
e=garbage value 2nd(stored in stack memory)
e=1+2+1+0=4 3rd(stored in stack memory)
c=2 4th(stored in stack memory)
As Soon as function gets executed completely,
e pops out of the memory stack
then d
hence output printed is :
call to function test(1) gives output:
e=2
c=1
call to function test(2) gives output:
e=4
c=2
Since, Static variables are not stored in stack thus, the value doesn't get destroyed when a function gets executed.
Ans2.
float sum(int n)
{
int i=0;
float total=0;
for(i=0;i<=n;i++)
{
total=total+(1/(pow(2,i)));
}
return total;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.