我一直在研究 Ruby,发现它的关键字“直到”和“除非”非常有趣。所以我想什么是在 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++ 中使用的类似技巧的引用资料,那就太好了。
最佳答案
Can anyone suggest a better alternative?
是的。根本不要这样做。直接使用 while
和 if
语句即可。
当您使用 C 或 C++ 编程时,请使用 C 或 C++ 编程。虽然 until
和 unless
在某些语言中可能经常使用且惯用语,但它们在 C 或 C++ 中却不是。
关于c++ - C/C++ 中的语法糖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5607253/