Swap operation with inline function

116 Views Asked by At
#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?

2

There are 2 best solutions below

0
Lundin On

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.

0
Eric Postpischil On

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.