我一直在研究Ruby,发现它的关键字"until"和"unless"非常有趣。因此,我想知道如何在C/C++中添加类似的关键字。以下是我的想法:
#define until(x) while(!(x))
#define unless(x) if(!(x))
我希望能够得到一些建议。有没有人能够提供更好的替代方案?
这是一个我编写的程序示例,用于说明我的意图:
#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;
}
如果您能指出一些类似的技巧,可以在C或C++中使用,那将是很棒的。
sugar.h
的文件包含类似于Pascal的定义... - mbxelse
子句中使用unless
(然而,在Lisp中,我很喜欢when/unless
)。我对使用until
循环也没有什么特别的印象,可能是因为我以前从未使用过。 - 6502