Home / C Programming / Const :: Discussion

Discussion :: Const

  1. What will be the output of the program (in Turbo C)?

     #include 
     int fun(int *f)
     {   
          *f = 10;   
          return 0;
     }
     int main() 
     { 
        const int arr[5] = {1, 2, 3, 4, 5};    
        printf("Before modification arr[3] = %d", arr[3]);  
        fun(&arr[3]);   
        printf("\nAfter modification arr[3] = %d", arr[3]);     
        return 0;
     } 
    

  2. A.

    Before modification arr[3] = 4
    After modification arr[3] = 10

    B.

    Error: cannot convert parameter 1 from const int * to int *

    C.

    Error: Invalid parameter

    D.

    Before modification arr[3] = 4
    After modification arr[3] = 4

    View Answer

    Workspace

    Answer : Option A

    Explanation :

    Step 1: const int arr[5] = {1, 2, 3, 4, 5}; The constant variable arr is declared as an integer array and initialized to

    arr[0] = 1, arr[1] = 2, arr[2] = 3, arr[3] = 4, arr[4] = 5

    Step 2: printf("Before modification arr[3] = %d", arr[3]); It prints the value of arr[3] (ie. 4).

    Step 3: fun(&arr[3]); The memory location of the arr[3] is passed to fun() and arr[3] value is modified to 10.

    A const variable can be indirectly modified by a pointer.

    Step 4: printf("After modification arr[3] = %d", arr[3]); It prints the value of arr[3] (ie. 10).

    Hence the output of the program is

    Before modification arr[3] = 4

    After modification arr[3] = 10


Be The First To Comment