我对内联函数有疑问。

huangapple go评论126阅读模式
英文:

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.)

huangapple
  • 本文由 发表于 2023年6月1日 13:11:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76378821.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定