Why macros and functions work differently about same code in c

I am new to programing, and I found one interesting but difficult to find reason problem, so I am writing this post.

I was trying to write swap function:

When I write swap function in traditional way,

void swap(int *x,int *y){int t=*x;*x=*y;*y=t;}

this function works and of course,

void swap(int x,int y){int t=x;x=y;x=t;}

does not work. but when I write swap as macro,

#define swap(x,y){int t=x;x=y;y=t;}

why the macro can swap value though they don’t use pointer?

>Solution :

why the macro can swap value though they don’t use pointer?

Because macros and functions work differently. Functions in C use "call by value" semantics: when you pass a variable as a parameter to a function, only the value of that variable gets sent to the function — the function can’t change the variable itself. We simulate "call by reference" semantics by passing a pointer to the variable that you want to change instead of the variable itself. It’s still call by value in the sense that the function still can’t change the thing that was passed in, i.e. the address, but it can change the value stored at that address, which is what we want.

A macro, on the other hand, is just a simple text substitution; there’s no function call at all. When you use the swap(x,y) macro, the preprocessor inserts the macro’s definition right there into that spot. It’s as if you had written {int t=x;x=y;y=t;} instead of swap(x,y). When that code runs, it can change the values of the variables.

Leave a Reply