2k views

Consider the following C code segment.

int a, b, c = 0;
void prtFun(void);
main()
{
static int a = 1;       /* Line 1 */
prtFun();
a += 1;
prtFun();
printf(“ \n %d %d ”, a, b);
}

void prtFun(void)
{
static int a = 2;       /* Line 2 */
int b = 1;
a += ++b;
printf(“ \n %d %d ”, a, b);
}


What output will be generated by the given code segment?

 3 1 4 1 4 2
 4 2 6 1 6 1
 4 2 6 2 2 0
 3 1 5 2 5 2
edited | 2k views
0
nice question :)
0
it clears the concept of static variable.

main
$a=1$
$prtFun()$
$a=2$
$b=1$
$a= a + \text{++}b = 2+2 = 4$
$b = 2$
printf  $\rightarrow 4 \ 2$
back to main
$a = a+1 \rightarrow 1+1 \rightarrow 2$ (local static a is taken)
$prtFun()$
$a=4$ // previous  value in the function is retained because of static
$b=1$
$a= a + \text{++}b = 4+2 = 6$
$b = 2$
printf $\rightarrow 6 \ 2$
back to main
$a = 2$
$b = 0$ (initial value of global $b$. in $prtFun$ local b is only updated)
printf $\rightarrow 2 \ 0$

edited
0
For q-48

Only thing m not getting is in second call for function prtfun( ) ... Previous value of a persist tht is okay.but in second call of the prtfun( ).. value of a should hv been overwritten bcz of the statement static a=2;

And heading in this way will get another answer.. Plz explain it will overwrite or not
+9
static int a = 2;

This creates a and assigns 2 to it before program run. Due to "static" a won't be assigned 2 on each function call.
0

Doesn't b contain garbage value..????

0
No .. B is globally declared ... So B=0 ..
0
Good Explanation ,Thank you !
0
Extern is default storage class of all global variables as well as functions .Default initial value of extern integral type variable is zero or null. thus here B=0.
0

@arjun sir

in this program local and global variable has same name ,then while back to main why the local value of static x is again 1 why it is not 4?

1
2
3
4
5
6