In C, what’s the difference between a static const int and a const int in terms of memory alocated?
void f(int *a)
{
static const int b = 10;
const int c = 20;
*a = b + c;
}
Will b only consume sizeof(int)? And c, will it consume sizeof(int) for the 20 value, and sizeof(int), plus a copy instruction during f execution?
Given that both constants are known inside the function, what’s to stop the compiler from making it
*a = 30;? NeitherbnorcMUST have storage in this example.If there is storage needed:
will take up one sizeof(int) [possibly more space is used due to padding, depends on what comes before and after
ain the data section, and there is nothing stating how much padding the compiler will provide for any given scenario – whatever is necessary to make things “work” on the system the compiler is targetting]. Depending on the architecture of the system, there may be code required to set b = 10 [see below about the size of that].Will possibly take up sizeof(int) bytes on the stack, but there will also be code to initialize
bto 20 – which could be any small number – 2, 3, 5, 6, 7, 8, 16 or some such, depending on processor architecture and the type of instrucitons required to get that job done. Of course, the compiler could just use 20 directly wherever it needs to.But all that is required by the compiler is that *a is set to 30 some way or another. Everything else is “up to the compiler”.