Disclaimer: This question is out of curiosity only, obviously one should never try to do this.
I understand that constants are not variables. But the value of a constant has to be stored somewhere in memory right? And that memory location has an address. So there must be a way to get that address, right?
Something like this:
const int seven = 7;
void Test()
{
Console.Write(seven);//7
int* pointerToSeven = GetThePointerOfConstSeven();//here we get the pointer to the constant
Increment(pointerToSeven);
Console.Write(seven);//8
}
void Increment(int* value)
{
(*value) ;
}
Ignoring the fact that this is a stupid thing to do, is there any way to do this in C#?
CodePudding user response:
The main answer is no, it isn't possible. That is because the 7
doesn't have to be stored in (data) memory anywhere - it is just referred to directly as a number in the IL and machine code.
Consider:
const int seven = 7;
Console.WriteLine(seven);
Which produces IL:
IL_0000 ldc.i4.7
IL_0001 call Console.WriteLine (Int32)
Which becomes machine code:
L0006 mov [rsp 0x20], rax
L000b mov ecx, 7
L0010 call System.Console.WriteLine(Int32)
As you can see, the const int seven
becomes a literal 7
in the code.
However, one type of const
does require storage - a const string
. Then you can get a char*
and modify the string
const string sv = "7";
Console.WriteLine(sv); // outputs 7
unsafe {
fixed (char* p = sv) {
*p = '8';
}
}
Console.WriteLine(sv); // outputs 8
As you noted, this is a very bad idea.
CodePudding user response:
The compiler replaces constants with literals. At runtime, the only place in memory that holds the value of the constant is a variable whose value was assigned from the constant.
Incidentally, the compiler also does this with values that can be computed from constants at compile time. This means you don't gain any efficiency by defining constants for simple arithmetic operations on other constants. For example, there's no runtime difference between defining a constant HALF_PI
and just writing Math.PI / 2
everywhere. The reason to define HALF_PI
would be convenience or readability.