gpt4 book ai didi

c - 有什么充分的理由不使用 'define' 和可变参数长度吗?

转载 作者:行者123 更新时间:2023-11-30 15:51:34 24 4
gpt4 key购买 nike

最近我发现了这段代码:

#define LOG(type, str)                      printf(str)
#define LOG1(type, str,arg1) printf(str,arg1)
#define LOG2(type, str,arg1,arg2) printf(str,arg1,arg2)
#define LOG3(type, str,arg1,arg2,arg3) printf(str,arg1,arg2,arg3)
#define LOG4(type, str,arg1,arg2,arg3,arg4) printf(str,arg1,arg2,arg3,arg4)

代码是最近写的。所以我猜它可以用C99编译。

我的问题是:为什么不使用参数长度可变的简单宏?我们只会将自己限制在 LOG 宏上,仅此而已。更不用说我们不必添加 LOG5LOG6 等。如果我们获得堆栈跟踪、内存不足等任何会发生的情况,会发生可怕的事情吗?让这个解决方案有用吗?

我是一个极简主义者,如果我们能得到更少的行就更好了。但我在这里错过了什么吗?这是故意的还是不好的编码习惯?

最佳答案

在我看来,预处理器对可变参数宏的支持是唯一好的理由。我们的项目 LOG、LOG1 等 已有数十年历史,但最近确实升级到了 ...

根据维基百科:

Several compilers support variable-argument macros when compiling C and C++ code: the GNU Compiler Collection 3.0,[2] Visual Studio 2005,[3] C++Builder 2006, and Oracle Solaris Studio (formerly Sun Studio) Forte Developer 6 update 2 (C++ version 5.3).[5] GCC also supports such macros when compiling Objective-C.

如果您了解自己的平台,请使用花哨的可变参数宏。如果支持的人很少,那么事情可能会变得更有趣

关于c - 有什么充分的理由不使用 'define' 和可变参数长度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15020298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com