The Gateway to Computer Science Excellence
First time here? Checkout the FAQ!
x
+20 votes
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?
 

A.

3

1

4

1

4

2

B.

4

2

6

1

6

1

C.

4

2

6

2

2

0

D.

3

1

5

2

5

2

asked in Programming by Boss (18.3k points)
edited by | 2k views
0
nice question :)
0
it clears the concept of static variable.

1 Answer

+43 votes
Best answer

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$

Answer is C.

answered by Boss (11.5k points)
edited by
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

Sankaranarayanan P.N

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?

see this:https://gateoverflow.in/3361/gate2008-it-51

Answer:

Related questions



Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true

42,699 questions
48,662 answers
156,595 comments
63,970 users