【发布时间】:2011-04-07 12:15:40
【问题描述】:
我正在对一些代码进行逆向工程并遇到了这个......
/************************************************************************/
/* */
/* MACRO CHECK_FREAD */
/* */
/* CHECK_FREAD is used to check the status of a file read. It */
/* is passed the return code from read and a string to print out if */
/* an error is detected. If an error is found, an error message is */
/* printed out and the program terminates. This was made into a */
/* macro because it had to be done over and over and over . . . */
/* */
/************************************************************************/
#define CHECK_FREAD(X, msg) if (X==-1) \
{ \
return(DCD_BADREAD); \
}
基本上,此文件中的特定函数集在执行 (c-read) 以检查结果是否有错误时调用此函数。他们也对 EOF 进行了类似的检查...基本上据我所知,他们这样做是为了在函数中间的很多地方插入错误返回。
例如
/* Read in an 4 */
ret_val = read(fd, &input_integer, sizeof(int32));
CHECK_FREAD(ret_val, "reading an 4");
CHECK_FEOF(ret_val, "reading an 4");
if (input_integer != 4)
{
return(DCD_BADFORMAT);
}
/* Read in the number of atoms */
ret_val = read(fd, &input_integer, sizeof(int32));
*N = input_integer;
CHECK_FREAD(ret_val, "reading number of atoms");
CHECK_FEOF(ret_val, "reading number of atoms");
现在我才刚刚回到 c/c++ 编程领域,而且我一开始就很少使用宏,但是这种宏是滥用吗?
我读到了... When are C++ macros beneficial?
...听起来不像任何犹太洁食的例子,所以我的猜测是“是”。但我想获得更明智的意见,而不仅仅是做出有根据的猜测...... :)
...errr,使用某种包装不是更好吗?
【问题讨论】:
-
此宏不会按照 cmets 中的描述打印错误消息。这是完整的代码吗?
-
是的,这是完整的代码。对于 ChrisF,请参阅我添加的示例。
-
为什么不使用'msg'参数?注释与实现不匹配,这意味着至少有一个是错误的,但可能两者都有。最好编写一个
size_t checked_fread(void *buffer, size_t itemsize, size_t numitems, FILE *fp, const char *msg)函数并始终如一地使用它。推测它为什么检查 -1 也很有趣;fread()返回 0 或错误计数 - 返回类型为size_t,几乎所有目的都排除了 -1 的返回值。 -
但这算不算滥用?那是我的问题。 @Jonathan我不知道他们为什么不使用味精......健忘?懒惰?困惑?你选!但你说得对,这很奇怪....
-
他们可能在测试代码时使用了 msg 属性,并在发布之前拿走了打印代码。我最初认为它是一种在代码中插入 cmets 的方法,但为什么不改用诚实的 /* cmets */ 呢?
标签: c file-io macros coding-style