C Programming - Const - Discussion
Discussion Forum : Const - Find Output of Program (Q.No. 8)
8.
What will be the output of the program (in Turbo C)?
#include<stdio.h>
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;
}
Answer: Option
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
Discussion:
12 comments Page 2 of 2.
Himanshu said:
1 decade ago
You are right mohini it is not strange but wrong cause when we execute it, it gives two errors.
Mohini said:
1 decade ago
It sounds strange that const variable can be indirectly modified by a pointer.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers