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

C and C++ Interview Questions

4.   When should the volatile modifier be used?

Ans:  

The volatile modifier is a directive to the compiler’s optimizer that operations involving this variable should not be optimized in certain ways.

 There are two special cases in which use of the volatile modifier is desirable.
 1. The first case involves memory-mapped hardware (a device such as a graphics adaptor that appears to the computer’s hardware as if it were part of the computer’s memory), and  
 2. The second involves shared memory (memory used by two or more programs running simultaneously).

Ex - 1: What is the output?
  char *someFun1()
            {
            char temp[ ] = “string";
            return temp;
            }
            char *someFun2()
            {
            char temp[ ] = {‘s’, ‘t’,’r’,’i’,’n’,’g’};
            return temp;
            }          
 int main()
            {
            puts(someFun1());
            puts(someFun2());
            }
Ans:
      Garbage values.
Explanation:

Both the functions suffer from the problem of dangling pointers. In someFun1() temp is a character array and so the space for it is allocated in heap and is initialized with character string “string”. This is created dynamically as the function is called, so is also deleted dynamically on exiting the function so the string data is not available in the calling function main() leading to print some garbage values. The function someFun2() also suffers from the same problem but the problem can be easily identified in this case.

Ex - 2: What is the output?
. main()
{
   char str1[10]="HAI",str2[10];
   str2=str1;
  printf("%s",str2);
  
}

Ans:
compile time error Lvalue required in function main.

Explanation:
Array is sequenece of memeory loaction so can't initialize a array into another one.

SLogix Student Projects
bottom