交换操作与内联函数

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

Swap operation with inline function

问题

#define INLINE static inline __attribute__((always_inline)) 

INLINE void swap(int a, int b){
	int tmp = a;
	a = b;
	b = tmp;
}


int main(){
	int x = 10;
    int y = 20;
	swap(x, y);
	printf("x:%d y:%d", x, y);
	return 0;
}
output: x:10 y:20

如果内联函数被插入到它们被调用的地方,为什么这个函数不会给出正确的结果?

英文:
#define INLINE static inline __attribute__((always_inline)) 

INLINE void swap(int a, int b){
	int tmp = a;
	a = b;
	b = tmp;
}


int main(){
	int x = 10;
    int y = 20;
	swap(x, y);
	printf("x:%d y:%d", x, y);
	return 0;
}
output: x:10 y:20

If inline functions are insert to the function they are called, why does this function not give correct results?

答案1

得分: 4

你需要像写普通函数一样编写它。即:

static inline void swap(int* a, int* b){
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

然后就交给编译器处理吧。它会将指针的间接寻址作为内联的一部分进行优化。

你编写的函数没有副作用,所以编译器会将其视为一个巨大的空操作并完全删除它。

英文:

You'll have to write it just like you would write an ordinary function. That is:

static inline void swap(int* a, int* b){
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

And leave it to the compiler from there. It will optimize out the indirect addressing with pointers as part of the inlining.

The function you wrote has no side effects and so the compiler will just regard it as one big no-op and remove it entirely.

答案2

得分: 2

如果内联函数插入到调用它们的函数中,为什么这个函数不能给出正确的结果?

内联函数不会改变语义(源代码的含义和程序行为规则)。内联函数的参数仍然是独立的变量,初始化为参数值的副本。内联不会使它们成为调用函数的一部分。

英文:

> If inline functions are insert to the function they are called, why does this function not give correct results?

Inlining a function does not change the semantics (the meaning of the source code and the rules about how the program behaves). The parameters of the inline function are still separate variables, initialized as copies of the argument values. Inlining does not make them part of the calling function.

huangapple
  • 本文由 发表于 2023年5月14日 06:04:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76245058.html
匿名

发表评论

匿名网友

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

确定