Syntactic sugar in C/C++

BiGYaN picture BiGYaN · Apr 9, 2011 · Viewed 12.1k times · Source

I have been looking into Ruby and find its keywords "until" and "unless" very interesting. So I thought what was a good way to add similar keywords into C/C++. This is what I came up with:

#define until(x)    while(!(x))
#define unless(x)   if(!(x))

I am looking for some suggestions on this. Can anyone suggest a better alternative?

Here is an example of a program that I wrote to illustrate what I intended to do:

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

#define until(x)    while(!(x))
#define unless(x)   if(!(x))

unsigned int factorial(unsigned int n) {
    unsigned int fact=1, i;
    until ( n==0 )
        fact *= n--;
    return fact;    
}

int main(int argc, char*argv[]) {
    unless (argc==2)
        puts("Usage: fact <num>");
    else {
        int n = atoi(argv[1]);
        if (n<0)
            puts("please give +ve number");
        else
            printf("factorial(%u) = %u\n",n,factorial(n));
    }
    return 0;
}

It would be great if you could point me to some references for similar tricks that can be employed in C or C++.

Answer

James McNellis picture James McNellis · Apr 9, 2011

Can anyone suggest a better alternative?

Yes. Don't do this at all. Just use the while and if statements directly.

When you're programming in C or C++, program in C or C++. While until and unless might be used frequently and idiomatic in some languages, they are not in C or C++.