How does this code work?

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  # include <stdio .h>
int abc (int a)
{
int x =10;
printf ("\ t in abc before increasing : x= %d\n", x);
x=x+a;
printf ("\ t in abc after increasing : x= %d\n", x);
return x;
}
int main ()
{
int x =100;
int a =20;
a=abc(x);
x=abc(a);
printf (" in main : a=%d, x=%d\n", a, x);
return 0;
}


I would think that it would print the following:
1
2
3
4
5
	in abc before increasing : x= 10
	in abc after increasing : x= 110
	in abc before increasing : x= 10
	in abc after increasing : x= 30
in main: a=110, x=30

but when I run the same code I get a different output why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# include <stdio.h>
int abc (int a)
{
static int x =10;
printf ("\ t in abc before increasing : x= %d\n", x);
x=x+a;
printf ("\ t in abc after increasing : x= %d\n", x);

return x;
}
int main ()
{
int x =100;
printf (" in main : x= %d\n", x);
x=abc(x);
printf (" in main : x= %d\n", x);
x=abc(x);
printf (" in main : x= %d\n", x);
return 0;
}


I would think that is will print:
1
2
3
4
5
6
7
in main: x = 100
	in abc before increasing :  x =10
	in abc after increasing : x=110
in main: x=110
	in abc before increasing: x = 110
	in abc after increasing: x=210
in main: x =220


But the out put is different with 4th line being 120? Where is the 10 coming from?


In the first program, line 14 assigns the return value from abc(), which is 110, to a. The functionality is confusing because main() has local variables a & x, and abc() has a and x also. To see what happens, rewrite abc using different variable names:
1
2
3
4
5
6
7
8
int abc (int i)
{
int j =10;
printf ("\ t in abc before increasing : j= %d\n", j);
j=j+i;
printf ("\ t in abc after increasing : j= %d\n", j);
return j;
}

This is completely equivalent to the original. The important point is that the parameter and the local variable are complete different variables from the ones in main.

In the second example, x is declared as static inside abc(). That means that it is initialized only once at the beginning of the program (actually the first time abc is called). After that it retains its value from one call to the next. It's like this:
1
2
3
4
5
static int x=10;
int abc(int a)
{
...
}

except that (1) x is only visible inside abc and (2) x is actually initialized the first time abc is called.
but how does in the second example x increase by 10 in the second call?
1
2
3
4
int x =100;
int a =20;
a=abc(x);
x=abc(a);



This is in your code, look at the order of things...

First x = 100.
a = abc(x) or a = abc(100). The result a = 110.
Next, x = abc(a) or x = abc(110) since a is now equall to 110.
The result, x = 120.

So why does making the function call add 10 to your number?
Your function starts with x=10, then adds the argument to that 10. Then returns the new value.
Registered users can post here. Sign in or register to post.