© 2014 Firstsoft Technologies (P) Limited. login
Hi 'Guest'
Home SiteMap Contact Us Disclaimer
enggedu

C and C++ Interview Questions

2. In C, what is the difference between a static variable and global variable?

Ans:

A static variable declared outside of any function is accessible only to all the functions defined in the same file (as the static variable). However, a global variable can be accessed by any function (including the ones from different files).

Ex - 1: What is the output?
  void main()
{
      int i;
      char a[]="\0";
      if(printf("%s\n",a))
            printf("Ok here \n");
      else
            printf("Forget it\n");
}
Ans:
 Ok here

Explanation:
Printf will return how many characters does it print. Hence printing a null character returns 1 which makes the if statement true, thus "Ok here" is printed.

Ex - 2: What is the output?
main()
{
      int a[5];
      printf("%d",*a+1-*a+3);
}
Ans:

Explanation:
       Here array elements have the garbage value.
       *a points starting location of the array a[0].
        a[0] has the garpage value.
        It is an airthmetic expression.
        So *a-*a=0 remaining 1+3=4.
        If a name is not known the preprocessor treats it to be equal to zero.

Ex - 3: What is the output?

            main()
             {
      int arr2D[3][3];
       printf("%d\n", ((arr2D==* arr2D)&&(* arr2D == arr2D[0])) );
               }
Ans
1
Explanation:

This is due to the close relation between the arrays and pointers. N dimensional arrays are made up of (N-1) dimensional arrays. arr2D is made up of a 3 single arrays that contains 3 integers each .The name arr2D refers to the beginning of all the 3 arrays. *arr2D refers to the start of the first 1D array (of 3 integers) that is the same address as arr2D. So the expression (arr2D == *arr2D) is true (1). Similarly, *arr2D is nothing but *(arr2D + 0), adding a zero doesn’t change the value/meaning. Again arr2D[0] is the another way of telling *(arr2D + 0). So the expression (*(arr2D + 0) == arr2D[0]) is true (1).   


SLogix Student Projects
bottom