edited by
9,993 views
46 votes
46 votes

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 if:

Line 1 is replaced by auto int $a = 1$;

Line 2 is replaced by register int $a = 2$; 

  1. $\begin{array}{ll}  \text{3}  & \text{1} \\ \text{4}  & \text{1} \\ \text{4}  & \text{2} \\ \end{array}$
  2. $\begin{array}{ll}  \text{4}  & \text{2} \\ \text{6}  & \text{1} \\ \text{6}  & \text{1} \\ \end{array}$
  3. $\begin{array}{ll}  \text{4}  & \text{2} \\ \text{6}  & \text{2} \\ \text{2}  & \text{0} \\ \end{array}$
  4. $\begin{array}{ll}  \text{4}  & \text{2} \\ \text{4}  & \text{2} \\ \text{2}  & \text{0} \\ \end{array}$
edited by

4 Answers

Best answer
36 votes
36 votes

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$


$prtFun()$
$a=2$ //previous a is lost
$b=1$
$a= a  + \text{++}b = 2+2 = 4$
$b = 2 $
printf $\rightarrow  4 \ 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 D.

3 votes
3 votes

I tried the same and I am getting C
Here is my code:

#include<stdio.h>

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);
        }
 

0 votes
0 votes

Static is special but Register and Auto has nothing special in terms of Scope. So a simple execution follows.

Answer:

Related questions

45 votes
45 votes
4 answers
1
40 votes
40 votes
5 answers
2
48 votes
48 votes
4 answers
3
go_editor asked Apr 21, 2016
13,582 views
Consider the following relations $A, B$ and $C:$ $$\overset{\textbf{A}}{\begin{array}{|c|c|c|}\hline\\\textbf{Id}& \textbf{Name}& \textbf{Age} \\\hline12& \text{A...
42 votes
42 votes
3 answers
4