Home > other >  swap using a macro in c but there is an error
swap using a macro in c but there is an error

Time:08-10

i am trying to understand macro in c. i had found this program as a question to extract the error obviously it need to swap the numbers using exclusive or (i can not also understand why using xor to swap)

#include <stdio.h>
#include <stdlib.h>
#define SWAP(a, b) { a ^= b; b ^= a; a ^= b;}
int main(void) {
int x = 10;
int y = 5;
int z = 4;
if (x < 0)
 SWAP(x, y);
else
 SWAP(x, z);
}

the compiler popped an error to include if before else. but obviously there is an if before else i want to understand the reason behind this.

CodePudding user response:

The problem is the ; after SWAP(x, y).

Once the macro substitution is performed by the preprocessor, here's what the code looks like (with the ; moved to a separate line for illustrative purposes):

if (x < 0)
 { x ^= y; y ^= x; x ^= y;}
 ;
else
 { x ^= z; z ^= x; x ^= z;}
 ;

The block in { } after the if is valid, and technically so is it the ;, but it makes the else invalid syntax.

As the comments indicate, the best fix is to remove the ;, but also put the if/else blocks in braces, like this:

if (x < 0) {
 SWAP(x, y)
} else {
 SWAP(x, z)
}

CodePudding user response:

The issue is caused by a semicolon after closing braces:

{ ... };
       ^ here

The C grammar does not allow that. The solution is using do {} while (0) trick. Which a dummy loop that is always executed once and it allows a semicolon after it.

Just define your macro as:

#define SWAP(a, b) do { a ^= b; b ^= a; a ^= b;} while (0)
  •  Tags:  
  • c
  • Related