Tuesday, January 17, 2012

C typedef Questions


Question 1
#include<stdio.h>
int main()
{
   typedef int i;
   i a = 0;
   printf("%d", a);
   getchar();
   return 0;
}
Output: 0
There is no problem with the program. It simply creates a user defined type and creates a variable a of type i.

Question 2
#include<stdio.h>
int main()
{
  typedef int *i;
  int j = 10;
  i *a = &j;
  printf("%d", **a);
  getchar();
  return 0;
}
Output: Compiler Error -> Initialization with incompatible pointer type.
The line typedef int *i makes i as type int *. So, the declaration of means a is pointer to a pointer. The Error message may be different on different compilers.

Question 3
#include<stdio.h>
int main()
{
  typedef static int *i;
  int j;
  i a = &j;
  printf("%d", *a);
  getchar();
  return 0;
}
Output: Compiler Error -> Multiple Storage classes for a.
In C, typedef is considered as a storage class. The Error message may be different on different compilers.

No comments:

Post a Comment