Search code examples
cparameter-passingcalling-conventionmemory-layoutcontiguous

Are variables that are passed to a function stored in contiguous memory positions?


I have written this little function:

int mayor(int n1, int n2, int n3, int n4, int n5) {

   int mayor = n1;

   for(int *p=&n2; p<=&n5; ++p)

           mayor = *p;

   return mayor;

}

Is it guaranteed that the memory block that contains n1 to n5 is contiguous? Since I get the expected return value I hope so, but I want to know whether this is safe.


Solution

  • No. The variables do not have even to be in the memory - they can be (all or only some) kept in the registers.

    So your assumptions are wrong. If you want to have them in the contiguous chunks of memory you need to place them there yourself.

    int mayor(int n1, int n2, int n3, int n4, int n5) 
    {
      int parameters[5] = {n1,n2,n3,n4,n5};