C Programming - Const - Discussion
Discussion Forum : Const - Find Output of Program (Q.No. 4)
4.
What will be the output of the program?
#include<stdio.h>
int main()
{
const int x=5;
const int *ptrx;
ptrx = &x;
*ptrx = 10;
printf("%d\n", x);
return 0;
}
Answer: Option
Explanation:
Step 1: const int x=5; The constant variable x is declared as an integer data type and initialized with value '5'.
Step 2: const int *ptrx; The constant variable ptrx is declared as an integer pointer.
Step 3: ptrx = &x; The address of the constant variable x is assigned to integer pointer variable ptrx.
Step 4: *ptrx = 10; Here we are indirectly trying to change the value of the constant vaiable x. This will result in an error.
To change the value of const variable x we have to use *(int *)&x = 10;
Discussion:
18 comments Page 2 of 2.
Charan said:
10 years ago
How we can change const variable by using *(int *)&x = 10; (mentioned in explanation). However it is not allowing to change from 5 to 10. But no error also raising.
Logeswari said:
1 decade ago
1)const x is declared as integer and assign the value 5.
2)const ptrx value declared as integer point.
3)ptrx=&x mean ptrx contain address of x which mean *ptrx contain x value 5.
4)then *ptrx=10 mean indirectly change the value of 5 know.
So its wrong.
If any wrong in above statement means please any one clear me.
2)const ptrx value declared as integer point.
3)ptrx=&x mean ptrx contain address of x which mean *ptrx contain x value 5.
4)then *ptrx=10 mean indirectly change the value of 5 know.
So its wrong.
If any wrong in above statement means please any one clear me.
Voski said:
1 decade ago
A small correction in the Explanation Step 2 is needed: ptrx is not a constant, but a pointer to an integer constant.
Bijay said:
1 decade ago
In gcc compiler it will work o/p:10.
Prakash said:
1 decade ago
int main()
{
int x=5;
int *ptrx;
ptrx = &x;
*ptrx = 10;
printf("%d\n", x);
return 0;
}
To change the value of const variable x we have to use *(int *)&x = 10;
{
int x=5;
int *ptrx;
ptrx = &x;
*ptrx = 10;
printf("%d\n", x);
return 0;
}
To change the value of const variable x we have to use *(int *)&x = 10;
Martyf said:
1 decade ago
It is very difficult paper.
Hari said:
1 decade ago
I also don't think step 4 willl work how can it will try to change the value of x answer is 5.
Prudhvi said:
1 decade ago
Any one give me a clear explanation to step 4.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers