c++ - C/C++ 中的语法糖

标签 c++ c syntax metaprogramming syntactic-sugar

我一直在研究 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?

是的。根本不要这样做。直接使用 whileif 语句即可。

当您使用 C 或 C++ 编程时,请使用 C 或 C++ 编程。虽然 untilunless 在某些语言中可能经常使用且惯用语,但它们在 C 或 C++ 中却不是。

关于c++ - C/C++ 中的语法糖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5607253/

相关文章:

C++:从重载函数到 std::function 的转换

c - C中的itoa使用Codeblocks导致段错误

c - 用 C 程序替换 pipe-shellscript

javascript - jQuery 将选择器转换为负数

c++ - 为什么我在编译 cilk 程序时得到 "error expected an expression"

c++ - 为什么并行读取大文本文件不好?

c++ - 一个类作为另一个类的数据成员

c - 如何保存返回结构体指针的函数

google-sheets - 如何在 Google Sheets 查询中从数组中选择特定列?

variables - 为什么修改未声明为可变的变量时编译器不报错?