Passing "int" as an argument in a macro

This has been undermining me for a while, I came across this while solving some objective type questions in C.

#define SWAP(a,b,c) c t;t=a;a=b;b=t;

int main() {
    int x=10,y=20;
    SWAP(x,y,int);     
}

      

The code gives the correct answer: Working code

In C, we only have to pass the data type as an argument. This presumably works here, but I want to know how else. Two more questions related to this:

  • If I want to swap using pointers, will it work
  • Will this work if SWAP is defined as a function instead of a macro.
+3


source to share


2 answers


Macros are preprocessed before compilation, and you can practically write anything in the macros to be replaced. In function arguments, you cannot pass data types as arguments.

Side note:

#define SWAP(a,b,c) do { c t;t=a;a=b;b=t; } while(0)

      

- safer implementation of macros than the one you mentioned. Also, the name t is quite common. If the argument name is t, it won't work as expected, so it's better to choose some sparse name. Capital letters are usually preferred when defining macros.

for ex: #define SWAP(a,b,c) do { c MACRO_TEMP_;MACRO_TEMP_=a;a=b;b=MACRO_TEMP_; } while(0)



SWAP(x,y,int);

Becomes c t;t=a;a=b;b=t;

where all occurrences of c are replaced with int, a with x and b with y. Result:Γ¬nt t; t = x; x = y; y = t;

To understand macros better, you can see the preprocessed output of your code. Output on my computer:

$ cat q26727935.c
#define SWAP(a,b,c) c t;t=a;a=b;b=t;

int main() {
    int x=10,y=20;
    SWAP(x,y,int);     
}

$ gcc -E q26727935.c 
# 1 "q26727935.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "q26727935.c"


int main() {
    int x=10,y=20;
    int t;t=x;x=y;y=t;;
}
$ 

      

  • Macro is at the pre-processor stage, so swap will work even with pointers , although this is unnecessary.

  • In a function, you cannot pass the data type as arguments, so it won't work.

+4


source


  • Yes.
  • Not.

First of all, you should be aware that when you use macros, the argument will be replaced as it is. Thus, if you call SWAP (a, b, int *) it will be replaced with

int* t;t=a;a=b;b=t;

      



and then the code will be compiled.

But when you use functions, this will not happen, and you cannot pass the data type as an argument to the function.

+1


source







All Articles