Tuesday, January 17, 2012

C Scope and Extent Questions

1.int x = 0;
int f()
{
   return x;
}
int g()
{
   int x = 1;
   return f();
}
int main()
{
  printf("%d", g());
  printf("\n");
  getchar();
}
Output: 0
In C, variables are always statically (or lexically) scoped. Binding of x inside f() to global variable x is defined at compile time and not dependent on who is calling it. Hence, output for the above program will be 0.

2.
int * call();
void main(){
int *ptr;
ptr=call();
clrscr();
printf("%d",*ptr);
}
int * call(){
int a=25;
a++;
return &a;
}
In this question variable a is a local variable and its scope and visibility is within the function call. After returning the address of a by function call variable a became dead while pointer ptr is still pointing to address of variable a. This problem is known as dangling pointer problem.


3.void main(){
int i=10;
static int x=i;
if(x==i)
printf("Equal");
else if(x>i)
printf("Greater than");
else
printf("Less than");
}
 
Output:Compiler Error
static variables are load time entity while auto variables are run time entity. We can not initialize any load time variable by the run time variable.
In this example i is run time variable while x is load time variable.

No comments:

Post a Comment