Click here to Skip to main content
15,879,535 members
Please Sign up or sign in to vote.
2.71/5 (6 votes)
See more:
How can we change the value of a constant at run time?

The declaration is as follows:

C
const int a=10;


Please help!

:confused:
Posted
Updated 13-Dec-10 22:09pm
v3

// How can we change the value of a constant at run time?

Hmm... Where could be a reason for us, please ? :)
 
Share this answer
 
I'd dare say if you want to change "a" in your program then don't declare it as a const int. Leave out the const part and make that int a;.
Then you're free to change it as much as you want.


Cheers,


Manfred
 
Share this answer
 
Comments
#realJSOP 14-Dec-10 8:53am    
It looks like he's performing maintenance coding. Redefiniing anything that already exists without fully understanding and accounting for side effects elsewhere in the code is an egregiously *bad idea*.
fjdiewornncalwe 14-Dec-10 10:32am    
continuing on John's statement... which is why this variable is probably a const. Changing it will likely have serious adverse effects on the solution. (I 5'd your answer though because it is a correct answer to the OP's question.)
C
#include<stdio.h>
#include<conio.h>


void main()
{
    const int x = 5;
    int *p = (int *) &x;
    printf("x = %d\n", x);
    *p = 10;
    printf("x = %d", x);
    getch();
}
 
Share this answer
 
v3
Comments
Dalek Dave 14-Dec-10 4:31am    
Edited for Code Block.
#realJSOP 14-Dec-10 8:48am    
Just because you can, doesn't mean you should. If someone ever did that on a programming team I was on, I'd see that they got fired. Clever code, stupid programmer.
fjdiewornncalwe 14-Dec-10 10:34am    
Something that is defined as a const should never be changed. The original developer did it that way for a reason. Unless you can verify every usage of the variable to not be negatively affected by a change, I wouldn't do it. If you did have to change it, then simply recompile with the const keyword removed, but comment the hell out of your reasoning for do so in the source.
You can't (shouldn't). A constant is called a constant because it's value is - well - constant.

EDIT ==================

Why did you vote this a 1? It's damn well correct. A constant cannot be changed at runtime, dynamically or otherwise. That's why it's called a "constant".

If you need to redefine a constant, you can do this:

const int a = 10;
const in newA = a + 5;


At that point, your old const definition still exists, but new code that needs it can use the new definition.
 
Share this answer
 
v3
Comments
Henry Minute 14-Dec-10 9:15am    
Compensated.
fjdiewornncalwe 14-Dec-10 10:31am    
I'll compensate as well. I don't care if this guy is a brand new developer. I think it was in my very first or second development class ever that I learned about the const keyword. It may very well not be the OP who voted you the 1 though. It may just be one of the pricks who trolls through here looking for people they don't like.
Aescleal 14-Dec-10 14:33pm    
While you can make an argument that you shouldn't modify something defined as const in C your answer's just plain wrong.

The problem with this answer is that const doesn't mean "constant" (as in invariant) in C. Right from the time it was introduced into the language it's only meant "read only through this label." If you alias the variable you can modify it. It's an accepted part of C - if you really want something invariant there are cleaner and more C idiomatic ways of doing it.

Interestingly if you look through most large bodies of well maintained C code you won't find many non-pointer variable's defined as const. You find loads of pointer definitions that are though. C programmers tend to use the preprocessor or enumerations to define true invariance.
Just tried Mukesh's code inside VS2010 C++ project:

C++
int _tmain(int argc, _TCHAR* argv[])
{
    const int x = 5;
    int *p = (int *) &x;
    printf("x = %d\n", x);
    *p = 10;
    printf("x = %d", x);
    return 0;
}


And guess what? Running the console application yields:
x = 5
x = 5


Debugging the application step by step shows x having a value of 10 in the variable view, but the output is the same as above:

x = 5
x = 5


Now that's strange. Some how the pointer stuff does not work in C++, when x is declared as const int.

Cheers,

Manfred
 
Share this answer
 
v2
Comments
Alain Rist 14-Dec-10 6:47am    
C++ is not C :)
Aescleal 14-Dec-10 7:18am    
I wouldn't expect it to work either. In C when you declare a const you get a variable that the compiler won't let you modify - unless you short circuit the compiler using some pointer tricks. It takes space in memory and you can do all sort of disgusting things to it.

In C++ when you declare a const you get an alias for a value - there is no variable to modify. When you take an address of a const though the compiler creates a real variable and initialises it with the value, leaving the original const value untouched.

Incidentally it's one of the gotcha questions you can ask to quickly detect people with a superficial understanding of C++. Admittedly they've usually sunk themselves already by not being able to write an exception safe assignment operator...
#realJSOP 14-Dec-10 8:38am    
Even if it did work, redefining the value of a const is a bad f*ckin idea. You have NO CLUE what kind of side-effect it's going to have on the rest of the code.
fjdiewornncalwe 14-Dec-10 10:35am    
I believe the compiler causes the memory space pointed to by a const declaration to be protected in C++, but in C that internal protection is not enforced.
Manfred Rudolf Bihy 14-Dec-10 14:06pm    
Sorry, if you all misunderstood my intention of posting this. I was freaked out to find that x took on the value 10 in the debuggers variable view, whilst the output was 5 both before and after the manipulation. Just saying...
It should probably have been a new question along the lines "Why does debugger variable view differ from output"
In C you can cast away the const and you'll be able to modify the variable. You also deserve the bad thoughts maintenance programmers will be sending your way.

Incidentally this won't work in C++ - a const is a const is a const and there's nothing you can do to modify a variable you've defined as being const.

Cheers,

Ash

PS: To whoever marked me down, care to enlighten me as to why?
 
Share this answer
 
v2
Comments
#realJSOP 14-Dec-10 8:43am    
Once you "cast it away", it's no longer a const. It's simpler (and more maintainable) just to assign a new variable to the const value and modify that new variable.
Aescleal 14-Dec-10 14:22pm    
No, the variable is still a const, at least as constant as it was before. The problem you're having here is that in C there's no such thing as a const - whenever you see const think "read only through this alias" which doesn't stop something being mutable through other aliases.

Generally it's a bad idea to remove const or otherwise modify things that have a const label. However sometimes it's nice to be signal to the compiler that something is logically const but has mutable components - e.g. a transparent caching mechanism. C++ allows you to do this with const - with C you have to fall back on bit fiddling and pointers which most C programmers know about.
Aescleal 14-Dec-10 14:50pm    
Ooops, can't edit comments apparently, they're obviously const in the C++ sense. The last sentence should have been:

" C++ allows you to do this with const and mutable - with C you have to fall back on bit fiddling and pointers which most C programmers know"
OK - so it is a bit off topic, but this is my favorite compiler bug of all time. Back in the 70's (showing my age here), there was a Fortran compiler that DID let you change a constant; in fact, you could literally change the value of any number. To minimize executable size in core (that's in RAM for you youngsters), it only stored any given value once. Then, if you called a function and passed in a value by reference, you could change that value, and it would update memory location where the constant was stored. Kind of like this in pseudo-code:

sub anySub(by ref anyArg)
    anyArg = anyArg + 1
end sub

sub main()
   print 4         // this would print "4"
   call anySub(4)  // call sub, passing in same number by ref
   print 4         // this would print "5"! From now on 4=5
end sub


Good luck debugging under that compiler.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900