Where in memory are the const
function parameters stored in C?
Generally the parameters are stored on the stack, but if the parameter is declared const
then where it is stored?
Where in memory are the const
function parameters stored in C?
Generally the parameters are stored on the stack, but if the parameter is declared const
then where it is stored?
Same as any other parameter (implementation dependent). The const qualifier only means the function won't modify its parameter. It doesn't mean the parameter is a compile time constant expression that can be eliminated.
Also, compilers aren't bound to passing arguments/parameters on the call stack (if such a thing exists for an implementation). They can be passed in registers as well, if the compiler deems it better.
const
keyword means that data with this keyword won't be able to modify content.
For example, if function has parameter with const:
void my_func(const char c) {
//Do things
//This is prohibited and will cause error:
c = 3;
}
//Function call
char a = 'a'; //This is stored on RAM somewhere (if inside function, then it is on stack)
my_func(a); //Call function, value of a is pushed to stack.
This function cannot change value of c
inside.
If you have global variable with const parameter, then some compiler will put it to FLASH memory (non-volatile) memory. This happens on embedded systems mostly, but it is not sure that will actually happen.
//This is stored either on RAM or on non-volatile memory (FLASH)
const char str[] = "My string which cannot be modified later";
int main(void) {
//...your code
//This is prohibited:
str[2] = 3; //Error!
}
This str
is constant and is not able to be modified. Now, modern compilers (ARM compilers) will put this to flash memory, on AVR, this might now happen. There you have to add PROGMEM
keyword of GCC for AVR.