0

After compiling into console exe, how does a C++ function, as simple as below:

int sum(int a, int b){
    return a + b;
}

int main(){
    std::cout << sum(3, 5);
    return 0;
}

be calculated in memory? Is there an address or pointer of any memory block or similar?

Thanks,

Benjamin
  • 93
  • 11
  • 1
    You may be interested in looking at the assembly generated by the compiler. –  Sep 28 '19 at 05:03
  • Short answer: each function call creates a function stack where local variables are stored (e.g. `a` and `b`). Those values are loaded and the calculation is done and the result returned to the calling function. – David C. Rankin Sep 28 '19 at 05:07
  • Do you mean does the compiler put that function somewhere at a distinct place in memory ? Maybe it does (eg, you can assign a function pointer to point to it), maybe it doesn’t (eg, the compiler might optimise by in-lining it) – racraman Sep 28 '19 at 05:11
  • @David That's clear. Just one more question, in the example, I assume the total memory needs for the function sum should be more than 8 bytes? – Benjamin Sep 28 '19 at 05:30
  • @racraman sounds great. – Benjamin Sep 28 '19 at 05:38
  • Yes, there is a minimum function stack size for the function stack frame. It generally varies between 1M-4M. Not only does it provide storage for variables, but also memory needed to hold the information for the function return (as well as usable, but not defined sections such as the "red zone", etc). See, e.g.. [Red zone (computing) - Wikipedia](https://en.wikipedia.org/wiki/Red_zone_(computing)) – David C. Rankin Sep 28 '19 at 05:47
  • @David you mean a single function has a minimum area of about 1MB - 4MB? – Benjamin Sep 28 '19 at 06:56
  • Yes. See [How does the gcc determine stack size the function based on C will use?](https://stackoverflow.com/questions/21021223/how-does-the-gcc-determine-stack-size-the-function-based-on-c-will-use). It will be similar for most compilers. – David C. Rankin Sep 28 '19 at 07:10
  • You never worry about memory for function arguments and local variables, they use temporary storage. Except when you declare a large array as a local variable. You then discover how this web site got its name. – Hans Passant Sep 28 '19 at 07:24

0 Answers0