int a, b, c = 0; void prtfun(); main() { static int a
int a, b, c = 0;
void prtfun();
main()
{
	static int a = 1;
	prtfun();
	a = a + 1;
	prtfun();
	printf("%d,%d\n",a,b);
}
void prtfun()
{
	static int a = 2;
	int b = 1;
	a += ++b;
	printf("%d,%d\n",a,b);
}

Q1. What output will be generated by the given code segment?

Q2. If we replace the statement "static int a = 1;" by "auto int a = 1;", and "static int a = 2;" by "register int a = 2;", then what will be the output?

Answer

Q1. Both the local variables a of main function and prtfun are static variables, so their values will persist between different function calls. First time when prtfun is called, value of a (inside prtfun) is initialized to 2, then a += ++b changes a's value as follows: a = a+(b+1) = 2 + 2 = 4, b's value is also changed to 2. So, first time 4, 2 will be printed. Next, a of main function is incremented to 2, and again prtfun is called. This time as a is static, it's value will be initially 4 (as set in the previous call to prtfun), and a += ++b, changes it's value as follows: a = a+(b+1) = 4 + 2 = 6, b's value is changed to 2. So, this time 6, 2 will be printed. Next, from main function, values of a and b are printed which are 2, and 0 (b is a global variable whose default value is 0) respectively. So, output of the code:
4, 2
6, 2
2, 0

Q2. If the storage classes are changed to auto and register from static, the values of a will not persist between different function calls. So, both the times prtfun is called, a will be initialized with 2, and values printed will be 4, 2 (as was only in the first call before). main function will work as before, and 2, 0 will be printed last. So, in this case output of the code:
4, 2
4, 2
2, 0

0Comment