-1
#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?

kaan
  • 35
  • 5
  • 2
    because `a` and `b` are not pointers, you are only swapping copies of `x` and `y`. – Pablo May 13 '23 at 22:05
  • 3
    Wouldn't you hope that the function behaved the same whether or not `INLINE` were added? – Scott Hunter May 13 '23 at 22:06
  • 1
    I think you are thinking of macros, see also https://stackoverflow.com/questions/13375288/inline-function-vs-macro-function – Pablo May 13 '23 at 22:09

2 Answers2

4

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.

Lundin
  • 195,001
  • 40
  • 254
  • 396
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.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312