cmacro icon indicating copy to clipboard operation
cmacro copied to clipboard

Negation (!) in macroexpansion

Open maximvl opened this issue 8 years ago • 2 comments

Hi, I'm trying to write unless macro, but straightforward variant doesn't work:

macro unless {
  case {
    match {
      $(cond)
    }
    template {
      if(!$(cond))
    }
  }
}

#include <stdlib.h>
#include <stdio.h>

int main() {
  int x = 0;
  unless x {
    printf("unless works!\n");
  }
  exit(0);
}

results into:

 #include <stdlib.h>
 #include <stdio.h>
 int main () {
int x= 0; if (!$ (cond)) {
printf ("unless works!\n");
}
 exit (0);
}

where !$ (cond) is obviously not correct. btw inserting a space between ! and $ does the job.

maximvl avatar Dec 19 '15 12:12 maximvl

two lines need change

macro unless {
  case {
    match {
      $(cond)
    }
    template {
      if(! $(cond)) /*add a blank before $*/
    }
  }
}

#include <stdlib.h>
#include <stdio.h>

int main() {
  int x = 0;
  unless (x) { /*add a quote to warp the variable x*/
    printf("unless works!\n");
  }
  exit(0);
}

ukari avatar Dec 19 '15 17:12 ukari

well, you can also just change one line, no quote wrapping is ok

macro unless {
  case {
    match {
      $(cond)
    }
    template {
      if(! $(cond)) /*add a blank before $*/
    }
  }
}

#include <stdlib.h>
#include <stdio.h>

int main() {
  int x = 0;
  unless x {
    printf("unless works!\n");
  }
  exit(0);
}

ukari avatar Dec 19 '15 17:12 ukari