C question

How can you change the value of a constant variable in C?

Questions by mrinal671987   answers by mrinal671987

Showing Answers 1 - 15 of 15 Answers

This is one of those "tricky" C questions that a lot of interviewers think is clever but is more silly than anything else.  The whole point behind declaring something as "const" is that you *don't* want to change it.  If you find yourself doing something like this in production code, then you need to take a step back and ask yourself *why* you need to do it.  Something's obviously wrong with your design if you need to change the value of something that's been declared "const". 

Having said that, something like the following should work:

const int x = 5;
int *p = (int *) &x;
printf("x = %dn", x);
*p = 10;
printf("x = %dn", x);

trying

  • Oct 27th, 2010
 

At any case we cannot the value of x. because it is declared as const.

and if you write like this

const int x=5;
int *p=(int*)&x;
*p=10;


then p and x points to the same address but will have a different values in it. And iam surprised how that is gona happen. But still i don't know the explanation for this. Can any one help me out with that part why both pointing to the same address and having different values.

  Was this answer useful?  Yes

x should not be a declared as global in this case.  
This is how you can change the value of constant x:
void test()
{
const int x=3;
printf("x before=%d n", x);
}

void main()
{
test();
int x = 10;
printf("x after=%d n", x);
printf("Bingonpress any key to exitn"); 

getch();//waits for key from user and then exits program

}

The output:
x before=3
x after=10
Bingo
press any key to exit

Hope this helps..

  Was this answer useful?  Yes

mrinal671987: I should have checked the language standard before posting that code.  Per section 6.7.3, paragraph 5, "[i]f an attempt is made to modify an object with a const-qualified type through an lvalue with non-const-qualified type, the behavior is undefined." 

IOW, don't do that.  The code I posted invokes undefined behavior, so any result is possible. 

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions