英文:
I have query on inline fuction
问题
当内联函数被执行时,它们将使用哪个内存区域?
让我举个例子:
int sum(int a, int b) {
return a + b;
}
变量a和b存储在哪里?
英文:
When inline function gets executed, which memory area they will use
Let me give some example
int sum(int a,int b)
{return a+b;
}
Where the variables a and b are stored ?
答案1
得分: 3
大部分情况下,根本不会使用内存。如果 sum()
的参数在“调用”时已经存储在寄存器中,那么它们将简单相加,然后将和放入另一个寄存器中,或者如果之后不再需要这些寄存器的内容,可以放入其中一个寄存器。
例如,这段代码:
inline int sum(int a, int b) {
return a + b;
}
int main(int argc, char **argv) {
(void)argv;
int a = argc;
int b = a * 5;
return sum(a, b);
}
编译成这样:
_main: ; @main
.cfi_startproc
; %bb.0:
add w8, w0, w0, lsl #1
lsl w0, w8, #1
ret
.cfi_endproc
所有操作都在寄存器中完成,没有存储在内存中。(优化器将乘法替换为加法。)
英文:
Most likely no memory is used at all. If the arguments of sum()
are in registers at the time of the "call", then they will simply be added and the sum put in another register, or one of those registers if the contents are not needed after that.
For example, this:
inline int sum(int a, int b) {
return a + b;
}
int main(int argc, char **argv) {
(void)argv;
int a = argc;
int b = a * 5;
return sum(a, b);
}
Compiles to this:
_main: ; @main
.cfi_startproc
; %bb.0:
add w8, w0, w0, lsl #1
lsl w0, w8, #1
ret
.cfi_endproc
All done in the registers. Nothing stored in memory. (And the optimizer added instead of multiplied.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论